Compare commits
42 Commits
c94f5bdb45
...
feature/mq
| Author | SHA1 | Date | |
|---|---|---|---|
| bd257b89f0 | |||
| 4debbfb39e | |||
| d83189417a | |||
| 3c92cf0c26 | |||
|
96023c8dc3
|
|||
|
7497a8c05d
|
|||
|
d3d8d829be
|
|||
|
6889ba4561
|
|||
|
18095349f3
|
|||
|
3d8fd893f5
|
|||
|
1bea7ef2f4
|
|||
|
f5b9674840
|
|||
|
6f22881007
|
|||
|
1d8af1b6c4
|
|||
|
2c532359fc
|
|||
|
53819484fb
|
|||
|
1151d099cf
|
|||
|
3feaacd460
|
|||
|
e15e78cc26
|
|||
|
d9aa96a3cb
|
|||
|
ecf989b859
|
|||
|
db401aac55
|
|||
| ecb7707357 | |||
|
4cf7a1c94f
|
|||
|
9155676e06
|
|||
|
e05f3d768f
|
|||
| cf58486cf5 | |||
| cfe23c8a09 | |||
| 3d18b0dbf6 | |||
| 7ebc147f51 | |||
| f0bda32d7a | |||
| 76f59b093d | |||
| 7fc8d0c882 | |||
| 6d5bb5b966 | |||
| 336961f0a0 | |||
| e20b474dfd | |||
| 5b009f50e5 | |||
| d010c5d12a | |||
| b594a02870 | |||
| 1f3349c348 | |||
| 5b0e2b6797 | |||
| 1791f463b7 |
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" "$@"
|
||||||
@@ -24,6 +24,8 @@ CHRONO_TZ_TIMEZONE_FILTER = "UTC|America/New_York|America/Chicago|America/Los_An
|
|||||||
CARGO_WORKSPACE_DIR = { value = "", relative = true }
|
CARGO_WORKSPACE_DIR = { value = "", relative = true }
|
||||||
ESP_LOG = "info"
|
ESP_LOG = "info"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[unstable]
|
[unstable]
|
||||||
build-std = ["alloc", "core"]
|
build-std = ["alloc", "core"]
|
||||||
|
|
||||||
|
|||||||
4
rust/.idea/dictionaries/project.xml
generated
4
rust/.idea/dictionaries/project.xml
generated
@@ -1,14 +1,18 @@
|
|||||||
<component name="ProjectDictionaryState">
|
<component name="ProjectDictionaryState">
|
||||||
<dictionary name="project">
|
<dictionary name="project">
|
||||||
<words>
|
<words>
|
||||||
|
<w>boardtest</w>
|
||||||
<w>buildtime</w>
|
<w>buildtime</w>
|
||||||
<w>deepsleep</w>
|
<w>deepsleep</w>
|
||||||
<w>githash</w>
|
<w>githash</w>
|
||||||
|
<w>lamptest</w>
|
||||||
<w>lightstate</w>
|
<w>lightstate</w>
|
||||||
<w>mppt</w>
|
<w>mppt</w>
|
||||||
<w>plantstate</w>
|
<w>plantstate</w>
|
||||||
|
<w>pumptest</w>
|
||||||
<w>sntp</w>
|
<w>sntp</w>
|
||||||
<w>vergen</w>
|
<w>vergen</w>
|
||||||
|
<w>wifiscan</w>
|
||||||
</words>
|
</words>
|
||||||
</dictionary>
|
</dictionary>
|
||||||
</component>
|
</component>
|
||||||
@@ -7,5 +7,6 @@
|
|||||||
</Languages>
|
</Languages>
|
||||||
</inspection_tool>
|
</inspection_tool>
|
||||||
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
|
||||||
|
<inspection_tool class="NewCrateVersionAvailable" enabled="true" level="INFORMATION" enabled_by_default="true" />
|
||||||
</profile>
|
</profile>
|
||||||
</component>
|
</component>
|
||||||
2931
rust/Cargo.lock
generated
Normal file
2931
rust/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
137
rust/Cargo.toml
137
rust/Cargo.toml
@@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
[package]
|
[package]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
name = "plant-ctrl2"
|
name = "plant-ctrl2"
|
||||||
@@ -26,113 +27,74 @@ command = [
|
|||||||
"partitions.csv"
|
"partitions.csv"
|
||||||
]
|
]
|
||||||
|
|
||||||
|
#this strips the bootloader, we need that tho
|
||||||
|
#strip = true
|
||||||
|
|
||||||
[profile.dev]
|
[profile.dev]
|
||||||
lto = true
|
lto = "fat"
|
||||||
strip = false
|
|
||||||
debug = false
|
debug = false
|
||||||
overflow-checks = true
|
overflow-checks = true
|
||||||
panic = "abort"
|
panic = "abort"
|
||||||
incremental = true
|
incremental = true
|
||||||
opt-level = 3
|
opt-level = "z"
|
||||||
|
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
# Explicitly disable LTO which the Xtensa codegen backend has issues
|
lto = "fat"
|
||||||
lto = true
|
#debug = false
|
||||||
strip = true
|
|
||||||
debug = false
|
|
||||||
overflow-checks = true
|
overflow-checks = true
|
||||||
panic = "abort"
|
panic = "abort"
|
||||||
incremental = true
|
incremental = false
|
||||||
opt-level = 3
|
opt-level = "z"
|
||||||
|
|
||||||
|
|
||||||
[package.metadata.espflash]
|
[package.metadata.espflash]
|
||||||
partition_table = "partitions.csv"
|
partition_table = "partitions.csv"
|
||||||
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
#ESP stuff
|
#ESP stuff
|
||||||
esp-bootloader-esp-idf = { version = "0.2.0", features = ["esp32c6"] }
|
log = "0.4.28"
|
||||||
esp-hal = { version = "=1.0.0-rc.0", features = [
|
esp-bootloader-esp-idf = { version = "0.5.0", features = ["esp32c6", "log-04"] }
|
||||||
"esp32c6",
|
esp-hal = { version = "1.1.0", features = ["esp32c6", "log-04"] }
|
||||||
"log-04",
|
esp-rtos = { version = "0.3.0", features = ["esp32c6", "embassy", "esp-radio"] }
|
||||||
"unstable",
|
esp-backtrace = { version = "0.19.0", features = ["esp32c6", "panic-handler", "println", "colors", "custom-halt"] }
|
||||||
"rt"
|
esp-println = { version = "0.17.0", features = ["esp32c6", "log-04", "auto"] }
|
||||||
] }
|
esp-storage = { version = "0.9.0", features = ["esp32c6"] }
|
||||||
log = "0.4.27"
|
esp-radio = { version = "0.18.0", features = ["esp32c6", "log-04", "wifi", "unstable"] }
|
||||||
|
esp-alloc = { version = "0.10.0", features = ["esp32c6", "internal-heap-stats"] }
|
||||||
|
|
||||||
embassy-net = { version = "0.7.0", features = [
|
# Async runtime (Embassy core)
|
||||||
"dhcpv4",
|
embassy-executor = { version = "0.10.0", features = ["log", "nightly"] }
|
||||||
"log",
|
embassy-time = { version = "0.5.1", features = ["log"], default-features = false }
|
||||||
"medium-ethernet",
|
embassy-sync = { version = "0.8.0", features = ["log"] }
|
||||||
"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-131072"
|
|
||||||
] }
|
|
||||||
embassy-time = { version = "0.5.0", features = ["log"] }
|
|
||||||
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 = [
|
# Networking and protocol stacks
|
||||||
"builtin-scheduler",
|
embassy-net = { version = "0.8.0", features = ["dhcpv4", "log", "medium-ethernet", "tcp", "udp", "proto-ipv4", "dns", "proto-ipv6"] }
|
||||||
"esp-alloc",
|
sntpc = { version = "0.6.1", default-features = false, features = ["log", "embassy-socket", "embassy-socket-ipv6"] }
|
||||||
"esp32c6",
|
edge-dhcp = "0.7.0"
|
||||||
"log-04",
|
edge-nal = "0.6.0"
|
||||||
"smoltcp",
|
edge-nal-embassy = "0.8.1"
|
||||||
"wifi",
|
edge-http = { version = "0.7.0", features = ["log"] }
|
||||||
] }
|
|
||||||
smoltcp = { version = "0.12.0", default-features = false, features = [
|
esp32c6 = { version = "0.23.2" }
|
||||||
"alloc",
|
|
||||||
"log",
|
# Hardware abstraction traits and HAL adapters
|
||||||
"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"
|
embedded-hal = "1.0.0"
|
||||||
heapless = { version = "0.8", features = ["serde"] }
|
embedded-storage = "0.3.1"
|
||||||
embedded-hal-bus = { version = "0.3.0" }
|
embassy-embedded-hal = "0.6.0"
|
||||||
|
nb = "1.1.0"
|
||||||
|
|
||||||
#Hardware additional driver
|
#Hardware additional driver
|
||||||
#ds18b20 = "0.1.1"
|
|
||||||
#bq34z100 = { version = "0.3.0", default-features = false }
|
|
||||||
one-wire-bus = "0.1.1"
|
|
||||||
ds323x = "0.6.0"
|
|
||||||
|
|
||||||
#pure code dependencies
|
#bq34z100 = { version = "0.3.0", default-features = false }
|
||||||
#once_cell = "1.19.0"
|
lib-bms-protocol = { git = "https://gitea.wlandt.de/judge/ch32-bms.git", default-features = false }
|
||||||
anyhow = { version = "1.0.75", default-features = false }
|
onewire = "0.4.0"
|
||||||
#strum = { version = "0.27.0", default-feature = false, features = ["derive"] }
|
#strum = { version = "0.27.0", default-feature = false, features = ["derive"] }
|
||||||
measurements = "0.11.0"
|
ds323x = "0.6.0"
|
||||||
|
|
||||||
#json
|
#json
|
||||||
serde = { version = "1.0.219", features = ["derive", "alloc"], default-features = false }
|
serde = { version = "1.0.219", features = ["derive", "alloc"], default-features = false }
|
||||||
serde_json = { version = "1.0.143", default-features = false, features = ["alloc"] }
|
serde_json = { version = "1.0.143", default-features = false, features = ["alloc"] }
|
||||||
|
|
||||||
#timezone
|
|
||||||
chrono = { version = "0.4.42", default-features = false, features = ["iana-time-zone", "alloc", "serde"] }
|
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"] }
|
chrono-tz = { version = "0.10.4", default-features = false, features = ["filter-by-regex"] }
|
||||||
eeprom24x = "0.7.2"
|
eeprom24x = "0.7.2"
|
||||||
@@ -141,21 +103,20 @@ strum_macros = "0.27.0"
|
|||||||
unit-enum = "1.4.1"
|
unit-enum = "1.4.1"
|
||||||
pca9535 = { version = "2.0.0" }
|
pca9535 = { version = "2.0.0" }
|
||||||
ina219 = { version = "0.2.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"
|
portable-atomic = "1.11.1"
|
||||||
embassy-sync = { version = "0.7.2", features = ["log"] }
|
|
||||||
async-trait = "0.1.89"
|
async-trait = "0.1.89"
|
||||||
bq34z100 = { version = "0.4.0", default-features = false }
|
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"
|
static_cell = "2.1.1"
|
||||||
edge-http = { version = "0.6.1", features = ["log"] }
|
|
||||||
littlefs2 = { version = "0.6.1", features = ["c-stubs", "alloc"] }
|
littlefs2 = { version = "0.6.1", features = ["c-stubs", "alloc"] }
|
||||||
littlefs2-core = "0.1.1"
|
littlefs2-core = "0.1.1"
|
||||||
bytemuck = { version = "1.23.2", features = ["derive", "min_const_generics", "pod_saturating", "extern_crate_alloc"] }
|
bytemuck = { version = "1.23.2", features = ["derive", "min_const_generics", "pod_saturating", "extern_crate_alloc"] }
|
||||||
|
deranged = "0.5.3"
|
||||||
|
bincode = { version = "2.0.1", default-features = false, features = ["derive"] }
|
||||||
|
option-lock = { version = "0.3.1", default-features = false }
|
||||||
|
measurements = "0.11.1"
|
||||||
|
heapless = { version = "0.7.17", features = ["serde"] }
|
||||||
|
mcutie = { path = "./src/mcutie_3_0_0/", default-features = false, features = ["log"] }
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
|
|||||||
BIN
rust/bootloader.bin
Normal file
BIN
rust/bootloader.bin
Normal file
Binary file not shown.
@@ -58,7 +58,7 @@ fn main() {
|
|||||||
fn webpack() {
|
fn webpack() {
|
||||||
//println!("cargo:rerun-if-changed=./src/src_webpack");
|
//println!("cargo:rerun-if-changed=./src/src_webpack");
|
||||||
Command::new("rm")
|
Command::new("rm")
|
||||||
.arg("./src/webserver/bundle.js")
|
.arg("./src/webserver/bundle.js.gz")
|
||||||
.output()
|
.output()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@@ -81,14 +81,14 @@ fn webpack() {
|
|||||||
let _ = Command::new("cmd")
|
let _ = Command::new("cmd")
|
||||||
.arg("/K")
|
.arg("/K")
|
||||||
.arg("move")
|
.arg("move")
|
||||||
.arg("./src_webpack/bundle.js")
|
.arg("./src_webpack/bundle.js.gz")
|
||||||
.arg("./src/webserver")
|
.arg("./src/webserver")
|
||||||
.output()
|
.output()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let _ = Command::new("cmd")
|
let _ = Command::new("cmd")
|
||||||
.arg("/K")
|
.arg("/K")
|
||||||
.arg("move")
|
.arg("move")
|
||||||
.arg("./src_webpack/index.html")
|
.arg("./src_webpack/index.html.gz")
|
||||||
.arg("./src/webserver")
|
.arg("./src/webserver")
|
||||||
.output()
|
.output()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -107,12 +107,12 @@ fn webpack() {
|
|||||||
|
|
||||||
// move webpack results to rust webserver src
|
// move webpack results to rust webserver src
|
||||||
let _ = Command::new("mv")
|
let _ = Command::new("mv")
|
||||||
.arg("./src_webpack/bundle.js")
|
.arg("./src_webpack/bundle.js.gz")
|
||||||
.arg("./src/webserver")
|
.arg("./src/webserver")
|
||||||
.output()
|
.output()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let _ = Command::new("mv")
|
let _ = Command::new("mv")
|
||||||
.arg("./src_webpack/index.html")
|
.arg("./src_webpack/index.html.gz")
|
||||||
.arg("./src/webserver")
|
.arg("./src/webserver")
|
||||||
.output()
|
.output()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -1,3 +1,2 @@
|
|||||||
[toolchain]
|
[toolchain]
|
||||||
channel = "nightly"
|
channel = "nightly"
|
||||||
toolchain = "esp"
|
|
||||||
|
|||||||
@@ -1,434 +0,0 @@
|
|||||||
use crate::hal::rtc::RTCModuleInteraction;
|
|
||||||
use crate::hal::water::TankSensor;
|
|
||||||
use crate::hal::{
|
|
||||||
deep_sleep, BoardInteraction, FreePeripherals, Sensor, PLANT_COUNT,
|
|
||||||
};
|
|
||||||
use crate::log::{log, LogMessage};
|
|
||||||
use crate::{
|
|
||||||
config::PlantControllerConfig,
|
|
||||||
hal::{battery::BatteryInteraction, esp::Esp},
|
|
||||||
};
|
|
||||||
use anyhow::{bail, Ok, Result};
|
|
||||||
use embedded_hal::digital::OutputPin;
|
|
||||||
use measurements::{Current, Voltage};
|
|
||||||
use plant_ctrl2::sipo::ShiftRegister40;
|
|
||||||
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;
|
|
||||||
const PUMP2_BIT: usize = 2;
|
|
||||||
const PUMP3_BIT: usize = 3;
|
|
||||||
const PUMP4_BIT: usize = 4;
|
|
||||||
const PUMP5_BIT: usize = 5;
|
|
||||||
const PUMP6_BIT: usize = 6;
|
|
||||||
const PUMP7_BIT: usize = 7;
|
|
||||||
const MS_0: usize = 8;
|
|
||||||
const MS_4: usize = 9;
|
|
||||||
const MS_2: usize = 10;
|
|
||||||
const MS_3: usize = 11;
|
|
||||||
const MS_1: usize = 13;
|
|
||||||
const SENSOR_ON: usize = 12;
|
|
||||||
|
|
||||||
const SENSOR_A_1: u8 = 7;
|
|
||||||
const SENSOR_A_2: u8 = 6;
|
|
||||||
const SENSOR_A_3: u8 = 5;
|
|
||||||
const SENSOR_A_4: u8 = 4;
|
|
||||||
const SENSOR_A_5: u8 = 3;
|
|
||||||
const SENSOR_A_6: u8 = 2;
|
|
||||||
const SENSOR_A_7: u8 = 1;
|
|
||||||
const SENSOR_A_8: u8 = 0;
|
|
||||||
|
|
||||||
const SENSOR_B_1: u8 = 8;
|
|
||||||
const SENSOR_B_2: u8 = 9;
|
|
||||||
const SENSOR_B_3: u8 = 10;
|
|
||||||
const SENSOR_B_4: u8 = 11;
|
|
||||||
const SENSOR_B_5: u8 = 12;
|
|
||||||
const SENSOR_B_6: u8 = 13;
|
|
||||||
const SENSOR_B_7: u8 = 14;
|
|
||||||
const SENSOR_B_8: u8 = 15;
|
|
||||||
|
|
||||||
const CHARGING: usize = 14;
|
|
||||||
const AWAKE: usize = 15;
|
|
||||||
|
|
||||||
const FAULT_3: usize = 16;
|
|
||||||
const FAULT_8: usize = 17;
|
|
||||||
const FAULT_7: usize = 18;
|
|
||||||
const FAULT_6: usize = 19;
|
|
||||||
const FAULT_5: usize = 20;
|
|
||||||
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>,
|
|
||||||
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:
|
|
||||||
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Output>,
|
|
||||||
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>,
|
|
||||||
general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
|
||||||
signal_counter: PcntDriver<'a>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn create_v3(
|
|
||||||
peripherals: FreePeripherals,
|
|
||||||
esp: Esp<'static>,
|
|
||||||
config: PlantControllerConfig,
|
|
||||||
battery_monitor: Box<dyn BatteryInteraction + 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())?;
|
|
||||||
latch.set_pull(Pull::Floating)?;
|
|
||||||
let mut data = PinDriver::input_output(peripherals.gpio23.downgrade())?;
|
|
||||||
data.set_pull(Pull::Floating)?;
|
|
||||||
let shift_register = ShiftRegister40::new(clock, latch, data);
|
|
||||||
//disable all
|
|
||||||
for mut pin in shift_register.decompose() {
|
|
||||||
pin.set_low()?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let awake = &mut shift_register.decompose()[AWAKE];
|
|
||||||
awake.set_high()?;
|
|
||||||
|
|
||||||
let charging = &mut shift_register.decompose()[CHARGING];
|
|
||||||
charging.set_high()?;
|
|
||||||
|
|
||||||
let ms0 = &mut shift_register.decompose()[MS_0];
|
|
||||||
ms0.set_low()?;
|
|
||||||
let ms1 = &mut shift_register.decompose()[MS_1];
|
|
||||||
ms1.set_low()?;
|
|
||||||
let ms2 = &mut shift_register.decompose()[MS_2];
|
|
||||||
ms2.set_low()?;
|
|
||||||
let ms3 = &mut shift_register.decompose()[MS_3];
|
|
||||||
ms3.set_low()?;
|
|
||||||
|
|
||||||
let ms4 = &mut shift_register.decompose()[MS_4];
|
|
||||||
ms4.set_high()?;
|
|
||||||
|
|
||||||
let one_wire_pin = peripherals.gpio18.downgrade();
|
|
||||||
let tank_power_pin = peripherals.gpio11.downgrade();
|
|
||||||
|
|
||||||
let flow_sensor_pin = peripherals.gpio4.downgrade();
|
|
||||||
|
|
||||||
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,
|
|
||||||
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 mut solar_is_day = PinDriver::input(peripherals.gpio7.downgrade())?;
|
|
||||||
solar_is_day.set_pull(Pull::Floating)?;
|
|
||||||
|
|
||||||
let mut light = PinDriver::input_output(peripherals.gpio10.downgrade())?;
|
|
||||||
light.set_pull(Pull::Floating)?;
|
|
||||||
|
|
||||||
let mut main_pump = PinDriver::input_output(peripherals.gpio2.downgrade())?;
|
|
||||||
main_pump.set_pull(Pull::Floating)?;
|
|
||||||
main_pump.set_low()?;
|
|
||||||
|
|
||||||
let mut general_fault = PinDriver::input_output(peripherals.gpio6.downgrade())?;
|
|
||||||
general_fault.set_pull(Pull::Floating)?;
|
|
||||||
general_fault.set_low()?;
|
|
||||||
|
|
||||||
let mut shift_register_enable_invert = PinDriver::output(peripherals.gpio21.downgrade())?;
|
|
||||||
|
|
||||||
unsafe { gpio_hold_dis(shift_register_enable_invert.pin()) };
|
|
||||||
shift_register_enable_invert.set_low()?;
|
|
||||||
unsafe { gpio_hold_en(shift_register_enable_invert.pin()) };
|
|
||||||
|
|
||||||
Ok(Box::new(V3 {
|
|
||||||
config,
|
|
||||||
battery_monitor,
|
|
||||||
rtc_module,
|
|
||||||
esp,
|
|
||||||
shift_register,
|
|
||||||
_shift_register_enable_invert: shift_register_enable_invert,
|
|
||||||
tank_sensor,
|
|
||||||
solar_is_day,
|
|
||||||
light,
|
|
||||||
main_pump,
|
|
||||||
general_fault,
|
|
||||||
signal_counter,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> BoardInteraction<'a> for V3<'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
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_config(&mut self) -> &PlantControllerConfig {
|
|
||||||
&self.config
|
|
||||||
}
|
|
||||||
|
|
||||||
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())?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
|
|
||||||
let _ = self.shift_register.decompose()[AWAKE].set_low();
|
|
||||||
deep_sleep(duration_in_ms)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_day(&self) -> bool {
|
|
||||||
self.solar_is_day.get_level().into()
|
|
||||||
}
|
|
||||||
|
|
||||||
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()?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let index = match plant {
|
|
||||||
0 => PUMP1_BIT,
|
|
||||||
1 => PUMP2_BIT,
|
|
||||||
2 => PUMP3_BIT,
|
|
||||||
3 => PUMP4_BIT,
|
|
||||||
4 => PUMP5_BIT,
|
|
||||||
5 => PUMP6_BIT,
|
|
||||||
6 => PUMP7_BIT,
|
|
||||||
7 => PUMP8_BIT,
|
|
||||||
_ => bail!("Invalid pump {plant}",),
|
|
||||||
};
|
|
||||||
self.shift_register.decompose()[index].set_state(enable.into())?;
|
|
||||||
|
|
||||||
if !enable {
|
|
||||||
self.main_pump.set_low()?;
|
|
||||||
}
|
|
||||||
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,
|
|
||||||
1 => FAULT_2,
|
|
||||||
2 => FAULT_3,
|
|
||||||
3 => FAULT_4,
|
|
||||||
4 => FAULT_5,
|
|
||||||
5 => FAULT_6,
|
|
||||||
6 => FAULT_7,
|
|
||||||
7 => FAULT_8,
|
|
||||||
_ => panic!("Invalid plant id {}", plant),
|
|
||||||
};
|
|
||||||
self.shift_register.decompose()[index].set_state(enable.into())?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> 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.shift_register.decompose()[MS_4].set_high()?;
|
|
||||||
|
|
||||||
let sensor_channel = match sensor {
|
|
||||||
Sensor::A => match plant {
|
|
||||||
0 => SENSOR_A_1,
|
|
||||||
1 => SENSOR_A_2,
|
|
||||||
2 => SENSOR_A_3,
|
|
||||||
3 => SENSOR_A_4,
|
|
||||||
4 => SENSOR_A_5,
|
|
||||||
5 => SENSOR_A_6,
|
|
||||||
6 => SENSOR_A_7,
|
|
||||||
7 => SENSOR_A_8,
|
|
||||||
_ => bail!("Invalid plant id {}", plant),
|
|
||||||
},
|
|
||||||
Sensor::B => match plant {
|
|
||||||
0 => SENSOR_B_1,
|
|
||||||
1 => SENSOR_B_2,
|
|
||||||
2 => SENSOR_B_3,
|
|
||||||
3 => SENSOR_B_4,
|
|
||||||
4 => SENSOR_B_5,
|
|
||||||
5 => SENSOR_B_6,
|
|
||||||
6 => SENSOR_B_7,
|
|
||||||
7 => SENSOR_B_8,
|
|
||||||
_ => bail!("Invalid plant id {}", plant),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let is_bit_set = |b: u8| -> bool { sensor_channel & (1 << b) != 0 };
|
|
||||||
let pin_0 = &mut self.shift_register.decompose()[MS_0];
|
|
||||||
let pin_1 = &mut self.shift_register.decompose()[MS_1];
|
|
||||||
let pin_2 = &mut self.shift_register.decompose()[MS_2];
|
|
||||||
let pin_3 = &mut self.shift_register.decompose()[MS_3];
|
|
||||||
if is_bit_set(0) {
|
|
||||||
pin_0.set_high()?;
|
|
||||||
} else {
|
|
||||||
pin_0.set_low()?;
|
|
||||||
}
|
|
||||||
if is_bit_set(1) {
|
|
||||||
pin_1.set_high()?;
|
|
||||||
} else {
|
|
||||||
pin_1.set_low()?;
|
|
||||||
}
|
|
||||||
if is_bit_set(2) {
|
|
||||||
pin_2.set_high()?;
|
|
||||||
} else {
|
|
||||||
pin_2.set_low()?;
|
|
||||||
}
|
|
||||||
if is_bit_set(3) {
|
|
||||||
pin_3.set_high()?;
|
|
||||||
} else {
|
|
||||||
pin_3.set_low()?;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.shift_register.decompose()[MS_4].set_low()?;
|
|
||||||
self.shift_register.decompose()[SENSOR_ON].set_high()?;
|
|
||||||
|
|
||||||
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);
|
|
||||||
self.signal_counter.counter_resume()?;
|
|
||||||
self.esp.delay.delay_ms(measurement);
|
|
||||||
self.signal_counter.counter_pause()?;
|
|
||||||
self.shift_register.decompose()[MS_4].set_high()?;
|
|
||||||
self.shift_register.decompose()[SENSOR_ON].set_low()?;
|
|
||||||
self.esp.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];
|
|
||||||
Ok(median)
|
|
||||||
}
|
|
||||||
|
|
||||||
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()) };
|
|
||||||
}
|
|
||||||
|
|
||||||
fn test(&mut self) -> Result<()> {
|
|
||||||
self.general_fault(true);
|
|
||||||
self.esp.delay.delay_ms(100);
|
|
||||||
self.general_fault(false);
|
|
||||||
self.esp.delay.delay_ms(100);
|
|
||||||
self.light(true)?;
|
|
||||||
self.esp.delay.delay_ms(500);
|
|
||||||
self.light(false)?;
|
|
||||||
self.esp.delay.delay_ms(500);
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
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);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
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,440 +0,0 @@
|
|||||||
use crate::config::PlantControllerConfig;
|
|
||||||
use crate::hal::battery::BatteryInteraction;
|
|
||||||
use crate::hal::esp::Esp;
|
|
||||||
use crate::hal::rtc::RTCModuleInteraction;
|
|
||||||
use crate::hal::v4_sensor::SensorImpl;
|
|
||||||
use crate::hal::v4_sensor::SensorInteraction;
|
|
||||||
use crate::hal::water::TankSensor;
|
|
||||||
use crate::hal::{
|
|
||||||
deep_sleep, BoardInteraction, FreePeripherals, Sensor, I2C_DRIVER, PLANT_COUNT
|
|
||||||
};
|
|
||||||
use crate::log::{log, LogMessage};
|
|
||||||
use anyhow::bail;
|
|
||||||
use embedded_hal::digital::OutputPin;
|
|
||||||
use embedded_hal_bus::i2c::MutexDevice;
|
|
||||||
use ina219::address::{Address, Pin};
|
|
||||||
use ina219::calibration::UnCalibrated;
|
|
||||||
use ina219::configuration::{Configuration, OperatingMode};
|
|
||||||
use ina219::SyncIna219;
|
|
||||||
use measurements::{Current, Resistance, Voltage};
|
|
||||||
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
|
||||||
use std::result::Result::Ok as OkStd;
|
|
||||||
use embedded_can::Frame;
|
|
||||||
use embedded_can::StandardId;
|
|
||||||
use alloc::string::ToString;
|
|
||||||
use alloc::boxed::Box;
|
|
||||||
use esp_hal::gpio::Pull;
|
|
||||||
|
|
||||||
pub enum Charger<'a> {
|
|
||||||
SolarMpptV1 {
|
|
||||||
mppt_ina: SyncIna219<MutexDevice<'a, I2cDriver<'a>>, UnCalibrated>,
|
|
||||||
solar_is_day: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
|
|
||||||
charge_indicator: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
|
||||||
},
|
|
||||||
ErrorInit {},
|
|
||||||
}
|
|
||||||
|
|
||||||
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) -> anyhow::Result<()> {
|
|
||||||
match self {
|
|
||||||
Self::SolarMpptV1 {
|
|
||||||
charge_indicator, ..
|
|
||||||
} => {
|
|
||||||
charge_indicator.set_state(charging.into())?;
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_day(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
Charger::SolarMpptV1 { solar_is_day, .. } => solar_is_day.get_level().into(),
|
|
||||||
_ => true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage> {
|
|
||||||
let voltage = match self {
|
|
||||||
Charger::SolarMpptV1 { mppt_ina, .. } => mppt_ina
|
|
||||||
.bus_voltage()
|
|
||||||
.map(|v| Voltage::from_millivolts(v.voltage_mv() as f64))?,
|
|
||||||
_ => {
|
|
||||||
bail!("hardware error during init")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(voltage)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_mptt_current(&mut self) -> anyhow::Result<Current> {
|
|
||||||
let current = match self {
|
|
||||||
Charger::SolarMpptV1 { mppt_ina, .. } => mppt_ina.shunt_voltage().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)
|
|
||||||
})?,
|
|
||||||
_ => {
|
|
||||||
bail!("hardware error during init")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(current)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, Output>,
|
|
||||||
light: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
|
||||||
general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
|
|
||||||
pump_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
|
|
||||||
pump_ina: Option<SyncIna219<MutexDevice<'a, I2cDriver<'a>>, UnCalibrated>>,
|
|
||||||
sensor: SensorImpl<'a>,
|
|
||||||
extra1: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, Output>,
|
|
||||||
extra2: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, Output>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn create_v4(
|
|
||||||
peripherals: FreePeripherals,
|
|
||||||
esp: Esp<'static>,
|
|
||||||
config: PlantControllerConfig,
|
|
||||||
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
|
||||||
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
|
||||||
) -> anyhow::Result<Box<dyn BoardInteraction<'static> + Send + 'static>> {
|
|
||||||
log::info!("Start v4");
|
|
||||||
let mut awake = PinDriver::output(peripherals.gpio21.downgrade())?;
|
|
||||||
awake.set_high()?;
|
|
||||||
|
|
||||||
let mut general_fault = PinDriver::input_output(peripherals.gpio23.downgrade())?;
|
|
||||||
general_fault.set_pull(Pull::Floating)?;
|
|
||||||
general_fault.set_low()?;
|
|
||||||
|
|
||||||
let mut extra1 = PinDriver::output(peripherals.gpio6.downgrade())?;
|
|
||||||
extra1.set_low()?;
|
|
||||||
|
|
||||||
let mut extra2 = PinDriver::output(peripherals.gpio15.downgrade())?;
|
|
||||||
extra2.set_low()?;
|
|
||||||
|
|
||||||
let one_wire_pin = peripherals.gpio18.downgrade();
|
|
||||||
let tank_power_pin = peripherals.gpio11.downgrade();
|
|
||||||
let flow_sensor_pin = peripherals.gpio4.downgrade();
|
|
||||||
|
|
||||||
let tank_sensor = TankSensor::create(
|
|
||||||
one_wire_pin,
|
|
||||||
peripherals.adc1,
|
|
||||||
peripherals.gpio5,
|
|
||||||
tank_power_pin,
|
|
||||||
flow_sensor_pin,
|
|
||||||
peripherals.pcnt1,
|
|
||||||
)?;
|
|
||||||
|
|
||||||
let mut sensor_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 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,
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
|
|
||||||
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 timing = can::config::Timing::B25K;
|
|
||||||
let config = can::config::Config::new().timing(timing);
|
|
||||||
let can = can::CanDriver::new(peripherals.can, peripherals.gpio0, peripherals.gpio2, &config).unwrap();
|
|
||||||
|
|
||||||
|
|
||||||
let frame = StandardId::new(0x042).unwrap();
|
|
||||||
let tx_frame = Frame::new(frame, &[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
|
|
||||||
can.transmit(&tx_frame, 1000).unwrap();
|
|
||||||
|
|
||||||
if let Ok(rx_frame) = can.receive(1000) {
|
|
||||||
log::info!("rx {:}:", rx_frame);
|
|
||||||
}
|
|
||||||
//can bus version
|
|
||||||
SensorImpl::CanBus {
|
|
||||||
can
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
let mut solar_is_day = PinDriver::input(peripherals.gpio7.downgrade())?;
|
|
||||||
solar_is_day.set_pull(Pull::Floating)?;
|
|
||||||
|
|
||||||
let mut light = PinDriver::input_output(peripherals.gpio10.downgrade())?;
|
|
||||||
light.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);
|
|
||||||
for pin in 0..8 {
|
|
||||||
let _ = pump_expander.pin_into_output(GPIOBank::Bank0, pin);
|
|
||||||
let _ = pump_expander.pin_into_output(GPIOBank::Bank1, pin);
|
|
||||||
let _ = pump_expander.pin_set_low(GPIOBank::Bank0, pin);
|
|
||||||
let _ = pump_expander.pin_set_low(GPIOBank::Bank1, pin);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
let mppt_ina = SyncIna219::new(
|
|
||||||
MutexDevice::new(&I2C_DRIVER),
|
|
||||||
Address::from_pins(Pin::Vcc, Pin::Gnd),
|
|
||||||
);
|
|
||||||
|
|
||||||
let charger = match mppt_ina {
|
|
||||||
Ok(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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => Charger::ErrorInit {},
|
|
||||||
};
|
|
||||||
|
|
||||||
let pump_ina = match SyncIna219::new(
|
|
||||||
MutexDevice::new(&I2C_DRIVER),
|
|
||||||
Address::from_pins(Pin::Gnd, Pin::Sda),
|
|
||||||
) {
|
|
||||||
Ok(pump_ina) => Some(pump_ina),
|
|
||||||
Err(err) => {
|
|
||||||
log::info!("Error creating pump ina: {:?}", err);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let v = V4 {
|
|
||||||
rtc_module,
|
|
||||||
esp,
|
|
||||||
awake,
|
|
||||||
tank_sensor,
|
|
||||||
light,
|
|
||||||
general_fault,
|
|
||||||
pump_ina,
|
|
||||||
pump_expander,
|
|
||||||
config,
|
|
||||||
battery_monitor,
|
|
||||||
charger,
|
|
||||||
extra1,
|
|
||||||
extra2,
|
|
||||||
sensor,
|
|
||||||
};
|
|
||||||
Ok(Box::new(v))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> BoardInteraction<'a> for V4<'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
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_config(&mut self) -> &PlantControllerConfig {
|
|
||||||
&self.config
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send> {
|
|
||||||
&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) -> anyhow::Result<()> {
|
|
||||||
self.charger.set_charge_indicator(charging)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
|
|
||||||
self.awake.set_low().unwrap();
|
|
||||||
self.charger.power_save();
|
|
||||||
deep_sleep(duration_in_ms);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_day(&self) -> bool {
|
|
||||||
self.charger.is_day()
|
|
||||||
}
|
|
||||||
|
|
||||||
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<()> {
|
|
||||||
if enable {
|
|
||||||
self.pump_expander
|
|
||||||
.pin_set_high(GPIOBank::Bank0, plant.try_into()?)?;
|
|
||||||
} else {
|
|
||||||
self.pump_expander
|
|
||||||
.pin_set_low(GPIOBank::Bank0, plant.try_into()?)?;
|
|
||||||
}
|
|
||||||
anyhow::Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pump_current(&mut self, _plant: usize) -> anyhow::Result<Current> {
|
|
||||||
//sensore 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(|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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fault(&mut self, plant: usize, enable: bool) -> anyhow::Result<()> {
|
|
||||||
if enable {
|
|
||||||
self.pump_expander
|
|
||||||
.pin_set_high(GPIOBank::Bank1, plant.try_into()?)?
|
|
||||||
} else {
|
|
||||||
self.pump_expander
|
|
||||||
.pin_set_low(GPIOBank::Bank1, plant.try_into()?)?
|
|
||||||
}
|
|
||||||
anyhow::Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
|
|
||||||
self.sensor.measure_moisture_hz(plant, sensor)
|
|
||||||
}
|
|
||||||
|
|
||||||
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()) };
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
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(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_config(&mut self, config: PlantControllerConfig) -> anyhow::Result<()> {
|
|
||||||
self.config = config;
|
|
||||||
self.esp.save_config(&self.config)?;
|
|
||||||
anyhow::Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage> {
|
|
||||||
self.charger.get_mptt_voltage()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_mptt_current(&mut self) -> anyhow::Result<Current> {
|
|
||||||
self.charger.get_mptt_current()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
use crate::hal::TANK_MULTI_SAMPLE;
|
|
||||||
use anyhow::{anyhow, bail};
|
|
||||||
use ds18b20::Ds18b20;
|
|
||||||
use esp_idf_hal::adc::oneshot::config::AdcChannelConfig;
|
|
||||||
use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver};
|
|
||||||
use esp_idf_hal::adc::{attenuation, Resolution, ADC1};
|
|
||||||
use esp_idf_hal::delay::Delay;
|
|
||||||
use esp_idf_hal::gpio::{AnyIOPin, AnyInputPin, Gpio5, InputOutput, PinDriver, Pull};
|
|
||||||
use esp_idf_hal::pcnt::{
|
|
||||||
PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex, PCNT1,
|
|
||||||
};
|
|
||||||
use esp_idf_sys::EspError;
|
|
||||||
use one_wire_bus::OneWire;
|
|
||||||
|
|
||||||
pub struct TankSensor<'a> {
|
|
||||||
// one_wire_bus: OneWire<PinDriver<'a, AnyIOPin, InputOutput>>,
|
|
||||||
// tank_channel: AdcChannelDriver<'a, Gpio5, AdcDriver<'a, ADC1>>,
|
|
||||||
// tank_power: PinDriver<'a, AnyIOPin, InputOutput>,
|
|
||||||
// flow_counter: PcntDriver<'a>,
|
|
||||||
// delay: Delay,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TankSensor<'a> {
|
|
||||||
pub(crate) fn create(
|
|
||||||
// one_wire_pin: AnyIOPin,
|
|
||||||
// adc1: ADC1,
|
|
||||||
// gpio5: Gpio5,
|
|
||||||
// tank_power_pin: AnyIOPin,
|
|
||||||
// flow_sensor_pin: AnyIOPin,
|
|
||||||
// pcnt1: PCNT1,
|
|
||||||
) -> anyhow::Result<TankSensor<'a>> {
|
|
||||||
// let mut one_wire_pin =
|
|
||||||
// PinDriver::input_output_od(one_wire_pin).expect("Failed to configure pin");
|
|
||||||
// one_wire_pin
|
|
||||||
// .set_pull(Pull::Floating)
|
|
||||||
// .expect("Failed to set pull");
|
|
||||||
//
|
|
||||||
// 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(adc1).expect("Failed to configure ADC");
|
|
||||||
// let tank_channel = AdcChannelDriver::new(tank_driver, gpio5, &adc_config)
|
|
||||||
// .expect("Failed to configure ADC channel");
|
|
||||||
//
|
|
||||||
// let mut tank_power =
|
|
||||||
// PinDriver::input_output(tank_power_pin).expect("Failed to configure pin");
|
|
||||||
// tank_power
|
|
||||||
// .set_pull(Pull::Floating)
|
|
||||||
// .expect("Failed to set pull");
|
|
||||||
//
|
|
||||||
// let one_wire_bus =
|
|
||||||
// OneWire::new(one_wire_pin).expect("OneWire bus did not pull up after release");
|
|
||||||
//
|
|
||||||
// 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,
|
|
||||||
// flow_counter,
|
|
||||||
// delay: Default::default(),
|
|
||||||
// })
|
|
||||||
bail!("Tank sensor not implemented");
|
|
||||||
}
|
|
||||||
|
|
||||||
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) -> anyhow::Result<f32> {
|
|
||||||
//multisample should be moved to water_temperature_c
|
|
||||||
let mut attempt = 1;
|
|
||||||
let water_temp: Result<f32, anyhow::Error> = loop {
|
|
||||||
let temp = self.single_temperature_c().await;
|
|
||||||
match &temp {
|
|
||||||
Ok(res) => {
|
|
||||||
log::info!("Water temp is {}", res);
|
|
||||||
break temp;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
log::info!("Could not get water temp {} attempt {}", err, attempt)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if attempt == 5 {
|
|
||||||
break temp;
|
|
||||||
}
|
|
||||||
attempt += 1;
|
|
||||||
};
|
|
||||||
water_temp
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn single_temperature_c(&mut self) -> anyhow::Result<f32> {
|
|
||||||
bail!("err");
|
|
||||||
// self.one_wire_bus
|
|
||||||
// .reset(&mut self.delay)
|
|
||||||
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
|
||||||
// let first = self.one_wire_bus.devices(false, &mut self.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.delay)
|
|
||||||
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
|
|
||||||
// ds18b20::Resolution::Bits12.delay_for_measurement_time(&mut self.delay);
|
|
||||||
// let sensor_data = water_temp_sensor
|
|
||||||
// .read_data(&mut self.one_wire_bus, &mut self.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)
|
|
||||||
Ok(13_f32)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
|
|
||||||
// self.tank_power.set_high()?;
|
|
||||||
// //let stabilize
|
|
||||||
// self.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;
|
|
||||||
let median_mv = 10_f32;
|
|
||||||
anyhow::Ok(median_mv)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use alloc::string::String;
|
|
||||||
use core::str::FromStr;
|
|
||||||
use crate::hal::PLANT_COUNT;
|
use crate::hal::PLANT_COUNT;
|
||||||
use crate::plant_state::PlantWateringMode;
|
use crate::plant_state::PlantWateringMode;
|
||||||
|
use alloc::string::String;
|
||||||
|
use core::str::FromStr;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||||
@@ -10,10 +10,10 @@ pub struct NetworkConfig {
|
|||||||
pub ap_ssid: heapless::String<32>,
|
pub ap_ssid: heapless::String<32>,
|
||||||
pub ssid: Option<heapless::String<32>>,
|
pub ssid: Option<heapless::String<32>>,
|
||||||
pub password: Option<heapless::String<64>>,
|
pub password: Option<heapless::String<64>>,
|
||||||
pub mqtt_url: Option<heapless::String<128>>,
|
pub mqtt_url: Option<String>,
|
||||||
pub base_topic: Option<heapless::String<64>>,
|
pub base_topic: Option<heapless::String<64>>,
|
||||||
pub mqtt_user: Option<heapless::String<32>>,
|
pub mqtt_user: Option<String>,
|
||||||
pub mqtt_password: Option<heapless::String<64>>,
|
pub mqtt_password: Option<String>,
|
||||||
pub max_wait: u32,
|
pub max_wait: u32,
|
||||||
}
|
}
|
||||||
impl Default for NetworkConfig {
|
impl Default for NetworkConfig {
|
||||||
|
|||||||
321
rust/src/fat_error.rs
Normal file
321
rust/src/fat_error.rs
Normal file
@@ -0,0 +1,321 @@
|
|||||||
|
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_hal::pcnt::unit::{InvalidHighLimit, InvalidLowLimit};
|
||||||
|
use esp_radio::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,
|
||||||
|
},
|
||||||
|
OTAError,
|
||||||
|
PartitionError {
|
||||||
|
error: esp_bootloader_esp_idf::partitions::Error,
|
||||||
|
},
|
||||||
|
I2CConfigError {
|
||||||
|
error: ConfigError,
|
||||||
|
},
|
||||||
|
DS323 {
|
||||||
|
error: String,
|
||||||
|
},
|
||||||
|
Eeprom24x {
|
||||||
|
error: String,
|
||||||
|
},
|
||||||
|
ExpanderError {
|
||||||
|
error: String,
|
||||||
|
},
|
||||||
|
SNTPError {
|
||||||
|
error: sntpc::Error,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
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),
|
||||||
|
FatError::SNTPError { error } => write!(f, "SNTPError {error:?}"),
|
||||||
|
FatError::OTAError => {
|
||||||
|
write!(f, "OTA missing partition")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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<T, E> ContextExt<T> for Result<T, E>
|
||||||
|
where
|
||||||
|
E: fmt::Debug,
|
||||||
|
{
|
||||||
|
fn context<C>(self, context: C) -> Result<T, FatError>
|
||||||
|
where
|
||||||
|
C: AsRef<str>,
|
||||||
|
{
|
||||||
|
match self {
|
||||||
|
Ok(value) => Ok(value),
|
||||||
|
Err(err) => Err(FatError::String {
|
||||||
|
error: format!("{}: {:?}", context.as_ref(), err),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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<sntpc::Error> for FatError {
|
||||||
|
fn from(value: sntpc::Error) -> Self {
|
||||||
|
FatError::SNTPError { 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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Infallible> for FatError {
|
||||||
|
fn from(value: Infallible) -> Self {
|
||||||
|
panic!("Infallible error: {:?}", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<InvalidLowLimit> for FatError {
|
||||||
|
fn from(value: InvalidLowLimit) -> Self {
|
||||||
|
FatError::String {
|
||||||
|
error: format!("{:?}", value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl From<InvalidHighLimit> for FatError {
|
||||||
|
fn from(value: InvalidHighLimit) -> Self {
|
||||||
|
FatError::String {
|
||||||
|
error: format!("{:?}", value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<chrono::format::ParseError> for FatError {
|
||||||
|
fn from(value: chrono::format::ParseError) -> Self {
|
||||||
|
FatError::String {
|
||||||
|
error: format!("Parsing error: {value:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,27 +1,28 @@
|
|||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
use crate::hal::Box;
|
use crate::hal::Box;
|
||||||
use alloc::string::String;
|
use alloc::string::String;
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use core::error::Error;
|
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;
|
use serde::Serialize;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait BatteryInteraction {
|
pub trait BatteryInteraction {
|
||||||
async fn state_charge_percent(&mut self) -> Result<f32, BatteryError>;
|
async fn state_charge_percent(&mut self) -> FatResult<f32>;
|
||||||
async fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
async fn remaining_milli_ampere_hour(&mut self) -> FatResult<u16>;
|
||||||
async fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
async fn max_milli_ampere_hour(&mut self) -> FatResult<u16>;
|
||||||
async fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError>;
|
async fn design_milli_ampere_hour(&mut self) -> FatResult<u16>;
|
||||||
async fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError>;
|
async fn voltage_milli_volt(&mut self) -> FatResult<u16>;
|
||||||
async fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError>;
|
async fn average_current_milli_ampere(&mut self) -> FatResult<i16>;
|
||||||
async fn cycle_count(&mut self) -> Result<u16, BatteryError>;
|
async fn cycle_count(&mut self) -> FatResult<u16>;
|
||||||
async fn state_health_percent(&mut self) -> Result<u16, BatteryError>;
|
async fn state_health_percent(&mut self) -> FatResult<u16>;
|
||||||
async fn bat_temperature(&mut self) -> Result<u16, BatteryError>;
|
async fn bat_temperature(&mut self) -> FatResult<u16>;
|
||||||
async fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError>;
|
async fn get_battery_state(&mut self) -> FatResult<BatteryState>;
|
||||||
}
|
|
||||||
|
|
||||||
impl From<BatteryError> for anyhow::Error {
|
|
||||||
fn from(err: BatteryError) -> Self {
|
|
||||||
anyhow::anyhow!(err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
@@ -42,14 +43,6 @@ pub enum BatteryError {
|
|||||||
CommunicationError(String),
|
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(),
|
|
||||||
// )
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
pub enum BatteryState {
|
pub enum BatteryState {
|
||||||
Unknown,
|
Unknown,
|
||||||
@@ -60,43 +53,44 @@ pub enum BatteryState {
|
|||||||
pub struct NoBatteryMonitor {}
|
pub struct NoBatteryMonitor {}
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl BatteryInteraction for NoBatteryMonitor {
|
impl BatteryInteraction for NoBatteryMonitor {
|
||||||
async fn state_charge_percent(&mut self) -> Result<f32, BatteryError> {
|
async fn state_charge_percent(&mut self) -> FatResult<f32> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
// No monitor configured: assume full battery for lightstate logic
|
||||||
|
Ok(100.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
async fn remaining_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
Err(FatError::NoBatteryMonitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
async fn max_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
Err(FatError::NoBatteryMonitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
async fn design_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
Err(FatError::NoBatteryMonitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError> {
|
async fn voltage_milli_volt(&mut self) -> FatResult<u16> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
Err(FatError::NoBatteryMonitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError> {
|
async fn average_current_milli_ampere(&mut self) -> FatResult<i16> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
Err(FatError::NoBatteryMonitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn cycle_count(&mut self) -> Result<u16, BatteryError> {
|
async fn cycle_count(&mut self) -> FatResult<u16> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
Err(FatError::NoBatteryMonitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn state_health_percent(&mut self) -> Result<u16, BatteryError> {
|
async fn state_health_percent(&mut self) -> FatResult<u16> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
Err(FatError::NoBatteryMonitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn bat_temperature(&mut self) -> Result<u16, BatteryError> {
|
async fn bat_temperature(&mut self) -> FatResult<u16> {
|
||||||
Err(BatteryError::NoBatteryMonitor)
|
Err(FatError::NoBatteryMonitor)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError> {
|
async fn get_battery_state(&mut self) -> FatResult<BatteryState> {
|
||||||
Ok(BatteryState::Unknown)
|
Ok(BatteryState::Unknown)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,115 +99,167 @@ impl BatteryInteraction for NoBatteryMonitor {
|
|||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct WchI2cSlave {}
|
pub struct WchI2cSlave {}
|
||||||
|
|
||||||
// pub struct BQ34Z100G1<'a> {
|
pub type I2cDev = I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>;
|
||||||
// pub battery_driver: Bq34z100g1Driver<MutexDevice<'a, I2cDriver<'a>>, Delay>,
|
|
||||||
// }
|
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> {
|
||||||
// fn remaining_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
self.battery_driver
|
||||||
// Ok(self.battery_driver.remaining_capacity()?)
|
.state_of_charge()
|
||||||
// }
|
.map(|v| v as f32)
|
||||||
//
|
.map_err(|e| FatError::String {
|
||||||
// fn max_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
error: alloc::format!("{:?}", e),
|
||||||
// Ok(self.battery_driver.full_charge_capacity()?)
|
})
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// fn design_milli_ampere_hour(&mut self) -> Result<u16, BatteryError> {
|
async fn remaining_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||||
// Ok(self.battery_driver.design_capacity()?)
|
self.battery_driver
|
||||||
// }
|
.remaining_capacity()
|
||||||
//
|
.map_err(|e| FatError::String {
|
||||||
// fn voltage_milli_volt(&mut self) -> Result<u16, BatteryError> {
|
error: alloc::format!("{:?}", e),
|
||||||
// Ok(self.battery_driver.voltage()?)
|
})
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// fn average_current_milli_ampere(&mut self) -> Result<i16, BatteryError> {
|
async fn max_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||||
// Ok(self.battery_driver.average_current()?)
|
self.battery_driver
|
||||||
// }
|
.full_charge_capacity()
|
||||||
//
|
.map_err(|e| FatError::String {
|
||||||
// fn cycle_count(&mut self) -> Result<u16, BatteryError> {
|
error: alloc::format!("{:?}", e),
|
||||||
// Ok(self.battery_driver.cycle_count()?)
|
})
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// fn state_health_percent(&mut self) -> Result<u16, BatteryError> {
|
async fn design_milli_ampere_hour(&mut self) -> FatResult<u16> {
|
||||||
// Ok(self.battery_driver.state_of_health()?)
|
self.battery_driver
|
||||||
// }
|
.design_capacity()
|
||||||
//
|
.map_err(|e| FatError::String {
|
||||||
// fn bat_temperature(&mut self) -> Result<u16, BatteryError> {
|
error: alloc::format!("{:?}", e),
|
||||||
// Ok(self.battery_driver.temperature()?)
|
})
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// fn get_battery_state(&mut self) -> Result<BatteryState, BatteryError> {
|
async fn voltage_milli_volt(&mut self) -> FatResult<u16> {
|
||||||
// Ok(BatteryState::Info(BatteryInfo {
|
self.battery_driver.voltage().map_err(|e| FatError::String {
|
||||||
// voltage_milli_volt: self.voltage_milli_volt()?,
|
error: alloc::format!("{:?}", e),
|
||||||
// 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()?,
|
async fn average_current_milli_ampere(&mut self) -> FatResult<i16> {
|
||||||
// state_of_charge: self.state_charge_percent()?,
|
self.battery_driver
|
||||||
// state_of_health: self.state_health_percent()?,
|
.average_current()
|
||||||
// temperature: self.bat_temperature()?,
|
.map_err(|e| FatError::String {
|
||||||
// }))
|
error: alloc::format!("{:?}", e),
|
||||||
// }
|
})
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// pub fn print_battery_bq34z100(
|
async fn cycle_count(&mut self) -> FatResult<u16> {
|
||||||
// battery_driver: &mut Bq34z100g1Driver<MutexDevice<I2cDriver<'_>>, Delay>,
|
self.battery_driver
|
||||||
// ) -> anyhow::Result<(), Bq34Z100Error<I2cError>> {
|
.cycle_count()
|
||||||
// log::info!("Try communicating with battery");
|
.map_err(|e| FatError::String {
|
||||||
// let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
|
error: alloc::format!("{:?}", e),
|
||||||
// log::info!("Firmware {:?}", e);
|
})
|
||||||
// 0
|
}
|
||||||
// });
|
|
||||||
// log::info!("fw version is {}", fwversion);
|
async fn state_health_percent(&mut self) -> FatResult<u16> {
|
||||||
//
|
self.battery_driver
|
||||||
// let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
|
.state_of_health()
|
||||||
// log::info!("Design capacity {:?}", e);
|
.map_err(|e| FatError::String {
|
||||||
// 0
|
error: alloc::format!("{:?}", e),
|
||||||
// });
|
})
|
||||||
// log::info!("Design Capacity {}", design_capacity);
|
}
|
||||||
// if design_capacity == 1000 {
|
|
||||||
// log::info!("Still stock configuring battery, readouts are likely to be wrong!");
|
async fn bat_temperature(&mut self) -> FatResult<u16> {
|
||||||
// }
|
self.battery_driver
|
||||||
//
|
.temperature()
|
||||||
// let flags = battery_driver.get_flags_decoded()?;
|
.map_err(|e| FatError::String {
|
||||||
// log::info!("Flags {:?}", flags);
|
error: alloc::format!("{:?}", e),
|
||||||
//
|
})
|
||||||
// let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
|
}
|
||||||
// log::info!("Chemid {:?}", e);
|
|
||||||
// 0
|
async fn get_battery_state(&mut self) -> FatResult<BatteryState> {
|
||||||
// });
|
Ok(BatteryState::Info(BatteryInfo {
|
||||||
//
|
voltage_milli_volt: self.voltage_milli_volt().await?,
|
||||||
// let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
|
average_current_milli_ampere: self.average_current_milli_ampere().await?,
|
||||||
// log::info!("Bat Temp {:?}", e);
|
cycle_count: self.cycle_count().await?,
|
||||||
// 0
|
design_milli_ampere_hour: self.design_milli_ampere_hour().await?,
|
||||||
// });
|
remaining_milli_ampere_hour: self.remaining_milli_ampere_hour().await?,
|
||||||
// let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
|
state_of_charge: self.state_charge_percent().await?,
|
||||||
// let voltage = battery_driver.voltage().unwrap_or_else(|e| {
|
state_of_health: self.state_health_percent().await?,
|
||||||
// log::info!("Bat volt {:?}", e);
|
temperature: self.bat_temperature().await?,
|
||||||
// 0
|
}))
|
||||||
// });
|
}
|
||||||
// let current = battery_driver.current().unwrap_or_else(|e| {
|
}
|
||||||
// log::info!("Bat current {:?}", e);
|
|
||||||
// 0
|
pub fn print_battery_bq34z100(
|
||||||
// });
|
battery_driver: &mut Bq34z100g1Driver<I2cDevice<CriticalSectionRawMutex, I2c<Blocking>>, Delay>,
|
||||||
// let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
|
) -> FatResult<()> {
|
||||||
// log::info!("Bat Soc {:?}", e);
|
log::info!("Try communicating with battery");
|
||||||
// 0
|
let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
|
||||||
// });
|
log::info!("Firmware {:?}", e);
|
||||||
// let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
|
0
|
||||||
// log::info!("Bat Charge Volt {:?}", e);
|
});
|
||||||
// 0
|
log::info!("fw version is {}", fwversion);
|
||||||
// });
|
|
||||||
// let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
|
let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
|
||||||
// log::info!("Bat Charge Current {:?}", e);
|
log::info!("Design capacity {:?}", e);
|
||||||
// 0
|
0
|
||||||
// });
|
});
|
||||||
// log::info!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
|
log::info!("Design Capacity {}", design_capacity);
|
||||||
// let _ = battery_driver.unsealed();
|
if design_capacity == 1000 {
|
||||||
// let _ = battery_driver.it_enable();
|
log::info!("Still stock configuring battery, readouts are likely to be wrong!");
|
||||||
// anyhow::Result::Ok(())
|
}
|
||||||
// }
|
|
||||||
|
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| {
|
||||||
|
log::info!("Chemid {:?}", e);
|
||||||
|
0
|
||||||
|
});
|
||||||
|
|
||||||
|
let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|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| {
|
||||||
|
log::info!("Bat volt {:?}", e);
|
||||||
|
0
|
||||||
|
});
|
||||||
|
let current = battery_driver.current().unwrap_or_else(|e| {
|
||||||
|
log::info!("Bat current {:?}", e);
|
||||||
|
0
|
||||||
|
});
|
||||||
|
let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
|
||||||
|
log::info!("Bat Soc {:?}", e);
|
||||||
|
0
|
||||||
|
});
|
||||||
|
let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
|
||||||
|
log::info!("Bat Charge Volt {:?}", e);
|
||||||
|
0
|
||||||
|
});
|
||||||
|
let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
|
||||||
|
log::info!("Bat Charge Current {:?}", e);
|
||||||
|
0
|
||||||
|
});
|
||||||
|
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();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,18 +1,17 @@
|
|||||||
|
use crate::alloc::boxed::Box;
|
||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
use crate::hal::esp::Esp;
|
use crate::hal::esp::Esp;
|
||||||
use crate::hal::rtc::{BackupHeader, RTCModuleInteraction};
|
use crate::hal::rtc::{BackupHeader, RTCModuleInteraction};
|
||||||
use alloc::vec::Vec;
|
use crate::hal::water::TankSensor;
|
||||||
//use crate::hal::water::TankSensor;
|
|
||||||
use crate::alloc::boxed::Box;
|
|
||||||
use crate::hal::{BoardInteraction, FreePeripherals, Sensor};
|
use crate::hal::{BoardInteraction, FreePeripherals, Sensor};
|
||||||
use crate::{
|
use crate::{
|
||||||
|
bail,
|
||||||
config::PlantControllerConfig,
|
config::PlantControllerConfig,
|
||||||
hal::battery::{BatteryInteraction, NoBatteryMonitor},
|
hal::battery::{BatteryInteraction, NoBatteryMonitor},
|
||||||
};
|
};
|
||||||
use anyhow::{bail, Result};
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, FixedOffset, Utc};
|
||||||
use esp_hal::gpio::{Level, Output, OutputConfig};
|
use esp_hal::gpio::{Level, Output, OutputConfig};
|
||||||
use log::info;
|
|
||||||
use measurements::{Current, Voltage};
|
use measurements::{Current, Voltage};
|
||||||
|
|
||||||
pub struct Initial<'a> {
|
pub struct Initial<'a> {
|
||||||
@@ -23,27 +22,31 @@ pub struct Initial<'a> {
|
|||||||
pub rtc: Box<dyn RTCModuleInteraction + Send>,
|
pub rtc: Box<dyn RTCModuleInteraction + Send>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct NoRTC {}
|
pub(crate) struct NoRTC {}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl RTCModuleInteraction for NoRTC {
|
impl RTCModuleInteraction for NoRTC {
|
||||||
async fn get_backup_info(&mut self) -> Result<BackupHeader> {
|
async fn get_backup_info(&mut self) -> Result<BackupHeader, FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_backup_config(&mut self) -> Result<Vec<u8>> {
|
async fn get_backup_config(&mut self, _chunk: usize) -> FatResult<([u8; 32], usize, u16)> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn backup_config(&mut self, _bytes: &[u8]) -> Result<()> {
|
async fn backup_config(&mut self, _offset: usize, _bytes: &[u8]) -> FatResult<()> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_rtc_time(&mut self) -> Result<DateTime<Utc>> {
|
async fn backup_config_finalize(&mut self, _crc: u16, _length: usize) -> FatResult<()> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn set_rtc_time(&mut self, _time: &DateTime<Utc>) -> Result<()> {
|
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")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -52,7 +55,7 @@ pub(crate) fn create_initial_board(
|
|||||||
free_pins: FreePeripherals<'static>,
|
free_pins: FreePeripherals<'static>,
|
||||||
config: PlantControllerConfig,
|
config: PlantControllerConfig,
|
||||||
esp: Esp<'static>,
|
esp: Esp<'static>,
|
||||||
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
|
) -> Result<Box<dyn BoardInteraction<'static> + Send>, FatError> {
|
||||||
log::info!("Start initial");
|
log::info!("Start initial");
|
||||||
let general_fault = Output::new(free_pins.gpio23, Level::Low, OutputConfig::default());
|
let general_fault = Output::new(free_pins.gpio23, Level::Low, OutputConfig::default());
|
||||||
let v = Initial {
|
let v = Initial {
|
||||||
@@ -67,9 +70,9 @@ pub(crate) fn create_initial_board(
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<'a> BoardInteraction<'a> for Initial<'a> {
|
impl<'a> BoardInteraction<'a> for Initial<'a> {
|
||||||
// fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>> {
|
fn get_tank_sensor(&mut self) -> Result<&mut TankSensor<'a>, FatError> {
|
||||||
// None
|
bail!("Please configure board revision")
|
||||||
// }
|
}
|
||||||
|
|
||||||
fn get_esp(&mut self) -> &mut Esp<'a> {
|
fn get_esp(&mut self) -> &mut Esp<'a> {
|
||||||
&mut self.esp
|
&mut self.esp
|
||||||
@@ -87,33 +90,47 @@ impl<'a> BoardInteraction<'a> for Initial<'a> {
|
|||||||
&mut self.rtc
|
&mut self.rtc
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_charge_indicator(&mut self, _charging: bool) -> Result<()> {
|
async fn get_time(&mut self) -> DateTime<Utc> {
|
||||||
|
self.esp.get_time()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_time(&mut self, time: &DateTime<FixedOffset>) -> FatResult<()> {
|
||||||
|
self.rtc.set_rtc_time(&time.to_utc()).await?;
|
||||||
|
self.esp.set_time(time.to_utc());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_charge_indicator(&mut self, _charging: bool) -> Result<(), FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
|
async fn deep_sleep_ms(&mut self, duration_in_ms: u64) -> ! {
|
||||||
self.esp.deep_sleep(duration_in_ms).await;
|
self.esp.deep_sleep_ms(duration_in_ms);
|
||||||
}
|
}
|
||||||
fn is_day(&self) -> bool {
|
fn is_day(&self) -> bool {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
fn light(&mut self, _enable: bool) -> Result<()> {
|
async fn light(&mut self, _enable: bool) -> Result<(), FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn pump(&mut self, _plant: usize, _enable: bool) -> Result<()> {
|
async fn pump(&mut self, _plant: usize, _enable: bool) -> Result<(), FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn pump_current(&mut self, _plant: usize) -> Result<Current> {
|
async fn pump_current(&mut self, _plant: usize) -> Result<Current, FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fault(&mut self, _plant: usize, _enable: bool) -> Result<()> {
|
async fn fault(&mut self, _plant: usize, _enable: bool) -> Result<(), FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn measure_moisture_hz(&mut self, _plant: usize, _sensor: Sensor) -> Result<f32> {
|
async fn measure_moisture_hz(
|
||||||
|
&mut self,
|
||||||
|
_plant: usize,
|
||||||
|
_sensor: Sensor,
|
||||||
|
) -> Result<f32, FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,7 +138,7 @@ impl<'a> BoardInteraction<'a> for Initial<'a> {
|
|||||||
self.general_fault.set_level(enable.into());
|
self.general_fault.set_level(enable.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn test(&mut self) -> Result<()> {
|
async fn test(&mut self) -> Result<(), FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,11 +146,11 @@ impl<'a> BoardInteraction<'a> for Initial<'a> {
|
|||||||
self.config = config;
|
self.config = config;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_mptt_voltage(&mut self) -> Result<Voltage> {
|
async fn get_mptt_voltage(&mut self) -> Result<Voltage, FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_mptt_current(&mut self) -> Result<Current> {
|
async fn get_mptt_current(&mut self) -> Result<Current, FatError> {
|
||||||
bail!("Please configure board revision")
|
bail!("Please configure board revision")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,73 +1,88 @@
|
|||||||
use embedded_storage::{ReadStorage, Storage};
|
use crate::hal::shared_flash::MutexFlashStorage;
|
||||||
|
use embedded_storage::nor_flash::{check_erase, NorFlash, ReadNorFlash};
|
||||||
use esp_bootloader_esp_idf::partitions::FlashRegion;
|
use esp_bootloader_esp_idf::partitions::FlashRegion;
|
||||||
use esp_storage::FlashStorage;
|
use littlefs2::consts::U4096 as lfsCache;
|
||||||
use littlefs2::consts::U512 as lfsCache;
|
|
||||||
use littlefs2::consts::U512 as lfsLookahead;
|
use littlefs2::consts::U512 as lfsLookahead;
|
||||||
use littlefs2::driver::Storage as lfs2Storage;
|
use littlefs2::driver::Storage as lfs2Storage;
|
||||||
use littlefs2::fs::Filesystem as lfs2Filesystem;
|
|
||||||
use littlefs2::io::Error as lfs2Error;
|
use littlefs2::io::Error as lfs2Error;
|
||||||
use littlefs2::io::Result as lfs2Result;
|
use littlefs2::io::Result as lfs2Result;
|
||||||
use log::{error, info};
|
use log::error;
|
||||||
|
|
||||||
pub struct LittleFs2Filesystem {
|
pub struct LittleFs2Filesystem {
|
||||||
pub(crate) storage: &'static mut FlashRegion<'static, FlashStorage>,
|
pub(crate) storage: &'static mut FlashRegion<'static, MutexFlashStorage>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl lfs2Storage for LittleFs2Filesystem {
|
impl lfs2Storage for LittleFs2Filesystem {
|
||||||
const READ_SIZE: usize = 256;
|
const READ_SIZE: usize = 4096;
|
||||||
const WRITE_SIZE: usize = 512;
|
const WRITE_SIZE: usize = 4096;
|
||||||
const BLOCK_SIZE: usize = 512; //usually optimal for flash access
|
const BLOCK_SIZE: usize = 4096; //usually optimal for flash access
|
||||||
const BLOCK_COUNT: usize = 8 * 1024 * 1024 / 512; //8mb in 32kb blocks
|
const BLOCK_COUNT: usize = 8 * 1000 * 1000 / 4096; //8Mb in 4k blocks + a little space for stupid calculation errors
|
||||||
const BLOCK_CYCLES: isize = 100;
|
const BLOCK_CYCLES: isize = 100;
|
||||||
type CACHE_SIZE = lfsCache;
|
type CACHE_SIZE = lfsCache;
|
||||||
type LOOKAHEAD_SIZE = lfsLookahead;
|
type LOOKAHEAD_SIZE = lfsLookahead;
|
||||||
|
|
||||||
fn read(&mut self, off: usize, buf: &mut [u8]) -> lfs2Result<usize> {
|
fn read(&mut self, off: usize, buf: &mut [u8]) -> lfs2Result<usize> {
|
||||||
let read_size: usize = Self::READ_SIZE;
|
let read_size: usize = Self::READ_SIZE;
|
||||||
assert_eq!(off % read_size, 0);
|
if off % read_size != 0 {
|
||||||
assert_eq!(buf.len() % read_size, 0);
|
error!("Littlefs2Filesystem read error: offset not aligned to read size offset: {off} read_size: {read_size}");
|
||||||
|
return Err(lfs2Error::IO);
|
||||||
|
}
|
||||||
|
if buf.len() % read_size != 0 {
|
||||||
|
error!("Littlefs2Filesystem read error: length not aligned to read size length: {} read_size: {}", buf.len(), read_size);
|
||||||
|
return Err(lfs2Error::IO);
|
||||||
|
}
|
||||||
match self.storage.read(off as u32, buf) {
|
match self.storage.read(off as u32, buf) {
|
||||||
anyhow::Result::Ok(..) => lfs2Result::Ok(buf.len()),
|
Ok(..) => Ok(buf.len()),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("Littlefs2Filesystem read error: {:?}", err);
|
error!("Littlefs2Filesystem read error: {err:?}");
|
||||||
Err(lfs2Error::IO)
|
Err(lfs2Error::IO)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write(&mut self, off: usize, data: &[u8]) -> lfs2Result<usize> {
|
fn write(&mut self, off: usize, data: &[u8]) -> lfs2Result<usize> {
|
||||||
info!(
|
|
||||||
"Littlefs2Filesystem write at offset {} with len {}",
|
|
||||||
off,
|
|
||||||
data.len()
|
|
||||||
);
|
|
||||||
let write_size: usize = Self::WRITE_SIZE;
|
let write_size: usize = Self::WRITE_SIZE;
|
||||||
assert_eq!(off % write_size, 0);
|
if off % write_size != 0 {
|
||||||
assert_eq!(data.len() % write_size, 0);
|
error!("Littlefs2Filesystem write error: offset not aligned to write size offset: {off} write_size: {write_size}");
|
||||||
|
return Err(lfs2Error::IO);
|
||||||
|
}
|
||||||
|
if data.len() % write_size != 0 {
|
||||||
|
error!("Littlefs2Filesystem write error: length not aligned to write size length: {} write_size: {}", data.len(), write_size);
|
||||||
|
return Err(lfs2Error::IO);
|
||||||
|
}
|
||||||
match self.storage.write(off as u32, data) {
|
match self.storage.write(off as u32, data) {
|
||||||
anyhow::Result::Ok(..) => lfs2Result::Ok(data.len()),
|
Ok(..) => Ok(data.len()),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
error!("Littlefs2Filesystem write error: {:?}", err);
|
error!("Littlefs2Filesystem write error: {err:?}");
|
||||||
Err(lfs2Error::IO)
|
Err(lfs2Error::IO)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn erase(&mut self, off: usize, len: usize) -> lfs2Result<usize> {
|
fn erase(&mut self, off: usize, len: usize) -> lfs2Result<usize> {
|
||||||
info!(
|
|
||||||
"Littlefs2Filesystem erase at offset {} with len {}",
|
|
||||||
off, len
|
|
||||||
);
|
|
||||||
let block_size: usize = Self::BLOCK_SIZE;
|
let block_size: usize = Self::BLOCK_SIZE;
|
||||||
debug_assert!(off % block_size == 0);
|
if off % block_size != 0 {
|
||||||
debug_assert!(len % block_size == 0);
|
error!("Littlefs2Filesystem erase error: offset not aligned to block size offset: {off} block_size: {block_size}");
|
||||||
//match self.storage.erase(off as u32, len as u32) {
|
return Err(lfs2Error::IO);
|
||||||
//anyhow::Result::Ok(..) => lfs2Result::Ok(len),
|
}
|
||||||
//Err(err) => {
|
if len % block_size != 0 {
|
||||||
//error!("Littlefs2Filesystem erase error: {:?}", err);
|
error!("Littlefs2Filesystem erase error: length not aligned to block size length: {len} block_size: {block_size}");
|
||||||
//Err(lfs2Error::IO)
|
return Err(lfs2Error::IO);
|
||||||
// }
|
}
|
||||||
//}
|
|
||||||
lfs2Result::Ok(len)
|
match check_erase(self.storage, off as u32, (off + len) as u32) {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(err) => {
|
||||||
|
error!("Littlefs2Filesystem check erase error: {err:?}");
|
||||||
|
return Err(lfs2Error::IO);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match self.storage.erase(off as u32, (off + len) as u32) {
|
||||||
|
Ok(..) => Ok(len),
|
||||||
|
Err(err) => {
|
||||||
|
error!("Littlefs2Filesystem erase error: {err:?}");
|
||||||
|
Err(lfs2Error::IO)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,67 +2,132 @@ pub(crate) mod battery;
|
|||||||
pub mod esp;
|
pub mod esp;
|
||||||
mod initial_hal;
|
mod initial_hal;
|
||||||
mod little_fs2storage_adapter;
|
mod little_fs2storage_adapter;
|
||||||
mod rtc;
|
pub(crate) mod rtc;
|
||||||
//mod water;
|
mod shared_flash;
|
||||||
|
mod v3_hal;
|
||||||
|
mod v3_shift_register;
|
||||||
|
mod v4_hal;
|
||||||
|
mod v4_sensor;
|
||||||
|
mod water;
|
||||||
|
|
||||||
use crate::alloc::string::ToString;
|
use crate::alloc::string::ToString;
|
||||||
use crate::hal::rtc::RTCModuleInteraction;
|
use crate::hal::rtc::{DS3231Module, RTCModuleInteraction};
|
||||||
|
use esp_hal::interrupt::software::SoftwareInterruptControl;
|
||||||
use esp_hal::peripherals::Peripherals;
|
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::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::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::GPIO6;
|
||||||
|
use esp_hal::peripherals::GPIO7;
|
||||||
|
use esp_hal::peripherals::GPIO8;
|
||||||
|
use esp_hal::peripherals::PCNT;
|
||||||
|
use esp_hal::peripherals::TWAI0;
|
||||||
|
use portable_atomic::AtomicBool;
|
||||||
|
|
||||||
//use crate::hal::water::TankSensor;
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
bail,
|
||||||
config::{BatteryBoardVersion, BoardVersion, PlantControllerConfig},
|
config::{BatteryBoardVersion, BoardVersion, PlantControllerConfig},
|
||||||
hal::{
|
hal::{
|
||||||
battery::{BatteryInteraction, NoBatteryMonitor},
|
battery::{BatteryInteraction, NoBatteryMonitor},
|
||||||
esp::Esp,
|
esp::Esp,
|
||||||
},
|
},
|
||||||
log::{LogMessage},
|
log::LogMessage,
|
||||||
|
BOARD_ACCESS,
|
||||||
};
|
};
|
||||||
use alloc::boxed::Box;
|
use alloc::boxed::Box;
|
||||||
use alloc::format;
|
use alloc::format;
|
||||||
use alloc::sync::Arc;
|
use alloc::sync::Arc;
|
||||||
use core::cell::OnceCell;
|
|
||||||
use anyhow::{bail, Ok, Result};
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
use bq34z100::Bq34z100g1Driver;
|
||||||
use chrono::{DateTime, FixedOffset, Utc};
|
use chrono::{DateTime, FixedOffset, Utc};
|
||||||
use embassy_executor::Spawner;
|
use core::cell::RefCell;
|
||||||
//use battery::BQ34Z100G1;
|
use ds323x::ic::DS3231;
|
||||||
//use bq34z100::Bq34z100g1Driver;
|
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_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::blocking_mutex::CriticalSectionMutex;
|
||||||
|
use embedded_storage::nor_flash::RmwNorFlashStorage;
|
||||||
|
use embedded_storage::ReadStorage;
|
||||||
use esp_bootloader_esp_idf::partitions::{
|
use esp_bootloader_esp_idf::partitions::{
|
||||||
AppPartitionSubType, DataPartitionSubType, FlashRegion, PartitionEntry,
|
AppPartitionSubType, DataPartitionSubType, FlashRegion, PartitionEntry, PartitionTable,
|
||||||
|
PartitionType,
|
||||||
};
|
};
|
||||||
use esp_hal::clock::CpuClock;
|
use esp_hal::clock::CpuClock;
|
||||||
use esp_hal::gpio::{Input, InputConfig, Pull};
|
use esp_hal::gpio::{Input, InputConfig, Pull};
|
||||||
|
use esp_hal::uart::{Config as UartConfig, Uart};
|
||||||
|
use esp_storage::FlashStorage;
|
||||||
|
use lib_bms_protocol::{BmsReadable, ProtocolVersion};
|
||||||
use measurements::{Current, Voltage};
|
use measurements::{Current, Voltage};
|
||||||
|
|
||||||
|
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||||
|
use crate::hal::battery::{print_battery_bq34z100, BQ34Z100G1};
|
||||||
use crate::hal::little_fs2storage_adapter::LittleFs2Filesystem;
|
use crate::hal::little_fs2storage_adapter::LittleFs2Filesystem;
|
||||||
|
use crate::hal::water::TankSensor;
|
||||||
|
use crate::log::log;
|
||||||
use embassy_sync::mutex::Mutex;
|
use embassy_sync::mutex::Mutex;
|
||||||
use embassy_sync::once_lock::OnceLock;
|
use embassy_sync::once_lock::OnceLock;
|
||||||
use esp_alloc as _;
|
use esp_alloc as _;
|
||||||
use esp_backtrace as _;
|
use esp_backtrace as _;
|
||||||
use esp_bootloader_esp_idf::ota::Slot;
|
use esp_bootloader_esp_idf::ota::{OtaImageState, Ota};
|
||||||
|
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::rng::Rng;
|
||||||
use esp_hal::rtc_cntl::{Rtc, SocResetReason};
|
use esp_hal::rtc_cntl::{Rtc, SocResetReason};
|
||||||
use esp_hal::system::reset_reason;
|
use esp_hal::system::reset_reason;
|
||||||
use esp_hal::timer::timg::TimerGroup;
|
use esp_hal::time::Rate;
|
||||||
use esp_storage::FlashStorage;
|
use esp_hal::timer::timg::{TimerGroup, Wdt};
|
||||||
use esp_wifi::{init, EspWifiController};
|
use esp_hal::Blocking;
|
||||||
use littlefs2::fs::{Allocation, Filesystem as lfs2Filesystem};
|
use littlefs2::fs::{Allocation, Filesystem as lfs2Filesystem};
|
||||||
use littlefs2::object_safe::DynStorage;
|
use littlefs2::object_safe::DynStorage;
|
||||||
use log::{info, warn};
|
use log::{error, info, warn};
|
||||||
use crate::log::{LogArray, LOG_ACCESS};
|
use shared_flash::MutexFlashStorage;
|
||||||
|
|
||||||
pub static TIME_ACCESS: OnceLock<Rtc> = OnceLock::new();
|
pub static PROGRESS_ACTIVE: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
//Only support for 8 right now!
|
//Only support for 8 right now!
|
||||||
pub const PLANT_COUNT: usize = 8;
|
pub const PLANT_COUNT: usize = 8;
|
||||||
|
|
||||||
const TANK_MULTI_SAMPLE: usize = 11;
|
pub static WATCHDOG: OnceLock<
|
||||||
|
embassy_sync::blocking_mutex::Mutex<
|
||||||
|
CriticalSectionRawMutex,
|
||||||
|
RefCell<Wdt<esp_hal::peripherals::TIMG0>>,
|
||||||
|
>,
|
||||||
|
> = OnceLock::new();
|
||||||
|
|
||||||
//pub static I2C_DRIVER: LazyLock<Mutex<CriticalSectionRawMutex,I2cDriver<'static>>> = LazyLock::new(PlantHal::create_i2c);
|
const TANK_MULTI_SAMPLE: usize = 11;
|
||||||
|
pub static I2C_DRIVER: OnceLock<
|
||||||
|
embassy_sync::blocking_mutex::Mutex<CriticalSectionRawMutex, RefCell<I2c<Blocking>>>,
|
||||||
|
> = OnceLock::new();
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum Sensor {
|
pub enum Sensor {
|
||||||
@@ -76,196 +141,223 @@ pub struct HAL<'a> {
|
|||||||
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
|
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn ota_state(
|
||||||
|
slot: AppPartitionSubType,
|
||||||
|
ota_data: &mut FlashRegion<RmwNorFlashStorage<&mut MutexFlashStorage>>,
|
||||||
|
) -> OtaImageState {
|
||||||
|
// Read and log OTA states for both slots before constructing Ota
|
||||||
|
// Each OTA select entry is 32 bytes: [seq:4][label:20][state:4][crc:4]
|
||||||
|
// Offsets within the OTA data partition: slot0 @ 0x0000, slot1 @ 0x1000
|
||||||
|
let mut slot_buf = [0u8; 32];
|
||||||
|
if slot == AppPartitionSubType::Ota0 {
|
||||||
|
let _ = ReadStorage::read(ota_data, 0x0000, &mut slot_buf);
|
||||||
|
} else {
|
||||||
|
let _ = ReadStorage::read(ota_data, 0x1000, &mut slot_buf);
|
||||||
|
}
|
||||||
|
let raw_state = u32::from_le_bytes(slot_buf[24..28].try_into().unwrap_or([0xff; 4]));
|
||||||
|
|
||||||
|
OtaImageState::try_from(raw_state).unwrap_or(OtaImageState::Undefined)
|
||||||
|
}
|
||||||
|
fn get_current_slot(
|
||||||
|
pt: &PartitionTable,
|
||||||
|
ota: &mut Ota<RmwNorFlashStorage<&mut MutexFlashStorage>>,
|
||||||
|
) -> Result<AppPartitionSubType, FatError> {
|
||||||
|
let booted = pt.booted_partition()?.ok_or(FatError::OTAError)?;
|
||||||
|
let booted_type = booted.partition_type();
|
||||||
|
let booted_ota_type = match booted_type {
|
||||||
|
PartitionType::App(subtype) => subtype,
|
||||||
|
_ => {
|
||||||
|
bail!("Booted partition is not an app partition");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let expected_partition = ota.current_app_partition()?;
|
||||||
|
if expected_partition == booted_ota_type {
|
||||||
|
info!("Booted partition matches expected partition");
|
||||||
|
} else {
|
||||||
|
info!("Booted partition does not match expected partition, fixing ota entry");
|
||||||
|
ota.set_current_app_partition(booted_ota_type)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let fixed = ota.current_app_partition()?;
|
||||||
|
let state = ota.current_ota_state();
|
||||||
|
info!("Expected partition: {expected_partition:?}, current partition: {booted_ota_type:?}, state: {state:?}");
|
||||||
|
|
||||||
|
if fixed != booted_ota_type {
|
||||||
|
bail!(
|
||||||
|
"Could not fix ota entry, booted partition is still not correct: {:?} != {:?}",
|
||||||
|
booted_ota_type,
|
||||||
|
fixed
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(booted_ota_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next_partition(current: AppPartitionSubType) -> FatResult<AppPartitionSubType> {
|
||||||
|
let next = match current {
|
||||||
|
AppPartitionSubType::Ota0 => AppPartitionSubType::Ota1,
|
||||||
|
AppPartitionSubType::Ota1 => AppPartitionSubType::Ota0,
|
||||||
|
_ => {
|
||||||
|
bail!("Current slot is not ota0 or ota1");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(next)
|
||||||
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait BoardInteraction<'a> {
|
pub trait BoardInteraction<'a> {
|
||||||
//fn get_tank_sensor(&mut self) -> Option<&mut TankSensor>;
|
fn get_tank_sensor(&mut self) -> Result<&mut TankSensor<'a>, FatError>;
|
||||||
fn get_esp(&mut self) -> &mut Esp<'a>;
|
fn get_esp(&mut self) -> &mut Esp<'a>;
|
||||||
fn get_config(&mut self) -> &PlantControllerConfig;
|
fn get_config(&mut self) -> &PlantControllerConfig;
|
||||||
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send>;
|
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send>;
|
||||||
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send>;
|
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send>;
|
||||||
fn set_charge_indicator(&mut self, charging: bool) -> Result<()>;
|
async fn get_time(&mut self) -> DateTime<Utc>;
|
||||||
async fn deep_sleep(&mut self, duration_in_ms: u64) -> !;
|
async fn set_time(&mut self, time: &DateTime<FixedOffset>) -> FatResult<()>;
|
||||||
|
async fn set_charge_indicator(&mut self, charging: bool) -> Result<(), FatError>;
|
||||||
|
async fn deep_sleep_ms(&mut self, duration_in_ms: u64) -> !;
|
||||||
|
|
||||||
fn is_day(&self) -> bool;
|
fn is_day(&self) -> bool;
|
||||||
//should be multsampled
|
//should be multsampled
|
||||||
fn light(&mut self, enable: bool) -> Result<()>;
|
async fn light(&mut self, enable: bool) -> Result<(), FatError>;
|
||||||
async fn pump(&mut self, plant: usize, enable: bool) -> Result<()>;
|
async fn pump(&mut self, plant: usize, enable: bool) -> Result<(), FatError>;
|
||||||
async fn pump_current(&mut self, plant: usize) -> Result<Current>;
|
async fn pump_current(&mut self, plant: usize) -> Result<Current, FatError>;
|
||||||
async fn fault(&mut self, plant: usize, enable: bool) -> Result<()>;
|
async fn fault(&mut self, plant: usize, enable: bool) -> Result<(), FatError>;
|
||||||
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32>;
|
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32, FatError>;
|
||||||
async fn general_fault(&mut self, enable: bool);
|
async fn general_fault(&mut self, enable: bool);
|
||||||
async fn test(&mut self) -> Result<()>;
|
async fn test(&mut self) -> Result<(), FatError>;
|
||||||
fn set_config(&mut self, config: PlantControllerConfig);
|
fn set_config(&mut self, config: PlantControllerConfig);
|
||||||
async fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage>;
|
async fn get_mptt_voltage(&mut self) -> Result<Voltage, FatError>;
|
||||||
async fn get_mptt_current(&mut self) -> anyhow::Result<Current>;
|
async fn get_mptt_current(&mut self) -> Result<Current, FatError>;
|
||||||
}
|
|
||||||
|
|
||||||
impl dyn BoardInteraction<'_> {
|
async fn progress(&mut self, counter: u32) {
|
||||||
//the counter is just some arbitrary number that increases whenever some progress was made, try to keep the updates < 10 per second for ux reasons
|
let current = counter % PLANT_COUNT as u32;
|
||||||
async fn _progress(&mut self, counter: u32) {
|
|
||||||
let even = counter % 2 == 0;
|
|
||||||
let current = counter / (PLANT_COUNT as u32);
|
|
||||||
for led in 0..PLANT_COUNT {
|
for led in 0..PLANT_COUNT {
|
||||||
match self.fault(led, current == led as u32).await {
|
if let Err(err) = self.fault(led, current == led as u32).await {
|
||||||
Result::Ok(_) => {}
|
|
||||||
Err(err) => {
|
|
||||||
warn!("Fault on plant {}: {:?}", led, err);
|
warn!("Fault on plant {}: {:?}", led, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let even = counter % 2 == 0;
|
||||||
|
let _ = self.general_fault(even.into()).await;
|
||||||
}
|
}
|
||||||
let _ = self.general_fault(even.into());
|
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct FreePeripherals<'a> {
|
pub struct FreePeripherals<'a> {
|
||||||
// pub gpio0: Gpio0,
|
pub gpio0: GPIO0<'a>,
|
||||||
// pub gpio1: Gpio1,
|
pub gpio2: GPIO2<'a>,
|
||||||
// pub gpio2: Gpio2,
|
pub gpio3: GPIO3<'a>,
|
||||||
// pub gpio3: Gpio3,
|
pub gpio4: GPIO4<'a>,
|
||||||
// pub gpio4: Gpio4,
|
pub gpio5: GPIO5<'a>,
|
||||||
// pub gpio5: Gpio5,
|
|
||||||
pub gpio6: GPIO6<'a>,
|
pub gpio6: GPIO6<'a>,
|
||||||
// pub gpio7: Gpio7,
|
pub gpio7: GPIO7<'a>,
|
||||||
// pub gpio8: Gpio8,
|
pub gpio8: GPIO8<'a>,
|
||||||
// //config button here
|
// //config button here
|
||||||
// pub gpio10: Gpio10,
|
pub gpio10: GPIO10<'a>,
|
||||||
// pub gpio11: Gpio11,
|
pub gpio11: GPIO11<'a>,
|
||||||
// pub gpio12: Gpio12,
|
pub gpio12: GPIO12<'a>,
|
||||||
// pub gpio13: Gpio13,
|
pub gpio13: GPIO13<'a>,
|
||||||
// pub gpio14: Gpio14,
|
pub gpio14: GPIO14<'a>,
|
||||||
// pub gpio15: Gpio15,
|
pub gpio15: GPIO15<'a>,
|
||||||
// pub gpio16: Gpio16,
|
pub gpio16: GPIO16<'a>,
|
||||||
// pub gpio17: Gpio17,
|
pub gpio17: GPIO17<'a>,
|
||||||
// pub gpio18: Gpio18,
|
pub gpio18: GPIO18<'a>,
|
||||||
// //i2c here
|
// //i2c here
|
||||||
// pub gpio21: Gpio21,
|
pub gpio21: GPIO21<'a>,
|
||||||
// pub gpio22: Gpio22,
|
pub gpio22: GPIO22<'a>,
|
||||||
pub gpio23: GPIO23<'a>,
|
pub gpio23: GPIO23<'a>,
|
||||||
// pub gpio24: Gpio24,
|
pub gpio27: GPIO27<'a>,
|
||||||
// pub gpio25: Gpio25,
|
pub twai: TWAI0<'a>,
|
||||||
// pub gpio26: Gpio26,
|
pub pcnt0: Unit<'a, 0>,
|
||||||
// pub gpio27: Gpio27,
|
pub pcnt1: Unit<'a, 1>,
|
||||||
// pub gpio28: Gpio28,
|
pub adc1: ADC1<'a>,
|
||||||
// pub gpio29: Gpio29,
|
|
||||||
// pub gpio30: Gpio30,
|
|
||||||
// pub pcnt0: PCNT0,
|
|
||||||
// pub pcnt1: PCNT1,
|
|
||||||
// pub adc1: ADC1,
|
|
||||||
// pub can: CAN,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! mk_static {
|
use crate::util::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 {
|
impl PlantHal {
|
||||||
// fn create_i2c() -> Mutex<CriticalSectionRawMutex, I2cDriver<'static>> {
|
pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {
|
||||||
// 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())
|
|
||||||
// }
|
|
||||||
|
|
||||||
pub async fn create(spawner: Spawner) -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>> {
|
|
||||||
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
|
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
|
||||||
let peripherals: Peripherals = esp_hal::init(config);
|
let peripherals: Peripherals = esp_hal::init(config);
|
||||||
|
|
||||||
esp_alloc::heap_allocator!(size: 64 * 1024);
|
esp_alloc::heap_allocator!(size: 64 * 1024);
|
||||||
esp_alloc::heap_allocator!(#[link_section = ".dram2_uninit"] size: 64000);
|
esp_alloc::heap_allocator!(#[link_section = ".dram2_uninit"] size: 64000);
|
||||||
|
|
||||||
let rtc: Rtc = Rtc::new(peripherals.LPWR);
|
let mut rtc_peripheral: Rtc = Rtc::new(peripherals.LPWR);
|
||||||
match(TIME_ACCESS.init(rtc)){
|
rtc_peripheral.rwdt.disable();
|
||||||
Result::Ok(_) => {}
|
|
||||||
Err(_) => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
let systimer = SystemTimer::new(peripherals.SYSTIMER);
|
let timg0 = TimerGroup::new(peripherals.TIMG0);
|
||||||
|
let sw_int = SoftwareInterruptControl::new(peripherals.SW_INTERRUPT);
|
||||||
|
esp_rtos::start(timg0.timer0, sw_int.software_interrupt0);
|
||||||
|
|
||||||
let boot_button = Input::new(
|
let boot_button = Input::new(
|
||||||
peripherals.GPIO9,
|
peripherals.GPIO9,
|
||||||
InputConfig::default().with_pull(Pull::None),
|
InputConfig::default().with_pull(Pull::None),
|
||||||
);
|
);
|
||||||
|
|
||||||
let rng = Rng::new(peripherals.RNG);
|
// Reserve GPIO1 for deep sleep wake (configured just before entering sleep)
|
||||||
let timg0 = TimerGroup::new(peripherals.TIMG0);
|
let wake_gpio1 = peripherals.GPIO1;
|
||||||
let esp_wifi_ctrl = &*mk_static!(
|
|
||||||
EspWifiController<'static>,
|
|
||||||
init(timg0.timer0, rng.clone()).expect("Could not init wifi controller")
|
|
||||||
);
|
|
||||||
|
|
||||||
let (controller, interfaces) =
|
let rng = Rng::new();
|
||||||
esp_wifi::wifi::new(&esp_wifi_ctrl, peripherals.WIFI).expect("Could not init wifi");
|
let (controller, interfaces) = esp_radio::wifi::new(peripherals.WIFI, Default::default())
|
||||||
|
.expect("Could not init wifi");
|
||||||
|
|
||||||
use esp_hal::timer::systimer::SystemTimer;
|
let pcnt_module = Pcnt::new(peripherals.PCNT);
|
||||||
esp_hal_embassy::init(systimer.alarm0);
|
|
||||||
|
|
||||||
//let mut adc1 = Adc::new(peripherals.ADC1, adc1_config);
|
|
||||||
//
|
|
||||||
let free_pins = FreePeripherals {
|
let free_pins = FreePeripherals {
|
||||||
// can: peripherals.can,
|
gpio0: peripherals.GPIO0,
|
||||||
// adc1: peripherals.adc1,
|
gpio2: peripherals.GPIO2,
|
||||||
// pcnt0: peripherals.pcnt0,
|
gpio3: peripherals.GPIO3,
|
||||||
// pcnt1: peripherals.pcnt1,
|
gpio4: peripherals.GPIO4,
|
||||||
// gpio0: peripherals.pins.gpio0,
|
gpio5: peripherals.GPIO5,
|
||||||
// gpio1: peripherals.pins.gpio1,
|
|
||||||
// gpio2: peripherals.pins.gpio2,
|
|
||||||
// gpio3: peripherals.pins.gpio3,
|
|
||||||
// gpio4: peripherals.pins.gpio4,
|
|
||||||
// gpio5: peripherals.pins.gpio5,
|
|
||||||
gpio6: peripherals.GPIO6,
|
gpio6: peripherals.GPIO6,
|
||||||
// gpio7: peripherals.pins.gpio7,
|
gpio7: peripherals.GPIO7,
|
||||||
// gpio8: peripherals.pins.gpio8,
|
gpio8: peripherals.GPIO8,
|
||||||
// gpio10: peripherals.pins.gpio10,
|
gpio10: peripherals.GPIO10,
|
||||||
// gpio11: peripherals.pins.gpio11,
|
gpio11: peripherals.GPIO11,
|
||||||
// gpio12: peripherals.pins.gpio12,
|
gpio12: peripherals.GPIO12,
|
||||||
// gpio13: peripherals.pins.gpio13,
|
gpio13: peripherals.GPIO13,
|
||||||
// gpio14: peripherals.pins.gpio14,
|
gpio14: peripherals.GPIO14,
|
||||||
// gpio15: peripherals.pins.gpio15,
|
gpio15: peripherals.GPIO15,
|
||||||
// gpio16: peripherals.pins.gpio16,
|
gpio16: peripherals.GPIO16,
|
||||||
// gpio17: peripherals.pins.gpio17,
|
gpio17: peripherals.GPIO17,
|
||||||
// gpio18: peripherals.pins.gpio18,
|
gpio18: peripherals.GPIO18,
|
||||||
// gpio21: peripherals.pins.gpio21,
|
gpio21: peripherals.GPIO21,
|
||||||
// gpio22: peripherals.pins.gpio22,
|
gpio22: peripherals.GPIO22,
|
||||||
gpio23: peripherals.GPIO23,
|
gpio23: peripherals.GPIO23,
|
||||||
// gpio24: peripherals.pins.gpio24,
|
gpio27: peripherals.GPIO27,
|
||||||
// gpio25: peripherals.pins.gpio25,
|
twai: peripherals.TWAI0,
|
||||||
// gpio26: peripherals.pins.gpio26,
|
pcnt0: pcnt_module.unit0,
|
||||||
// gpio27: peripherals.pins.gpio27,
|
pcnt1: pcnt_module.unit1,
|
||||||
// gpio28: peripherals.pins.gpio28,
|
adc1: peripherals.ADC1,
|
||||||
// gpio29: peripherals.pins.gpio29,
|
|
||||||
// gpio30: peripherals.pins.gpio30,
|
|
||||||
};
|
};
|
||||||
//
|
|
||||||
|
|
||||||
let tablebuffer = mk_static!(
|
let tablebuffer = mk_static!(
|
||||||
[u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN],
|
[u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN],
|
||||||
[0u8; 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
|
let bullshit = MutexFlashStorage {
|
||||||
for i in 0..pt.len() {
|
inner: Arc::new(CriticalSectionMutex::new(RefCell::new(FlashStorage::new(
|
||||||
info!("{:?}", pt.get_partition(i));
|
peripherals.FLASH,
|
||||||
}
|
)))),
|
||||||
|
};
|
||||||
|
let flash_storage = mk_static!(MutexFlashStorage, bullshit.clone());
|
||||||
|
let flash_storage_2 = mk_static!(MutexFlashStorage, bullshit.clone());
|
||||||
|
let flash_storage_3 = mk_static!(MutexFlashStorage, bullshit.clone());
|
||||||
|
|
||||||
|
let pt =
|
||||||
|
esp_bootloader_esp_idf::partitions::read_partition_table(flash_storage, tablebuffer)?;
|
||||||
|
|
||||||
let ota_data = mk_static!(
|
let ota_data = mk_static!(
|
||||||
PartitionEntry,
|
PartitionEntry,
|
||||||
pt.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::Data(
|
pt.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::Data(
|
||||||
@@ -274,34 +366,39 @@ impl PlantHal {
|
|||||||
.expect("No OTA data partition found")
|
.expect("No OTA data partition found")
|
||||||
);
|
);
|
||||||
|
|
||||||
let ota_data = mk_static!(
|
let mut ota_data = ota_data.as_embedded_storage(mk_static!(
|
||||||
FlashRegion<FlashStorage>,
|
RmwNorFlashStorage<&mut MutexFlashStorage>,
|
||||||
ota_data.as_embedded_storage(storage_ota)
|
RmwNorFlashStorage::new(flash_storage_2, mk_static!([u8; 4096], [0_u8; 4096]))
|
||||||
);
|
));
|
||||||
|
|
||||||
let mut ota = esp_bootloader_esp_idf::ota::Ota::new(ota_data)?;
|
let state_0 = ota_state(AppPartitionSubType::Ota0, &mut ota_data);
|
||||||
|
let state_1 = ota_state(AppPartitionSubType::Ota1, &mut ota_data);
|
||||||
|
let mut ota = Ota::new(ota_data, 2)?;
|
||||||
|
let running = get_current_slot(&pt, &mut ota)?;
|
||||||
|
let target = next_partition(running)?;
|
||||||
|
|
||||||
let ota_partition = match ota.current_slot()? {
|
info!("Currently running OTA slot: {running:?}");
|
||||||
Slot::None => {
|
info!("Updates will be stored in OTA slot: {target:?}");
|
||||||
panic!("No OTA slot active?");
|
info!("Slot0 state: {state_0:?}");
|
||||||
|
info!("Slot1 state: {state_1:?}");
|
||||||
|
|
||||||
|
//get current_state and next_state here!
|
||||||
|
let ota_target = match target {
|
||||||
|
AppPartitionSubType::Ota0 => pt
|
||||||
|
.find_partition(PartitionType::App(AppPartitionSubType::Ota0))?
|
||||||
|
.context("Partition table invalid no ota0")?,
|
||||||
|
AppPartitionSubType::Ota1 => pt
|
||||||
|
.find_partition(PartitionType::App(AppPartitionSubType::Ota1))?
|
||||||
|
.context("Partition table invalid no ota1")?,
|
||||||
|
_ => {
|
||||||
|
bail!("Invalid target partition");
|
||||||
}
|
}
|
||||||
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 ota_target = mk_static!(PartitionEntry, ota_target);
|
||||||
let storage_ota = mk_static!(FlashStorage, FlashStorage::new());
|
let ota_target = mk_static!(
|
||||||
let ota_next = mk_static!(
|
FlashRegion<MutexFlashStorage>,
|
||||||
FlashRegion<FlashStorage>,
|
ota_target.as_embedded_storage(flash_storage)
|
||||||
ota_next.as_embedded_storage(storage_ota)
|
|
||||||
);
|
);
|
||||||
|
|
||||||
let data_partition = pt
|
let data_partition = pt
|
||||||
@@ -311,208 +408,203 @@ impl PlantHal {
|
|||||||
.expect("Data partition with littlefs not found");
|
.expect("Data partition with littlefs not found");
|
||||||
let data_partition = mk_static!(PartitionEntry, data_partition);
|
let data_partition = mk_static!(PartitionEntry, data_partition);
|
||||||
|
|
||||||
let storage_data = mk_static!(FlashStorage, FlashStorage::new());
|
|
||||||
let data = mk_static!(
|
let data = mk_static!(
|
||||||
FlashRegion<FlashStorage>,
|
FlashRegion<MutexFlashStorage>,
|
||||||
data_partition.as_embedded_storage(storage_data)
|
data_partition.as_embedded_storage(flash_storage_3)
|
||||||
);
|
);
|
||||||
let lfs2filesystem = mk_static!(LittleFs2Filesystem, LittleFs2Filesystem { storage: data });
|
let lfs2filesystem = mk_static!(LittleFs2Filesystem, LittleFs2Filesystem { storage: data });
|
||||||
let alloc = mk_static!(Allocation<LittleFs2Filesystem>, lfs2Filesystem::allocate());
|
let alloc = mk_static!(Allocation<LittleFs2Filesystem>, lfs2Filesystem::allocate());
|
||||||
if lfs2filesystem.is_mountable() {
|
if lfs2filesystem.is_mountable() {
|
||||||
log::info!("Littlefs2 filesystem is mountable");
|
info!("Littlefs2 filesystem is mountable");
|
||||||
} else {
|
} else {
|
||||||
match lfs2filesystem.format() {
|
match lfs2filesystem.format() {
|
||||||
Result::Ok(..) => {
|
Ok(..) => {
|
||||||
log::info!("Littlefs2 filesystem is formatted");
|
info!("Littlefs2 filesystem is formatted");
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
bail!("Littlefs2 filesystem could not be formatted: {:?}", err);
|
error!("Littlefs2 filesystem could not be formatted: {err:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::arc_with_non_send_sync)]
|
||||||
let fs = Arc::new(Mutex::new(
|
let fs = Arc::new(Mutex::new(
|
||||||
lfs2Filesystem::mount(alloc, lfs2filesystem).expect("Could not mount lfs2 filesystem"),
|
lfs2Filesystem::mount(alloc, lfs2filesystem).expect("Could not mount lfs2 filesystem"),
|
||||||
));
|
));
|
||||||
|
|
||||||
|
|
||||||
|
let uart0 =
|
||||||
|
Uart::new(peripherals.UART0, UartConfig::default()).map_err(|_| FatError::String {
|
||||||
|
error: "Uart creation failed".to_string(),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let ap = interfaces.access_point;
|
||||||
|
let sta = interfaces.station;
|
||||||
let mut esp = Esp {
|
let mut esp = Esp {
|
||||||
fs,
|
fs,
|
||||||
rng,
|
rng,
|
||||||
controller: Arc::new(Mutex::new(controller)),
|
controller: Arc::new(Mutex::new(controller)),
|
||||||
interfaces: Some(interfaces),
|
interface_sta: Some(sta),
|
||||||
|
interface_ap: Some(ap),
|
||||||
boot_button,
|
boot_button,
|
||||||
mqtt_client: None,
|
wake_gpio1,
|
||||||
ota,
|
ota,
|
||||||
ota_next,
|
ota_target,
|
||||||
wall_clock_offset: 0,
|
current: running,
|
||||||
|
slot0_state: state_0,
|
||||||
|
slot1_state: state_1,
|
||||||
|
uart0,
|
||||||
|
rtc: rtc_peripheral,
|
||||||
};
|
};
|
||||||
|
|
||||||
//init,reset rtc memory depending on cause
|
//init,reset rtc memory depending on cause
|
||||||
let mut init_rtc_store: bool = false;
|
let mut init_rtc_store: bool = false;
|
||||||
let mut to_config_mode: bool = false;
|
let mut to_config_mode: bool = false;
|
||||||
let reasons = match reset_reason() {
|
let reasons = match reset_reason() {
|
||||||
None => {
|
None => "unknown",
|
||||||
"unknown"
|
Some(reason) => match reason {
|
||||||
}
|
SocResetReason::ChipPowerOn => "power on",
|
||||||
Some(reason) => {
|
SocResetReason::CoreSDIO => "sdio reset",
|
||||||
match reason {
|
SocResetReason::CoreMwdt0 => "Watchdog Main",
|
||||||
SocResetReason::ChipPowerOn => {
|
SocResetReason::CoreMwdt1 => "Watchdog 1",
|
||||||
"power on"
|
SocResetReason::CoreRtcWdt => "Watchdog RTC",
|
||||||
}
|
SocResetReason::Cpu0Mwdt0 => "Watchdog MCpu0",
|
||||||
SocResetReason::CoreSw => {
|
SocResetReason::Cpu0Sw => "software reset cpu0",
|
||||||
"software reset"
|
SocResetReason::SysRtcWdt => "Watchdog Sys rtc",
|
||||||
}
|
SocResetReason::Cpu0Mwdt1 => "cpu0 mwdt1",
|
||||||
SocResetReason::CoreDeepSleep => {
|
SocResetReason::SysSuperWdt => "Watchdog Super",
|
||||||
"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 => {
|
SocResetReason::Cpu0RtcWdt => {
|
||||||
init_rtc_store = true;
|
init_rtc_store = true;
|
||||||
"Watchdog RTC cpu0"
|
"Watchdog RTC cpu0"
|
||||||
}
|
}
|
||||||
SocResetReason::SysBrownOut => {
|
SocResetReason::CoreSw => "software reset",
|
||||||
"sys brown out"
|
SocResetReason::CoreDeepSleep => "deep sleep",
|
||||||
}
|
SocResetReason::SysBrownOut => "sys brown out",
|
||||||
SocResetReason::SysRtcWdt => {
|
SocResetReason::CoreEfuseCrc => "core efuse crc",
|
||||||
"Watchdog Sys rtc"
|
|
||||||
}
|
|
||||||
SocResetReason::Cpu0Mwdt1 => {
|
|
||||||
"cpu0 mwdt1"
|
|
||||||
}
|
|
||||||
SocResetReason::SysSuperWdt => {
|
|
||||||
"Watchdog Super"
|
|
||||||
}
|
|
||||||
SocResetReason::CoreEfuseCrc => {
|
|
||||||
"core efuse crc"
|
|
||||||
}
|
|
||||||
SocResetReason::CoreUsbUart => {
|
SocResetReason::CoreUsbUart => {
|
||||||
|
//TODO still required? or via button ignore? to_config_mode = true;
|
||||||
to_config_mode = true;
|
to_config_mode = true;
|
||||||
"core usb uart"
|
"core usb uart"
|
||||||
}
|
}
|
||||||
SocResetReason::CoreUsbJtag => {
|
SocResetReason::CoreUsbJtag => "core usb jtag",
|
||||||
"core usb jtag"
|
SocResetReason::Cpu0JtagCpu => "cpu0 jtag cpu",
|
||||||
}
|
},
|
||||||
SocResetReason::Cpu0JtagCpu => {
|
|
||||||
"cpu0 jtag cpu"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
LOG_ACCESS.lock().await.log(
|
log(
|
||||||
LogMessage::ResetReason,
|
LogMessage::ResetReason,
|
||||||
init_rtc_store as u32,
|
init_rtc_store as u32,
|
||||||
to_config_mode as u32,
|
to_config_mode as u32,
|
||||||
"",
|
"",
|
||||||
&format!("{reasons:?}"),
|
&format!("{reasons:?}"),
|
||||||
).await;
|
);
|
||||||
|
|
||||||
|
|
||||||
esp.init_rtc_deepsleep_memory(init_rtc_store, to_config_mode)
|
esp.init_rtc_deepsleep_memory(init_rtc_store, to_config_mode)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let config = esp.load_config().await;
|
let config = esp.load_config().await;
|
||||||
|
|
||||||
log::info!("Init rtc driver");
|
info!("Init rtc driver");
|
||||||
// let mut rtc = Ds323x::new_ds3231(MutexDevice::new(&I2C_DRIVER));
|
|
||||||
//
|
|
||||||
// log::info!("Init rtc eeprom driver");
|
|
||||||
// let eeprom = {
|
|
||||||
// Eeprom24x::new_24x32(
|
|
||||||
// MutexDevice::new(&I2C_DRIVER),
|
|
||||||
// SlaveAddr::Alternative(true, true, true),
|
|
||||||
// )
|
|
||||||
// };
|
|
||||||
// let rtc_time = rtc.datetime();
|
|
||||||
// match rtc_time {
|
|
||||||
// OkStd(tt) => {
|
|
||||||
// log::info!("Rtc Module reports time at UTC {}", tt);
|
|
||||||
// }
|
|
||||||
// Err(err) => {
|
|
||||||
// log::info!("Rtc Module could not be read {:?}", err);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// let storage = Storage::new(eeprom, Delay::new(1000));
|
let sda = peripherals.GPIO20;
|
||||||
//let rtc_module: Box<dyn RTCModuleInteraction + Send> =
|
let scl = peripherals.GPIO19;
|
||||||
// Box::new(DS3231Module { rtc, storage }) as Box<dyn RTCModuleInteraction + Send>;
|
|
||||||
|
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 mut bms_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) => {
|
||||||
|
info!("Rtc Module reports time at UTC {tt}");
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
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 {
|
let hal = match config {
|
||||||
Result::Ok(config) => {
|
Ok(config) => {
|
||||||
let battery_interaction: Box<dyn BatteryInteraction + Send> =
|
let battery_interaction: Box<dyn BatteryInteraction + Send> =
|
||||||
match config.hardware.battery {
|
match config.hardware.battery {
|
||||||
BatteryBoardVersion::Disabled => Box::new(NoBatteryMonitor {}),
|
BatteryBoardVersion::Disabled => Box::new(NoBatteryMonitor {}),
|
||||||
// BatteryBoardVersion::BQ34Z100G1 => {
|
|
||||||
// let mut battery_driver = Bq34z100g1Driver {
|
|
||||||
// i2c: MutexDevice::new(&I2C_DRIVER),
|
|
||||||
// delay: Delay::new(0),
|
|
||||||
// flash_block_data: [0; 32],
|
|
||||||
// };
|
|
||||||
// let status = print_battery_bq34z100(&mut battery_driver);
|
|
||||||
// match status {
|
|
||||||
// Ok(_) => {}
|
|
||||||
// Err(err) => {
|
|
||||||
// log(
|
|
||||||
// LogMessage::BatteryCommunicationError,
|
|
||||||
// 0u32,
|
|
||||||
// 0,
|
|
||||||
// "",
|
|
||||||
// &format!("{err:?})"),
|
|
||||||
// );
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// Box::new(BQ34Z100G1 { battery_driver })
|
|
||||||
// }
|
|
||||||
BatteryBoardVersion::WchI2cSlave => {
|
BatteryBoardVersion::WchI2cSlave => {
|
||||||
// TODO use correct implementation once availible
|
let version = ProtocolVersion::read_from_i2c(&mut bms_device);
|
||||||
|
let version_val = match version {
|
||||||
|
Ok(v) => unsafe { core::mem::transmute::<ProtocolVersion, u32>(v) },
|
||||||
|
Err(_) => 0,
|
||||||
|
};
|
||||||
|
if version_val == 1 {
|
||||||
|
//Box::new(WCHI2CSlave { i2c: bms_device })
|
||||||
|
// todo fix the type above
|
||||||
|
Box::new(NoBatteryMonitor {})
|
||||||
|
} else {
|
||||||
|
//todo should be an error variant instead?
|
||||||
Box::new(NoBatteryMonitor {})
|
Box::new(NoBatteryMonitor {})
|
||||||
}
|
}
|
||||||
_ => {
|
|
||||||
todo!()
|
|
||||||
}
|
}
|
||||||
|
BatteryBoardVersion::BQ34Z100G1 => Box::new(NoBatteryMonitor {}),
|
||||||
};
|
};
|
||||||
|
|
||||||
let board_hal: Box<dyn BoardInteraction + Send> = //match config.hardware.board {
|
let board_hal: Box<dyn BoardInteraction + Send> = match config.hardware.board {
|
||||||
//BoardVersion::INITIAL => {
|
BoardVersion::INITIAL => {
|
||||||
initial_hal::create_initial_board(free_pins, config, esp)?
|
initial_hal::create_initial_board(free_pins, config, esp)?
|
||||||
;
|
}
|
||||||
//}
|
BoardVersion::V3 => {
|
||||||
// BoardVersion::V3 => {
|
v3_hal::create_v3(free_pins, esp, config, battery_interaction, rtc_module)?
|
||||||
// v3_hal::create_v3(free_pins, esp, config, battery_interaction, rtc_module)?
|
}
|
||||||
// }
|
BoardVersion::V4 => {
|
||||||
//BoardVersion::V4 => {
|
v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)
|
||||||
// v4_hal::create_v4(free_pins, esp, config, battery_interaction, rtc_module)?
|
.await?
|
||||||
//}
|
}
|
||||||
//_ => {
|
};
|
||||||
// todo!()
|
|
||||||
//}
|
|
||||||
//};
|
|
||||||
|
|
||||||
HAL { board_hal }
|
HAL { board_hal }
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
LOG_ACCESS.lock().await.log(
|
log(
|
||||||
LogMessage::ConfigModeMissingConfig,
|
LogMessage::ConfigModeMissingConfig,
|
||||||
0,
|
0,
|
||||||
0,
|
0,
|
||||||
"",
|
"",
|
||||||
&err.to_string(),
|
&err.to_string(),
|
||||||
).await;
|
);
|
||||||
HAL {
|
HAL {
|
||||||
board_hal: initial_hal::create_initial_board(
|
board_hal: initial_hal::create_initial_board(
|
||||||
free_pins,
|
free_pins,
|
||||||
@@ -525,13 +617,13 @@ impl PlantHal {
|
|||||||
|
|
||||||
Ok(Mutex::new(hal))
|
Ok(Mutex::new(hal))
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
/// Feed the watchdog timer to prevent system reset
|
||||||
pub async fn esp_time() -> DateTime<Utc> {
|
pub fn feed_watchdog() {
|
||||||
DateTime::from_timestamp_micros(TIME_ACCESS.get().await.current_time_us() as i64).unwrap()
|
if let Some(wdt_mutex) = WATCHDOG.try_get() {
|
||||||
}
|
wdt_mutex.lock(|cell| {
|
||||||
|
cell.borrow_mut().feed();
|
||||||
pub async fn esp_set_time(time: DateTime<FixedOffset>) {
|
});
|
||||||
TIME_ACCESS.get().await.set_current_time_us(time.timestamp_micros() as u64);
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,138 +1,133 @@
|
|||||||
use crate::hal::Box;
|
use crate::hal::Box;
|
||||||
use alloc::vec::Vec;
|
use crate::fat_error::FatResult;
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
use bincode::config::Configuration;
|
||||||
|
use bincode::{config, Decode, Encode};
|
||||||
use chrono::{DateTime, Utc};
|
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};
|
||||||
|
|
||||||
// use crate::hal::Box;
|
pub const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
|
||||||
// use alloc::vec::Vec;
|
const CONFIG: Configuration = config::standard();
|
||||||
// use anyhow::{anyhow, bail};
|
|
||||||
// use async_trait::async_trait;
|
|
||||||
// use bincode::config::Configuration;
|
|
||||||
// use bincode::{config, Decode, Encode};
|
|
||||||
// use chrono::{DateTime, Utc};
|
|
||||||
// use ds323x::{DateTimeAccess, Ds323x};
|
|
||||||
// use eeprom24x::addr_size::TwoBytes;
|
|
||||||
// use eeprom24x::page_size::B32;
|
|
||||||
// use eeprom24x::unique_serial::No;
|
|
||||||
// use eeprom24x::Storage;
|
|
||||||
// use embedded_storage::ReadStorage as embedded_storage_ReadStorage;
|
|
||||||
// use embedded_storage::Storage as embedded_storage_Storage;
|
|
||||||
// use serde::{Deserialize, Serialize};
|
|
||||||
//
|
|
||||||
// const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
|
|
||||||
// const CONFIG: Configuration = config::standard();
|
|
||||||
//
|
//
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait RTCModuleInteraction {
|
pub trait RTCModuleInteraction {
|
||||||
async fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader>;
|
async fn get_backup_info(&mut self) -> FatResult<BackupHeader>;
|
||||||
async fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>>;
|
async fn get_backup_config(&mut self, chunk: usize) -> FatResult<([u8; 32], usize, u16)>;
|
||||||
async fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()>;
|
async fn backup_config(&mut self, offset: usize, bytes: &[u8]) -> FatResult<()>;
|
||||||
async fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>>;
|
async fn backup_config_finalize(&mut self, crc: u16, length: usize) -> FatResult<()>;
|
||||||
async fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()>;
|
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;
|
const BACKUP_HEADER_MAX_SIZE: usize = 64;
|
||||||
// #[derive(Serialize, Deserialize, PartialEq, Debug, Default, Encode, Decode)]
|
|
||||||
|
#[derive(Serialize, Deserialize, PartialEq, Debug, Default, Encode, Decode)]
|
||||||
pub struct BackupHeader {
|
pub struct BackupHeader {
|
||||||
pub timestamp: i64,
|
pub timestamp: i64,
|
||||||
crc16: u16,
|
crc16: u16,
|
||||||
pub size: u16,
|
pub size: u16,
|
||||||
}
|
}
|
||||||
//
|
//
|
||||||
// pub struct DS3231Module<'a> {
|
pub struct DS3231Module {
|
||||||
// pub(crate) rtc:
|
pub(crate) rtc: Ds323x<
|
||||||
// Ds323x<ds323x::interface::I2cInterface<MutexDevice<'a, I2cDriver<'a>>>, ds323x::ic::DS3231>,
|
I2cInterface<I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>>,
|
||||||
//
|
DS3231,
|
||||||
// pub(crate) storage: Storage<MutexDevice<'a, I2cDriver<'a>>, B32, TwoBytes, No, Delay>,
|
>,
|
||||||
// }
|
|
||||||
//
|
pub(crate) storage: eeprom24x::Storage<
|
||||||
// impl RTCModuleInteraction for DS3231Module<'_> {
|
I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>,
|
||||||
// fn get_backup_info(&mut self) -> anyhow::Result<BackupHeader> {
|
B32,
|
||||||
// let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
|
TwoBytes,
|
||||||
//
|
No,
|
||||||
// self.storage
|
Delay,
|
||||||
// .read(0, &mut header_page_buffer)
|
>,
|
||||||
// .map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
|
}
|
||||||
//
|
|
||||||
// let (header, len): (BackupHeader, usize) =
|
#[async_trait]
|
||||||
// bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
|
impl RTCModuleInteraction for DS3231Module {
|
||||||
//
|
async fn get_backup_info(&mut self) -> FatResult<BackupHeader> {
|
||||||
// log::info!("Raw header is {:?} with size {}", header_page_buffer, len);
|
let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
|
||||||
// anyhow::Ok(header)
|
|
||||||
// }
|
self.storage.read(0, &mut header_page_buffer)?;
|
||||||
//
|
|
||||||
// fn get_backup_config(&mut self) -> anyhow::Result<Vec<u8>> {
|
let (header, len): (BackupHeader, usize) =
|
||||||
// let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
|
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
|
||||||
//
|
|
||||||
// self.storage
|
log::info!("Raw header is {:?} with size {}", header_page_buffer, len);
|
||||||
// .read(0, &mut header_page_buffer)
|
Ok(header)
|
||||||
// .map_err(|err| anyhow!("Error reading eeprom header {:?}", err))?;
|
}
|
||||||
// let (header, _header_size): (BackupHeader, usize) =
|
|
||||||
// bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
|
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];
|
||||||
// let mut data_buffer = vec![0_u8; header.size as usize];
|
|
||||||
// //read the specified number of bytes after the header
|
self.storage.read(0, &mut header_page_buffer)?;
|
||||||
// self.storage
|
let (header, _header_size): (BackupHeader, usize) =
|
||||||
// .read(BACKUP_HEADER_MAX_SIZE as u32, &mut data_buffer)
|
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
|
||||||
// .map_err(|err| anyhow!("Error reading eeprom data {:?}", err))?;
|
|
||||||
//
|
let mut buf = [0_u8; 32];
|
||||||
// let checksum = X25.checksum(&data_buffer);
|
let offset = chunk * buf.len() + BACKUP_HEADER_MAX_SIZE;
|
||||||
// if checksum != header.crc16 {
|
|
||||||
// bail!(
|
let end: usize = header.size as usize + BACKUP_HEADER_MAX_SIZE;
|
||||||
// "Invalid checksum, got {} but expected {}",
|
let current_end = offset + buf.len();
|
||||||
// checksum,
|
let chunk_size = if current_end > end {
|
||||||
// header.crc16
|
end - offset
|
||||||
// );
|
} else {
|
||||||
// }
|
buf.len()
|
||||||
//
|
};
|
||||||
// anyhow::Ok(data_buffer)
|
if chunk_size == 0 {
|
||||||
// }
|
Ok((buf, 0, header.crc16))
|
||||||
// fn backup_config(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
|
} else {
|
||||||
// let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
|
self.storage.read(offset as u32, &mut buf)?;
|
||||||
//
|
//&buf[..chunk_size];
|
||||||
// let time = self.get_rtc_time()?.timestamp_millis();
|
Ok((buf, chunk_size, header.crc16))
|
||||||
// let checksum = X25.checksum(bytes);
|
}
|
||||||
//
|
}
|
||||||
// let header = BackupHeader {
|
async fn backup_config(&mut self, offset: usize, bytes: &[u8]) -> FatResult<()> {
|
||||||
// crc16: checksum,
|
//skip header and write after
|
||||||
// timestamp: time,
|
self.storage
|
||||||
// size: bytes.len() as u16,
|
.write((BACKUP_HEADER_MAX_SIZE + offset) as u32, &bytes)?;
|
||||||
// };
|
|
||||||
// let config = config::standard();
|
Ok(())
|
||||||
// let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
|
}
|
||||||
// log::info!(
|
|
||||||
// "Raw header is {:?} with size {}",
|
async fn backup_config_finalize(&mut self, crc: u16, length: usize) -> FatResult<()> {
|
||||||
// header_page_buffer,
|
let mut header_page_buffer = [0_u8; BACKUP_HEADER_MAX_SIZE];
|
||||||
// encoded
|
|
||||||
// );
|
let time = self.get_rtc_time().await?.timestamp_millis();
|
||||||
// self.storage
|
let header = BackupHeader {
|
||||||
// .write(0, &header_page_buffer)
|
crc16: crc,
|
||||||
// .map_err(|err| anyhow!("Error writing header {:?}", err))?;
|
timestamp: time,
|
||||||
//
|
size: length as u16,
|
||||||
// //write rest after the header
|
};
|
||||||
// self.storage
|
let config = config::standard();
|
||||||
// .write(BACKUP_HEADER_MAX_SIZE as u32, &bytes)
|
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
|
||||||
// .map_err(|err| anyhow!("Error writing body {:?}", err))?;
|
log::info!(
|
||||||
//
|
"Raw header is {:?} with size {}",
|
||||||
// anyhow::Ok(())
|
header_page_buffer,
|
||||||
// }
|
encoded
|
||||||
//
|
);
|
||||||
// fn get_rtc_time(&mut self) -> anyhow::Result<DateTime<Utc>> {
|
self.storage.write(0, &header_page_buffer)?;
|
||||||
// match self.rtc.datetime() {
|
Ok(())
|
||||||
// OkStd(rtc_time) => anyhow::Ok(rtc_time.and_utc()),
|
}
|
||||||
// Err(err) => {
|
|
||||||
// bail!("Error getting rtc time {:?}", err)
|
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<()> {
|
||||||
// fn set_rtc_time(&mut self, time: &DateTime<Utc>) -> anyhow::Result<()> {
|
let naive_time = time.naive_utc();
|
||||||
// let naive_time = time.naive_utc();
|
Ok(self.rtc.set_datetime(&naive_time)?)
|
||||||
// match self.rtc.set_datetime(&naive_time) {
|
}
|
||||||
// OkStd(_) => anyhow::Ok(()),
|
}
|
||||||
// Err(err) => {
|
|
||||||
// bail!("Error getting rtc time {:?}", err)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|||||||
65
rust/src/hal/shared_flash.rs
Normal file
65
rust/src/hal/shared_flash.rs
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
use alloc::sync::Arc;
|
||||||
|
use core::cell::RefCell;
|
||||||
|
use core::ops::{Deref, DerefMut};
|
||||||
|
use embassy_sync::blocking_mutex::CriticalSectionMutex;
|
||||||
|
use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash};
|
||||||
|
use embedded_storage::ReadStorage;
|
||||||
|
use esp_storage::{FlashStorage, FlashStorageError};
|
||||||
|
use log::info;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct MutexFlashStorage {
|
||||||
|
pub(crate) inner: Arc<CriticalSectionMutex<RefCell<FlashStorage<'static>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReadStorage for MutexFlashStorage {
|
||||||
|
type Error = FlashStorageError;
|
||||||
|
|
||||||
|
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), FlashStorageError> {
|
||||||
|
self.inner
|
||||||
|
.lock(|f| ReadStorage::read(f.borrow_mut().deref_mut(), offset, bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capacity(&self) -> usize {
|
||||||
|
self.inner
|
||||||
|
.lock(|f| ReadStorage::capacity(f.borrow().deref()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl embedded_storage::Storage for MutexFlashStorage {
|
||||||
|
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
|
||||||
|
NorFlash::write(self, offset, bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ErrorType for MutexFlashStorage {
|
||||||
|
type Error = FlashStorageError;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReadNorFlash for MutexFlashStorage {
|
||||||
|
const READ_SIZE: usize = 1;
|
||||||
|
|
||||||
|
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
|
||||||
|
ReadStorage::read(self, offset, bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capacity(&self) -> usize {
|
||||||
|
ReadStorage::capacity(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NorFlash for MutexFlashStorage {
|
||||||
|
const WRITE_SIZE: usize = 1;
|
||||||
|
const ERASE_SIZE: usize = 4096;
|
||||||
|
|
||||||
|
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
|
||||||
|
info!("Erasing flash from 0x{:x} to 0x{:x}", from, to);
|
||||||
|
self.inner
|
||||||
|
.lock(|f| NorFlash::erase(f.borrow_mut().deref_mut(), from, to))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
|
||||||
|
self.inner
|
||||||
|
.lock(|f| NorFlash::write(f.borrow_mut().deref_mut(), offset, bytes))
|
||||||
|
}
|
||||||
|
}
|
||||||
451
rust/src/hal/v3_hal.rs
Normal file
451
rust/src/hal/v3_hal.rs
Normal file
@@ -0,0 +1,451 @@
|
|||||||
|
use crate::bail;
|
||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
|
use crate::hal::esp::{hold_disable, hold_enable};
|
||||||
|
use crate::hal::rtc::RTCModuleInteraction;
|
||||||
|
use crate::hal::v3_shift_register::ShiftRegister40;
|
||||||
|
use crate::hal::water::TankSensor;
|
||||||
|
use crate::hal::{BoardInteraction, FreePeripherals, Sensor, PLANT_COUNT};
|
||||||
|
use crate::log::{log, LogMessage, LOG_ACCESS};
|
||||||
|
use crate::{
|
||||||
|
config::PlantControllerConfig,
|
||||||
|
hal::{battery::BatteryInteraction, esp::Esp},
|
||||||
|
};
|
||||||
|
use alloc::boxed::Box;
|
||||||
|
use alloc::format;
|
||||||
|
use alloc::string::ToString;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::{DateTime, FixedOffset, Utc};
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::mutex::Mutex;
|
||||||
|
use embassy_time::Timer;
|
||||||
|
use embedded_hal::digital::OutputPin as _;
|
||||||
|
use esp_hal::gpio::{Flex, Input, InputConfig, Level, Output, OutputConfig, Pull};
|
||||||
|
use esp_hal::pcnt::channel::CtrlMode::Keep;
|
||||||
|
use esp_hal::pcnt::channel::EdgeMode;
|
||||||
|
use esp_hal::pcnt::channel::EdgeMode::{Hold, Increment};
|
||||||
|
use esp_hal::pcnt::unit::Unit;
|
||||||
|
use measurements::{Current, Voltage};
|
||||||
|
|
||||||
|
const PUMP8_BIT: usize = 0;
|
||||||
|
const PUMP1_BIT: usize = 1;
|
||||||
|
const PUMP2_BIT: usize = 2;
|
||||||
|
const PUMP3_BIT: usize = 3;
|
||||||
|
const PUMP4_BIT: usize = 4;
|
||||||
|
const PUMP5_BIT: usize = 5;
|
||||||
|
const PUMP6_BIT: usize = 6;
|
||||||
|
const PUMP7_BIT: usize = 7;
|
||||||
|
const MS_0: usize = 8;
|
||||||
|
const MS_4: usize = 9;
|
||||||
|
const MS_2: usize = 10;
|
||||||
|
const MS_3: usize = 11;
|
||||||
|
const MS_1: usize = 13;
|
||||||
|
const SENSOR_ON: usize = 12;
|
||||||
|
|
||||||
|
const SENSOR_A_1: u8 = 7;
|
||||||
|
const SENSOR_A_2: u8 = 6;
|
||||||
|
const SENSOR_A_3: u8 = 5;
|
||||||
|
const SENSOR_A_4: u8 = 4;
|
||||||
|
const SENSOR_A_5: u8 = 3;
|
||||||
|
const SENSOR_A_6: u8 = 2;
|
||||||
|
const SENSOR_A_7: u8 = 1;
|
||||||
|
const SENSOR_A_8: u8 = 0;
|
||||||
|
|
||||||
|
const SENSOR_B_1: u8 = 8;
|
||||||
|
const SENSOR_B_2: u8 = 9;
|
||||||
|
const SENSOR_B_3: u8 = 10;
|
||||||
|
const SENSOR_B_4: u8 = 11;
|
||||||
|
const SENSOR_B_5: u8 = 12;
|
||||||
|
const SENSOR_B_6: u8 = 13;
|
||||||
|
const SENSOR_B_7: u8 = 14;
|
||||||
|
const SENSOR_B_8: u8 = 15;
|
||||||
|
|
||||||
|
const CHARGING: usize = 14;
|
||||||
|
const AWAKE: usize = 15;
|
||||||
|
|
||||||
|
const FAULT_3: usize = 16;
|
||||||
|
const FAULT_8: usize = 17;
|
||||||
|
const FAULT_7: usize = 18;
|
||||||
|
const FAULT_6: usize = 19;
|
||||||
|
const FAULT_5: usize = 20;
|
||||||
|
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>,
|
||||||
|
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||||
|
esp: Esp<'a>,
|
||||||
|
shift_register:
|
||||||
|
Mutex<CriticalSectionRawMutex, ShiftRegister40<Output<'a>, Output<'a>, Output<'a>>>,
|
||||||
|
_shift_register_enable_invert: Output<'a>,
|
||||||
|
tank_sensor: TankSensor<'a>,
|
||||||
|
solar_is_day: Input<'a>,
|
||||||
|
light: Output<'a>,
|
||||||
|
main_pump: Output<'a>,
|
||||||
|
general_fault: Output<'a>,
|
||||||
|
pub signal_counter: Unit<'static, 0>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn create_v3(
|
||||||
|
peripherals: FreePeripherals<'static>,
|
||||||
|
esp: Esp<'static>,
|
||||||
|
config: PlantControllerConfig,
|
||||||
|
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||||
|
rtc_module: Box<dyn RTCModuleInteraction + Send>,
|
||||||
|
) -> Result<Box<dyn BoardInteraction<'static> + Send + 'static>, FatError> {
|
||||||
|
log::info!("Start v3");
|
||||||
|
let clock = Output::new(peripherals.gpio15, Level::Low, OutputConfig::default());
|
||||||
|
let latch = Output::new(peripherals.gpio3, Level::Low, OutputConfig::default());
|
||||||
|
let data = Output::new(peripherals.gpio23, Level::Low, OutputConfig::default());
|
||||||
|
let shift_register = ShiftRegister40::new(clock, latch, data);
|
||||||
|
//disable all
|
||||||
|
for mut pin in shift_register.decompose() {
|
||||||
|
let _ = pin.set_low();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set always-on status bits
|
||||||
|
let _ = shift_register.decompose()[AWAKE].set_high();
|
||||||
|
let _ = shift_register.decompose()[CHARGING].set_high();
|
||||||
|
|
||||||
|
// Multiplexer defaults: ms0..ms3 low, ms4 high (disabled)
|
||||||
|
let _ = shift_register.decompose()[MS_0].set_low();
|
||||||
|
let _ = shift_register.decompose()[MS_1].set_low();
|
||||||
|
let _ = shift_register.decompose()[MS_2].set_low();
|
||||||
|
let _ = shift_register.decompose()[MS_3].set_low();
|
||||||
|
let _ = shift_register.decompose()[MS_4].set_high();
|
||||||
|
|
||||||
|
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 tank_sensor = TankSensor::create(
|
||||||
|
one_wire_pin,
|
||||||
|
peripherals.adc1,
|
||||||
|
peripherals.gpio5,
|
||||||
|
tank_power_pin,
|
||||||
|
flow_sensor_pin,
|
||||||
|
peripherals.pcnt1,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let solar_is_day = Input::new(peripherals.gpio7, InputConfig::default());
|
||||||
|
let light = Output::new(peripherals.gpio10, Level::Low, OutputConfig::default());
|
||||||
|
let mut main_pump = Output::new(peripherals.gpio2, Level::Low, OutputConfig::default());
|
||||||
|
main_pump.set_low();
|
||||||
|
let mut general_fault = Output::new(peripherals.gpio6, Level::Low, OutputConfig::default());
|
||||||
|
general_fault.set_low();
|
||||||
|
|
||||||
|
hold_disable(21);
|
||||||
|
let mut shift_register_enable_invert =
|
||||||
|
Output::new(peripherals.gpio21, Level::Low, OutputConfig::default());
|
||||||
|
shift_register_enable_invert.set_low();
|
||||||
|
hold_enable(21);
|
||||||
|
|
||||||
|
let signal_counter = peripherals.pcnt0;
|
||||||
|
|
||||||
|
signal_counter.set_low_limit(None)?;
|
||||||
|
signal_counter.set_high_limit(Some(i16::MAX))?;
|
||||||
|
|
||||||
|
let ch0 = &signal_counter.channel0;
|
||||||
|
let edge_pin = Input::new(peripherals.gpio22, InputConfig::default());
|
||||||
|
ch0.set_edge_signal(edge_pin.peripheral_input());
|
||||||
|
ch0.set_input_mode(Hold, Increment);
|
||||||
|
ch0.set_ctrl_mode(Keep, Keep);
|
||||||
|
signal_counter.listen();
|
||||||
|
|
||||||
|
Ok(Box::new(V3 {
|
||||||
|
config,
|
||||||
|
battery_monitor,
|
||||||
|
rtc_module,
|
||||||
|
esp,
|
||||||
|
shift_register: Mutex::new(shift_register),
|
||||||
|
_shift_register_enable_invert: shift_register_enable_invert,
|
||||||
|
tank_sensor,
|
||||||
|
solar_is_day,
|
||||||
|
light,
|
||||||
|
main_pump,
|
||||||
|
general_fault,
|
||||||
|
signal_counter,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<'a> BoardInteraction<'a> for V3<'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
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_config(&mut self) -> &PlantControllerConfig {
|
||||||
|
&self.config
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send> {
|
||||||
|
&mut self.battery_monitor
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send> {
|
||||||
|
&mut self.rtc_module
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_time(&mut self) -> DateTime<Utc> {
|
||||||
|
self.esp.get_time()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_time(&mut self, time: &DateTime<FixedOffset>) -> FatResult<()> {
|
||||||
|
self.rtc_module.set_rtc_time(&time.to_utc()).await?;
|
||||||
|
self.esp.set_time(time.to_utc());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_charge_indicator(&mut self, charging: bool) -> Result<(), FatError> {
|
||||||
|
let shift_register = self.shift_register.lock().await;
|
||||||
|
if charging {
|
||||||
|
let _ = shift_register.decompose()[CHARGING].set_high();
|
||||||
|
} else {
|
||||||
|
let _ = shift_register.decompose()[CHARGING].set_low();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn deep_sleep_ms(&mut self, duration_in_ms: u64) -> ! {
|
||||||
|
let _ = self.shift_register.lock().await.decompose()[AWAKE].set_low();
|
||||||
|
self.esp.deep_sleep_ms(duration_in_ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_day(&self) -> bool {
|
||||||
|
self.solar_is_day.is_high()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn light(&mut self, enable: bool) -> Result<(), FatError> {
|
||||||
|
hold_disable(10);
|
||||||
|
if enable {
|
||||||
|
self.light.set_high();
|
||||||
|
} else {
|
||||||
|
self.light.set_low();
|
||||||
|
}
|
||||||
|
hold_enable(10);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
async fn pump(&mut self, plant: usize, enable: bool) -> Result<(), FatError> {
|
||||||
|
if enable {
|
||||||
|
self.main_pump.set_high();
|
||||||
|
}
|
||||||
|
|
||||||
|
let index = match plant {
|
||||||
|
0 => PUMP1_BIT,
|
||||||
|
1 => PUMP2_BIT,
|
||||||
|
2 => PUMP3_BIT,
|
||||||
|
3 => PUMP4_BIT,
|
||||||
|
4 => PUMP5_BIT,
|
||||||
|
5 => PUMP6_BIT,
|
||||||
|
6 => PUMP7_BIT,
|
||||||
|
7 => PUMP8_BIT,
|
||||||
|
_ => bail!("Invalid pump {plant}"),
|
||||||
|
};
|
||||||
|
let shift_register = self.shift_register.lock().await;
|
||||||
|
if enable {
|
||||||
|
let _ = shift_register.decompose()[index].set_high();
|
||||||
|
} else {
|
||||||
|
let _ = shift_register.decompose()[index].set_low();
|
||||||
|
}
|
||||||
|
|
||||||
|
if !enable {
|
||||||
|
self.main_pump.set_low();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn pump_current(&mut self, _plant: usize) -> Result<Current, FatError> {
|
||||||
|
bail!("Not implemented in v3")
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fault(&mut self, plant: usize, enable: bool) -> Result<(), FatError> {
|
||||||
|
let index = match plant {
|
||||||
|
0 => FAULT_1,
|
||||||
|
1 => FAULT_2,
|
||||||
|
2 => FAULT_3,
|
||||||
|
3 => FAULT_4,
|
||||||
|
4 => FAULT_5,
|
||||||
|
5 => FAULT_6,
|
||||||
|
6 => FAULT_7,
|
||||||
|
7 => FAULT_8,
|
||||||
|
_ => panic!("Invalid plant id {}", plant),
|
||||||
|
};
|
||||||
|
let shift_register = self.shift_register.lock().await;
|
||||||
|
if enable {
|
||||||
|
let _ = shift_register.decompose()[index].set_high();
|
||||||
|
} else {
|
||||||
|
let _ = shift_register.decompose()[index].set_low();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32, FatError> {
|
||||||
|
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
|
||||||
|
for repeat in 0..REPEAT_MOIST_MEASURE {
|
||||||
|
self.signal_counter.pause();
|
||||||
|
self.signal_counter.clear();
|
||||||
|
//Disable all
|
||||||
|
{
|
||||||
|
let shift_register = self.shift_register.lock().await;
|
||||||
|
shift_register.decompose()[MS_4].set_high()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let sensor_channel = match sensor {
|
||||||
|
Sensor::A => match plant {
|
||||||
|
0 => SENSOR_A_1,
|
||||||
|
1 => SENSOR_A_2,
|
||||||
|
2 => SENSOR_A_3,
|
||||||
|
3 => SENSOR_A_4,
|
||||||
|
4 => SENSOR_A_5,
|
||||||
|
5 => SENSOR_A_6,
|
||||||
|
6 => SENSOR_A_7,
|
||||||
|
7 => SENSOR_A_8,
|
||||||
|
_ => bail!("Invalid plant id {}", plant),
|
||||||
|
},
|
||||||
|
Sensor::B => match plant {
|
||||||
|
0 => SENSOR_B_1,
|
||||||
|
1 => SENSOR_B_2,
|
||||||
|
2 => SENSOR_B_3,
|
||||||
|
3 => SENSOR_B_4,
|
||||||
|
4 => SENSOR_B_5,
|
||||||
|
5 => SENSOR_B_6,
|
||||||
|
6 => SENSOR_B_7,
|
||||||
|
7 => SENSOR_B_8,
|
||||||
|
_ => bail!("Invalid plant id {}", plant),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let is_bit_set = |b: u8| -> bool { sensor_channel & (1 << b) != 0 };
|
||||||
|
{
|
||||||
|
let shift_register = self.shift_register.lock().await;
|
||||||
|
let pin_0 = &mut shift_register.decompose()[MS_0];
|
||||||
|
let pin_1 = &mut shift_register.decompose()[MS_1];
|
||||||
|
let pin_2 = &mut shift_register.decompose()[MS_2];
|
||||||
|
let pin_3 = &mut shift_register.decompose()[MS_3];
|
||||||
|
if is_bit_set(0) {
|
||||||
|
pin_0.set_high()?;
|
||||||
|
} else {
|
||||||
|
pin_0.set_low()?;
|
||||||
|
}
|
||||||
|
if is_bit_set(1) {
|
||||||
|
pin_1.set_high()?;
|
||||||
|
} else {
|
||||||
|
pin_1.set_low()?;
|
||||||
|
}
|
||||||
|
if is_bit_set(2) {
|
||||||
|
pin_2.set_high()?;
|
||||||
|
} else {
|
||||||
|
pin_2.set_low()?;
|
||||||
|
}
|
||||||
|
if is_bit_set(3) {
|
||||||
|
pin_3.set_high()?;
|
||||||
|
} else {
|
||||||
|
pin_3.set_low()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
shift_register.decompose()[MS_4].set_low()?;
|
||||||
|
shift_register.decompose()[SENSOR_ON].set_high()?;
|
||||||
|
}
|
||||||
|
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
|
||||||
|
Timer::after_millis(10).await;
|
||||||
|
self.signal_counter.resume();
|
||||||
|
Timer::after_millis(measurement).await;
|
||||||
|
self.signal_counter.pause();
|
||||||
|
{
|
||||||
|
let shift_register = self.shift_register.lock().await;
|
||||||
|
shift_register.decompose()[MS_4].set_high()?;
|
||||||
|
shift_register.decompose()[SENSOR_ON].set_low()?;
|
||||||
|
}
|
||||||
|
Timer::after_millis(10).await;
|
||||||
|
let unscaled = self.signal_counter.value();
|
||||||
|
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];
|
||||||
|
Ok(median)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn general_fault(&mut self, enable: bool) {
|
||||||
|
hold_disable(6);
|
||||||
|
if enable {
|
||||||
|
self.general_fault.set_high();
|
||||||
|
} else {
|
||||||
|
self.general_fault.set_low();
|
||||||
|
}
|
||||||
|
hold_enable(6);
|
||||||
|
}
|
||||||
|
|
||||||
|
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(100).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).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).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(LogMessage::TestSensor, aa, bb, &plant.to_string(), "");
|
||||||
|
}
|
||||||
|
Timer::after_millis(10).await;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_config(&mut self, config: PlantControllerConfig) {
|
||||||
|
self.config = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_mptt_voltage(&mut self) -> Result<Voltage, FatError> {
|
||||||
|
bail!("Not implemented in v3")
|
||||||
|
}
|
||||||
|
async fn get_mptt_current(&mut self) -> Result<Current, FatError> {
|
||||||
|
bail!("Not implemented in v3")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
//! Serial-in parallel-out shift register
|
//! Serial-in parallel-out shift register
|
||||||
|
#![allow(warnings)]
|
||||||
use core::cell::RefCell;
|
use core::cell::RefCell;
|
||||||
use core::convert::Infallible;
|
use core::convert::Infallible;
|
||||||
use core::iter::Iterator;
|
use core::iter::Iterator;
|
||||||
@@ -7,7 +7,7 @@ use core::mem::{self, MaybeUninit};
|
|||||||
use core::result::{Result, Result::Ok};
|
use core::result::{Result, Result::Ok};
|
||||||
use embedded_hal::digital::OutputPin;
|
use embedded_hal::digital::OutputPin;
|
||||||
|
|
||||||
trait ShiftRegisterInternal {
|
trait ShiftRegisterInternal: Send {
|
||||||
fn update(&self, index: usize, command: bool) -> Result<(), ()>;
|
fn update(&self, index: usize, command: bool) -> Result<(), ()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,9 +47,9 @@ macro_rules! ShiftRegisterBuilder {
|
|||||||
/// Serial-in parallel-out shift register
|
/// Serial-in parallel-out shift register
|
||||||
pub struct $name<Pin1, Pin2, Pin3>
|
pub struct $name<Pin1, Pin2, Pin3>
|
||||||
where
|
where
|
||||||
Pin1: OutputPin,
|
Pin1: OutputPin + Send,
|
||||||
Pin2: OutputPin,
|
Pin2: OutputPin + Send,
|
||||||
Pin3: OutputPin,
|
Pin3: OutputPin + Send,
|
||||||
{
|
{
|
||||||
clock: RefCell<Pin1>,
|
clock: RefCell<Pin1>,
|
||||||
latch: RefCell<Pin2>,
|
latch: RefCell<Pin2>,
|
||||||
@@ -59,9 +59,9 @@ macro_rules! ShiftRegisterBuilder {
|
|||||||
|
|
||||||
impl<Pin1, Pin2, Pin3> ShiftRegisterInternal for $name<Pin1, Pin2, Pin3>
|
impl<Pin1, Pin2, Pin3> ShiftRegisterInternal for $name<Pin1, Pin2, Pin3>
|
||||||
where
|
where
|
||||||
Pin1: OutputPin,
|
Pin1: OutputPin + Send,
|
||||||
Pin2: OutputPin,
|
Pin2: OutputPin + Send,
|
||||||
Pin3: OutputPin,
|
Pin3: OutputPin + Send,
|
||||||
{
|
{
|
||||||
/// Sets the value of the shift register output at `index` to value `command`
|
/// Sets the value of the shift register output at `index` to value `command`
|
||||||
fn update(&self, index: usize, command: bool) -> Result<(), ()> {
|
fn update(&self, index: usize, command: bool) -> Result<(), ()> {
|
||||||
@@ -86,9 +86,9 @@ macro_rules! ShiftRegisterBuilder {
|
|||||||
|
|
||||||
impl<Pin1, Pin2, Pin3> $name<Pin1, Pin2, Pin3>
|
impl<Pin1, Pin2, Pin3> $name<Pin1, Pin2, Pin3>
|
||||||
where
|
where
|
||||||
Pin1: OutputPin,
|
Pin1: OutputPin + Send,
|
||||||
Pin2: OutputPin,
|
Pin2: OutputPin + Send,
|
||||||
Pin3: OutputPin,
|
Pin3: OutputPin + Send,
|
||||||
{
|
{
|
||||||
/// Creates a new SIPO shift register from clock, latch, and data output pins
|
/// Creates a new SIPO shift register from clock, latch, and data output pins
|
||||||
pub fn new(clock: Pin1, latch: Pin2, data: Pin3) -> Self {
|
pub fn new(clock: Pin1, latch: Pin2, data: Pin3) -> Self {
|
||||||
470
rust/src/hal/v4_hal.rs
Normal file
470
rust/src/hal/v4_hal.rs
Normal file
@@ -0,0 +1,470 @@
|
|||||||
|
use crate::config::PlantControllerConfig;
|
||||||
|
use crate::hal::battery::BatteryInteraction;
|
||||||
|
use crate::hal::esp::{hold_disable, hold_enable, 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 chrono::{DateTime, FixedOffset, Utc};
|
||||||
|
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_time::Timer;
|
||||||
|
use esp_hal::{twai, Blocking};
|
||||||
|
//use embedded_hal_bus::i2c::MutexDevice;
|
||||||
|
use crate::bail;
|
||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
|
use crate::hal::v4_sensor::{SensorImpl, SensorInteraction};
|
||||||
|
use crate::log::{LogMessage, LOG_ACCESS};
|
||||||
|
use esp_hal::gpio::{Flex, Input, InputConfig, Level, Output, OutputConfig, Pull};
|
||||||
|
use esp_hal::i2c::master::I2c;
|
||||||
|
use esp_hal::pcnt::channel::CtrlMode::Keep;
|
||||||
|
use esp_hal::pcnt::channel::EdgeMode::{Hold, Increment};
|
||||||
|
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 measurements::Resistance;
|
||||||
|
use measurements::{Current, Voltage};
|
||||||
|
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
||||||
|
|
||||||
|
const MPPT_CURRENT_SHUNT_OHMS: f64 = 0.05_f64;
|
||||||
|
const TWAI_BAUDRATE: twai::BaudRate = twai::BaudRate::B125K;
|
||||||
|
|
||||||
|
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 {},
|
||||||
|
}
|
||||||
|
|
||||||
|
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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn create_v4(
|
||||||
|
peripherals: FreePeripherals<'static>,
|
||||||
|
esp: Esp<'static>,
|
||||||
|
config: PlantControllerConfig,
|
||||||
|
battery_monitor: Box<dyn BatteryInteraction + Send>,
|
||||||
|
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 = Output::new(peripherals.gpio23, Level::Low, OutputConfig::default());
|
||||||
|
general_fault.set_low();
|
||||||
|
|
||||||
|
let extra1 = Output::new(peripherals.gpio6, Level::Low, OutputConfig::default());
|
||||||
|
let extra2 = Output::new(peripherals.gpio15, Level::Low, OutputConfig::default());
|
||||||
|
|
||||||
|
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 tank_sensor = TankSensor::create(
|
||||||
|
one_wire_pin,
|
||||||
|
peripherals.adc1,
|
||||||
|
peripherals.gpio5,
|
||||||
|
tank_power_pin,
|
||||||
|
flow_sensor_pin,
|
||||||
|
peripherals.pcnt1,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
let signal_counter = peripherals.pcnt0;
|
||||||
|
|
||||||
|
signal_counter.set_low_limit(Some(0))?;
|
||||||
|
signal_counter.set_high_limit(Some(i16::MAX))?;
|
||||||
|
|
||||||
|
let ch0 = &signal_counter.channel0;
|
||||||
|
let edge_pin = Input::new(peripherals.gpio22, InputConfig::default());
|
||||||
|
ch0.set_edge_signal(edge_pin.peripheral_input());
|
||||||
|
ch0.set_input_mode(Hold, Increment);
|
||||||
|
ch0.set_ctrl_mode(Keep, Keep);
|
||||||
|
signal_counter.listen();
|
||||||
|
|
||||||
|
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 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 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);
|
||||||
|
let _ = pump_expander.pin_set_low(GPIOBank::Bank0, pin);
|
||||||
|
let _ = pump_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 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 {
|
||||||
|
rtc_module,
|
||||||
|
esp,
|
||||||
|
awake,
|
||||||
|
tank_sensor,
|
||||||
|
light,
|
||||||
|
general_fault,
|
||||||
|
pump_expander,
|
||||||
|
config,
|
||||||
|
battery_monitor,
|
||||||
|
pump_ina,
|
||||||
|
charger,
|
||||||
|
extra1,
|
||||||
|
extra2,
|
||||||
|
sensor,
|
||||||
|
};
|
||||||
|
Ok(Box::new(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<'a> BoardInteraction<'a> for V4<'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
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_config(&mut self) -> &PlantControllerConfig {
|
||||||
|
&self.config
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send> {
|
||||||
|
&mut self.battery_monitor
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send> {
|
||||||
|
&mut self.rtc_module
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_time(&mut self) -> DateTime<Utc> {
|
||||||
|
self.esp.get_time()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_time(&mut self, time: &DateTime<FixedOffset>) -> FatResult<()> {
|
||||||
|
self.rtc_module.set_rtc_time(&time.to_utc()).await?;
|
||||||
|
self.esp.set_time(time.to_utc());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_charge_indicator(&mut self, charging: bool) -> Result<(), FatError> {
|
||||||
|
self.charger.set_charge_indicator(charging)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn deep_sleep_ms(&mut self, duration_in_ms: u64) -> ! {
|
||||||
|
self.awake.set_low();
|
||||||
|
self.charger.power_save();
|
||||||
|
self.esp.deep_sleep_ms(duration_in_ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_day(&self) -> bool {
|
||||||
|
self.charger.is_day()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn light(&mut self, enable: bool) -> Result<(), FatError> {
|
||||||
|
hold_disable(10);
|
||||||
|
self.light.set_level(enable.into());
|
||||||
|
hold_enable(10);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn pump(&mut self, plant: usize, enable: bool) -> FatResult<()> {
|
||||||
|
if enable {
|
||||||
|
self.pump_expander
|
||||||
|
.pin_set_high(GPIOBank::Bank0, plant as u8)?;
|
||||||
|
} else {
|
||||||
|
self.pump_expander
|
||||||
|
.pin_set_low(GPIOBank::Bank0, plant as u8)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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 as u8)?;
|
||||||
|
} else {
|
||||||
|
self.pump_expander
|
||||||
|
.pin_set_low(GPIOBank::Bank1, plant as u8)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32, FatError> {
|
||||||
|
self.sensor.measure_moisture_hz(plant, sensor).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn general_fault(&mut self, enable: bool) {
|
||||||
|
hold_disable(23);
|
||||||
|
self.general_fault.set_level(enable.into());
|
||||||
|
hold_enable(23);
|
||||||
|
}
|
||||||
|
|
||||||
|
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).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).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) {
|
||||||
|
self.config = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,24 @@
|
|||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
|
use crate::hal::Box;
|
||||||
use crate::hal::Sensor;
|
use crate::hal::Sensor;
|
||||||
use crate::log::{log, LogMessage};
|
use crate::log::{LogMessage, LOG_ACCESS};
|
||||||
|
use alloc::format;
|
||||||
use alloc::string::ToString;
|
use alloc::string::ToString;
|
||||||
use embedded_hal_bus::i2c::MutexDevice;
|
use async_trait::async_trait;
|
||||||
use esp_idf_hal::can::CanDriver;
|
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
|
||||||
use esp_idf_hal::delay::Delay;
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
use esp_idf_hal::i2c::I2cDriver;
|
use embassy_time::Timer;
|
||||||
use esp_idf_hal::pcnt::PcntDriver;
|
use esp_hal::i2c::master::I2c;
|
||||||
|
use esp_hal::pcnt::unit::Unit;
|
||||||
|
use esp_hal::twai::Twai;
|
||||||
|
use esp_hal::Blocking;
|
||||||
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
|
||||||
|
|
||||||
const REPEAT_MOIST_MEASURE: usize = 10;
|
const REPEAT_MOIST_MEASURE: usize = 10;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
pub trait SensorInteraction {
|
pub trait SensorInteraction {
|
||||||
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32>;
|
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> FatResult<f32>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MS0: u8 = 1_u8;
|
const MS0: u8 = 1_u8;
|
||||||
@@ -21,18 +28,20 @@ const MS3: u8 = 4_u8;
|
|||||||
const MS4: u8 = 2_u8;
|
const MS4: u8 = 2_u8;
|
||||||
const SENSOR_ON: u8 = 5_u8;
|
const SENSOR_ON: u8 = 5_u8;
|
||||||
|
|
||||||
pub enum SensorImpl<'a> {
|
pub enum SensorImpl {
|
||||||
PulseCounter {
|
PulseCounter {
|
||||||
signal_counter: PcntDriver<'a>,
|
signal_counter: Unit<'static, 0>,
|
||||||
sensor_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
|
sensor_expander:
|
||||||
|
Pca9535Immediate<I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>>,
|
||||||
},
|
},
|
||||||
CanBus {
|
CanBus {
|
||||||
can: CanDriver<'a>,
|
twai: Twai<'static, Blocking>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SensorInteraction for SensorImpl<'_> {
|
#[async_trait]
|
||||||
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
|
impl SensorInteraction for SensorImpl {
|
||||||
|
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> FatResult<f32> {
|
||||||
match self {
|
match self {
|
||||||
SensorImpl::PulseCounter {
|
SensorImpl::PulseCounter {
|
||||||
signal_counter,
|
signal_counter,
|
||||||
@@ -41,8 +50,8 @@ impl SensorInteraction for SensorImpl<'_> {
|
|||||||
} => {
|
} => {
|
||||||
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
|
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
|
||||||
for repeat in 0..REPEAT_MOIST_MEASURE {
|
for repeat in 0..REPEAT_MOIST_MEASURE {
|
||||||
signal_counter.counter_pause()?;
|
signal_counter.pause();
|
||||||
signal_counter.counter_clear()?;
|
signal_counter.clear();
|
||||||
|
|
||||||
//Disable all
|
//Disable all
|
||||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
||||||
@@ -77,42 +86,45 @@ impl SensorInteraction for SensorImpl<'_> {
|
|||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
|
||||||
sensor_expander.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
|
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 measurement = 100; // TODO what is this scaling factor? what is its purpose?
|
||||||
let factor = 1000f32 / measurement as f32;
|
let factor = 1000f32 / measurement as f32;
|
||||||
|
|
||||||
//give some time to stabilize
|
//give some time to stabilize
|
||||||
delay.delay_ms(10);
|
Timer::after_millis(10).await;
|
||||||
signal_counter.counter_resume()?;
|
signal_counter.resume();
|
||||||
delay.delay_ms(measurement);
|
Timer::after_millis(measurement).await;
|
||||||
signal_counter.counter_pause()?;
|
signal_counter.pause();
|
||||||
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
|
||||||
sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
|
sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
|
||||||
delay.delay_ms(10);
|
Timer::after_millis(10).await;
|
||||||
let unscaled = signal_counter.get_counter_value()? as i32;
|
let unscaled = 1337; //signal_counter.get_counter_value()? as i32;
|
||||||
let hz = unscaled as f32 * factor;
|
let hz = unscaled as f32 * factor;
|
||||||
log(
|
LOG_ACCESS
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.log(
|
||||||
LogMessage::RawMeasure,
|
LogMessage::RawMeasure,
|
||||||
unscaled as u32,
|
unscaled as u32,
|
||||||
hz as u32,
|
hz as u32,
|
||||||
&plant.to_string(),
|
&plant.to_string(),
|
||||||
&format!("{sensor:?}"),
|
&format!("{sensor:?}"),
|
||||||
);
|
)
|
||||||
|
.await;
|
||||||
results[repeat] = hz;
|
results[repeat] = hz;
|
||||||
}
|
}
|
||||||
results.sort_by(|a, b| a.partial_cmp(b).unwrap()); // floats don't seem to implement total_ord
|
results.sort_by(|a, b| a.partial_cmp(b).unwrap()); // floats don't seem to implement total_ord
|
||||||
|
|
||||||
let mid = results.len() / 2;
|
let mid = results.len() / 2;
|
||||||
let median = results[mid];
|
let median = results[mid];
|
||||||
anyhow::Ok(median)
|
Ok(median)
|
||||||
}
|
|
||||||
SensorImpl::CanBus { .. } => {
|
|
||||||
todo!()
|
|
||||||
}
|
}
|
||||||
|
SensorImpl::CanBus { twai } => Err(FatError::String {
|
||||||
|
error: "Not yet implemented".to_string(),
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
180
rust/src/hal/water.rs
Normal file
180
rust/src/hal/water.rs
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
use crate::bail;
|
||||||
|
use crate::fat_error::FatError;
|
||||||
|
use crate::hal::{ADC1, TANK_MULTI_SAMPLE};
|
||||||
|
use embassy_time::Timer;
|
||||||
|
use esp_hal::analog::adc::{Adc, AdcCalLine, AdcConfig, AdcPin, Attenuation};
|
||||||
|
use esp_hal::delay::Delay;
|
||||||
|
use esp_hal::gpio::{DriveMode, Flex, Input, InputConfig, Output, OutputConfig, Pull};
|
||||||
|
use esp_hal::pcnt::channel::CtrlMode::Keep;
|
||||||
|
use esp_hal::pcnt::channel::EdgeMode::{Hold, Increment};
|
||||||
|
use esp_hal::pcnt::unit::Unit;
|
||||||
|
use esp_hal::peripherals::GPIO5;
|
||||||
|
use esp_hal::Async;
|
||||||
|
use esp_println::println;
|
||||||
|
use onewire::{ds18b20, Device, DeviceSearch, OneWire, DS18B20};
|
||||||
|
|
||||||
|
unsafe impl Send for TankSensor<'_> {}
|
||||||
|
|
||||||
|
pub struct TankSensor<'a> {
|
||||||
|
one_wire_bus: OneWire<Flex<'a>>,
|
||||||
|
tank_channel: Adc<'a, ADC1<'a>, Async>,
|
||||||
|
tank_power: Output<'a>,
|
||||||
|
tank_pin: AdcPin<GPIO5<'a>, ADC1<'a>, AdcCalLine<ADC1<'a>>>,
|
||||||
|
flow_counter: Unit<'a, 1>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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_drive_mode(DriveMode::OpenDrain)
|
||||||
|
.with_pull(Pull::None),
|
||||||
|
);
|
||||||
|
one_wire_pin.apply_input_config(&InputConfig::default().with_pull(Pull::None));
|
||||||
|
one_wire_pin.set_high();
|
||||||
|
one_wire_pin.set_input_enable(true);
|
||||||
|
one_wire_pin.set_output_enable(true);
|
||||||
|
|
||||||
|
let mut adc1_config = AdcConfig::new();
|
||||||
|
let tank_pin =
|
||||||
|
adc1_config.enable_pin_with_cal::<_, AdcCalLine<_>>(gpio5, Attenuation::_11dB);
|
||||||
|
let tank_channel = Adc::new(adc1, adc1_config).into_async();
|
||||||
|
|
||||||
|
let one_wire_bus = OneWire::new(one_wire_pin, false);
|
||||||
|
|
||||||
|
pcnt1.set_high_limit(Some(i16::MAX))?;
|
||||||
|
|
||||||
|
let ch0 = &pcnt1.channel0;
|
||||||
|
ch0.set_edge_signal(flow_sensor.peripheral_input());
|
||||||
|
ch0.set_input_mode(Hold, Increment);
|
||||||
|
ch0.set_ctrl_mode(Keep, Keep);
|
||||||
|
pcnt1.listen();
|
||||||
|
|
||||||
|
Ok(TankSensor {
|
||||||
|
one_wire_bus,
|
||||||
|
tank_channel,
|
||||||
|
tank_power,
|
||||||
|
tank_pin,
|
||||||
|
flow_counter: pcnt1,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset_flow_meter(&mut self) {
|
||||||
|
self.flow_counter.pause();
|
||||||
|
self.flow_counter.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_flow_meter(&mut self) {
|
||||||
|
self.flow_counter.resume();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_flow_meter_value(&mut self) -> i16 {
|
||||||
|
self.flow_counter.value()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop_flow_meter(&mut self) -> i16 {
|
||||||
|
self.flow_counter.pause();
|
||||||
|
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();
|
||||||
|
|
||||||
|
let presence = self.one_wire_bus.reset(&mut delay)?;
|
||||||
|
println!("OneWire: reset presence pulse = {}", presence);
|
||||||
|
if !presence {
|
||||||
|
println!("OneWire: no device responded to reset — check pull-up resistor and wiring");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut search = DeviceSearch::new();
|
||||||
|
let mut water_temp_sensor: Option<Device> = None;
|
||||||
|
let mut devices_found = 0u8;
|
||||||
|
while let Some(device) = self.one_wire_bus.search_next(&mut search, &mut delay)? {
|
||||||
|
devices_found += 1;
|
||||||
|
println!(
|
||||||
|
"OneWire: found device #{} family=0x{:02X} addr={:02X?}",
|
||||||
|
devices_found, device.address[0], device.address
|
||||||
|
);
|
||||||
|
if device.address[0] == ds18b20::FAMILY_CODE {
|
||||||
|
water_temp_sensor = Some(device);
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
println!("OneWire: skipping device — not a DS18B20 (family 0x{:02X} != 0x{:02X})", device.address[0], ds18b20::FAMILY_CODE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if devices_found == 0 {
|
||||||
|
println!("OneWire: search found zero devices on the bus");
|
||||||
|
}
|
||||||
|
|
||||||
|
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 sample in store.iter_mut() {
|
||||||
|
*sample = self.tank_channel.read_oneshot(&mut self.tank_pin).await;
|
||||||
|
//force yield between successful samples
|
||||||
|
Timer::after_millis(10).await;
|
||||||
|
}
|
||||||
|
self.tank_power.set_low();
|
||||||
|
|
||||||
|
store.sort();
|
||||||
|
let median_mv = store[TANK_MULTI_SAMPLE / 2] as f32;
|
||||||
|
Ok(median_mv / 1000.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
108
rust/src/log/interceptor.rs
Normal file
108
rust/src/log/interceptor.rs
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
use alloc::string::String;
|
||||||
|
use alloc::vec::Vec;
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::blocking_mutex::Mutex as BlockingMutex;
|
||||||
|
use log::{LevelFilter, Log, Metadata, Record};
|
||||||
|
|
||||||
|
const MAX_LIVE_LOG_ENTRIES: usize = 64;
|
||||||
|
|
||||||
|
struct LiveLogBuffer {
|
||||||
|
entries: Vec<(u64, String)>,
|
||||||
|
next_seq: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LiveLogBuffer {
|
||||||
|
const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
entries: Vec::new(),
|
||||||
|
next_seq: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push(&mut self, text: String) {
|
||||||
|
if self.entries.len() >= MAX_LIVE_LOG_ENTRIES {
|
||||||
|
self.entries.remove(0);
|
||||||
|
}
|
||||||
|
self.entries.push((self.next_seq, text));
|
||||||
|
self.next_seq += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_after(&self, after: Option<u64>) -> (Vec<(u64, String)>, bool, u64) {
|
||||||
|
let next_seq = self.next_seq;
|
||||||
|
match after {
|
||||||
|
None => (self.entries.clone(), false, next_seq),
|
||||||
|
Some(after_seq) => {
|
||||||
|
let result: Vec<_> = self.entries
|
||||||
|
.iter()
|
||||||
|
.filter(|(seq, _)| *seq > after_seq)
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Dropped if there are entries that should exist (seq > after_seq) but
|
||||||
|
// the oldest retained entry has a higher seq than after_seq + 1.
|
||||||
|
let dropped = if next_seq > after_seq.saturating_add(1) {
|
||||||
|
if let Some((oldest_seq, _)) = self.entries.first() {
|
||||||
|
*oldest_seq > after_seq.saturating_add(1)
|
||||||
|
} else {
|
||||||
|
// Buffer empty but entries were written — all dropped
|
||||||
|
true
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
};
|
||||||
|
|
||||||
|
(result, dropped, next_seq)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct InterceptorLogger {
|
||||||
|
live_log: BlockingMutex<CriticalSectionRawMutex, core::cell::RefCell<LiveLogBuffer>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InterceptorLogger {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
live_log: BlockingMutex::new(core::cell::RefCell::new(LiveLogBuffer::new())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns (entries_after, dropped, next_seq).
|
||||||
|
/// Pass `after = None` to retrieve the entire current buffer.
|
||||||
|
/// Pass `after = Some(seq)` to retrieve only entries with seq > that value.
|
||||||
|
pub fn get_live_logs(&self, after: Option<u64>) -> (Vec<(u64, String)>, bool, u64) {
|
||||||
|
self.live_log.lock(|buf| buf.borrow().get_after(after))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init(&'static self) {
|
||||||
|
match log::set_logger(self).map(|()| log::set_max_level(LevelFilter::Info)) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(_e) => {
|
||||||
|
esp_println::println!("ERROR: Logger already set");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Log for InterceptorLogger {
|
||||||
|
fn enabled(&self, metadata: &Metadata) -> bool {
|
||||||
|
metadata.level() <= log::Level::Info
|
||||||
|
}
|
||||||
|
|
||||||
|
fn log(&self, record: &Record) {
|
||||||
|
if self.enabled(record.metadata()) {
|
||||||
|
let message = alloc::format!("{}: {}", record.level(), record.args());
|
||||||
|
|
||||||
|
// Print to serial
|
||||||
|
esp_println::println!("{}", message);
|
||||||
|
|
||||||
|
// Store in live log ring buffer
|
||||||
|
self.live_log.lock(|buf| {
|
||||||
|
buf.borrow_mut().push(message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&self) {}
|
||||||
|
}
|
||||||
@@ -1,39 +1,86 @@
|
|||||||
use crate::vec;
|
use crate::vec;
|
||||||
|
use crate::BOARD_ACCESS;
|
||||||
use alloc::string::ToString;
|
use alloc::string::ToString;
|
||||||
use alloc::vec::Vec;
|
use alloc::vec::Vec;
|
||||||
use bytemuck::{AnyBitPattern, Contiguous, Pod, Zeroable};
|
use bytemuck::{AnyBitPattern, Pod, Zeroable};
|
||||||
|
use deranged::RangedU8;
|
||||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::channel::Channel;
|
||||||
use embassy_sync::mutex::Mutex;
|
use embassy_sync::mutex::Mutex;
|
||||||
use embassy_time::Instant;
|
|
||||||
use esp_hal::Persistable;
|
use esp_hal::Persistable;
|
||||||
use log::info;
|
use log::{info, warn};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use strum_macros::IntoStaticStr;
|
use strum_macros::IntoStaticStr;
|
||||||
use unit_enum::UnitEnum;
|
use unit_enum::UnitEnum;
|
||||||
use crate::hal::TIME_ACCESS;
|
|
||||||
|
|
||||||
#[esp_hal::ram(rtc_fast, persistent)]
|
const LOG_ARRAY_SIZE: u8 = 220;
|
||||||
|
const MAX_LOG_ARRAY_INDEX: u8 = LOG_ARRAY_SIZE - 1;
|
||||||
|
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
|
||||||
static mut LOG_ARRAY: LogArray = LogArray {
|
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] }; 256],
|
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,
|
head: 0,
|
||||||
};
|
};
|
||||||
pub static LOG_ACCESS: Mutex<CriticalSectionRawMutex, LogArray> = Mutex::new(unsafe { LOG_ARRAY });
|
|
||||||
|
// this is the only reference created for LOG_ARRAY and the only way to access it
|
||||||
|
#[allow(static_mut_refs)]
|
||||||
|
pub static LOG_ACCESS: Mutex<CriticalSectionRawMutex, &'static mut LogArray> =
|
||||||
|
unsafe { Mutex::new(&mut LOG_ARRAY) };
|
||||||
|
|
||||||
|
mod interceptor;
|
||||||
|
|
||||||
|
pub use interceptor::InterceptorLogger;
|
||||||
|
|
||||||
|
pub static INTERCEPTOR: InterceptorLogger = InterceptorLogger::new();
|
||||||
|
|
||||||
|
pub struct LogRequest {
|
||||||
|
pub message_key: LogMessage,
|
||||||
|
pub number_a: u32,
|
||||||
|
pub number_b: u32,
|
||||||
|
pub txt_short: heapless::String<TXT_SHORT_LENGTH>,
|
||||||
|
pub txt_long: heapless::String<TXT_LONG_LENGTH>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static LOG_CHANNEL: Channel<CriticalSectionRawMutex, LogRequest, 16> = Channel::new();
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
pub async fn log_task() {
|
||||||
|
loop {
|
||||||
|
let request = LOG_CHANNEL.receive().await;
|
||||||
|
LOG_ACCESS
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.log(
|
||||||
|
request.message_key,
|
||||||
|
request.number_a,
|
||||||
|
request.number_b,
|
||||||
|
request.txt_short.as_str(),
|
||||||
|
request.txt_long.as_str(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const TXT_SHORT_LENGTH: usize = 8;
|
const TXT_SHORT_LENGTH: usize = 8;
|
||||||
const TXT_LONG_LENGTH: usize = 32;
|
const TXT_LONG_LENGTH: usize = 32;
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, AnyBitPattern)]
|
#[derive(Debug, Clone, Copy, AnyBitPattern)]
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
pub struct LogArray{
|
pub struct LogArray {
|
||||||
buffer: [LogEntryInner; (u8::MAX_VALUE as usize) +1],
|
buffer: [LogEntryInner; LOG_ARRAY_SIZE as usize],
|
||||||
head: u8
|
head: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl Persistable for LogArray {}
|
unsafe impl Persistable for LogArray {}
|
||||||
unsafe impl Zeroable for LogEntryInner {}
|
unsafe impl Zeroable for LogEntryInner {}
|
||||||
|
|
||||||
unsafe impl Pod for LogEntryInner{}
|
unsafe impl Pod for LogEntryInner {}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
struct LogEntryInner {
|
struct LogEntryInner {
|
||||||
@@ -57,7 +104,7 @@ pub struct LogEntry {
|
|||||||
|
|
||||||
impl From<LogEntryInner> for LogEntry {
|
impl From<LogEntryInner> for LogEntry {
|
||||||
fn from(value: LogEntryInner) -> Self {
|
fn from(value: LogEntryInner) -> Self {
|
||||||
LogEntry{
|
LogEntry {
|
||||||
timestamp: value.timestamp,
|
timestamp: value.timestamp,
|
||||||
message_id: value.message_id,
|
message_id: value.message_id,
|
||||||
a: value.a,
|
a: value.a,
|
||||||
@@ -68,12 +115,36 @@ impl From<LogEntryInner> for LogEntry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
match LOG_CHANNEL.try_send(LogRequest {
|
||||||
|
message_key,
|
||||||
|
number_a,
|
||||||
|
number_b,
|
||||||
|
txt_short: txt_short_stack,
|
||||||
|
txt_long: txt_long_stack,
|
||||||
|
}) {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(_) => {
|
||||||
|
warn!("Log channel full, dropping log entry");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl LogArray {
|
impl LogArray {
|
||||||
pub fn get(&mut self) -> Vec<LogEntry> {
|
pub fn get(&mut self) -> Vec<LogEntry> {
|
||||||
|
let head: RangedU8<0, MAX_LOG_ARRAY_INDEX> =
|
||||||
|
RangedU8::new(self.head).unwrap_or(RangedU8::new_saturating(0));
|
||||||
|
|
||||||
let mut rv: Vec<LogEntry> = Vec::new();
|
let mut rv: Vec<LogEntry> = Vec::new();
|
||||||
let mut index = self.head.wrapping_sub(1);
|
let mut index = head.wrapping_sub(1);
|
||||||
for _ in 0..self.buffer.len() {
|
for _ in 0..self.buffer.len() {
|
||||||
let entry = self.buffer[index as usize];
|
let entry = self.buffer[index.get() as usize];
|
||||||
if (entry.message_id as usize) != LogMessage::Empty.ordinal() {
|
if (entry.message_id as usize) != LogMessage::Empty.ordinal() {
|
||||||
rv.push(entry.into());
|
rv.push(entry.into());
|
||||||
}
|
}
|
||||||
@@ -90,13 +161,13 @@ impl LogArray {
|
|||||||
txt_short: &str,
|
txt_short: &str,
|
||||||
txt_long: &str,
|
txt_long: &str,
|
||||||
) {
|
) {
|
||||||
let mut txt_short_stack: heapless::String<TXT_SHORT_LENGTH> = heapless::String::new();
|
let mut head: RangedU8<0, MAX_LOG_ARRAY_INDEX> =
|
||||||
let mut txt_long_stack: heapless::String<TXT_LONG_LENGTH> = heapless::String::new();
|
RangedU8::new(self.head).unwrap_or(RangedU8::new_saturating(0));
|
||||||
|
|
||||||
limit_length(txt_short, &mut txt_short_stack);
|
let time = {
|
||||||
limit_length(txt_long, &mut txt_long_stack);
|
let mut guard = BOARD_ACCESS.get().await.lock().await;
|
||||||
|
guard.board_hal.get_esp().rtc.current_time_us()
|
||||||
let time = TIME_ACCESS.get().await.current_time_us()/1000;
|
} / 1000;
|
||||||
|
|
||||||
let ordinal = message_key.ordinal() as u16;
|
let ordinal = message_key.ordinal() as u16;
|
||||||
let template: &str = message_key.into();
|
let template: &str = message_key.into();
|
||||||
@@ -106,16 +177,17 @@ impl LogArray {
|
|||||||
template_string = template_string.replace("${txt_long}", txt_long);
|
template_string = template_string.replace("${txt_long}", txt_long);
|
||||||
template_string = template_string.replace("${txt_short}", txt_short);
|
template_string = template_string.replace("${txt_short}", txt_short);
|
||||||
|
|
||||||
info!("{}", template_string);
|
info!("{template_string}");
|
||||||
|
|
||||||
let to_modify = &mut self.buffer[self.head as usize];
|
let to_modify = &mut self.buffer[head.get() as usize];
|
||||||
to_modify.timestamp = time;
|
to_modify.timestamp = time;
|
||||||
to_modify.message_id = ordinal;
|
to_modify.message_id = ordinal;
|
||||||
to_modify.a = number_a;
|
to_modify.a = number_a;
|
||||||
to_modify.b = number_b;
|
to_modify.b = number_b;
|
||||||
to_modify.txt_short.clone_from_slice(&txt_short_stack.as_bytes());
|
to_modify.txt_short.clone_from_slice(txt_short.as_bytes());
|
||||||
to_modify.txt_long.clone_from_slice(&txt_long_stack.as_bytes());
|
to_modify.txt_long.clone_from_slice(txt_long.as_bytes());
|
||||||
self.head = self.head.wrapping_add(1);
|
head = head.wrapping_add(1);
|
||||||
|
self.head = head.get();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,28 +197,43 @@ fn limit_length<const LIMIT: usize>(input: &str, target: &mut heapless::String<L
|
|||||||
Ok(_) => {} //continue adding chars
|
Ok(_) => {} //continue adding chars
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
//clear space for two asci chars
|
//clear space for two asci chars
|
||||||
|
info!("pushing char {char} to limit {LIMIT} current value {target} input {input}");
|
||||||
while target.len() + 2 >= LIMIT {
|
while target.len() + 2 >= LIMIT {
|
||||||
target.pop().unwrap();
|
target.pop();
|
||||||
}
|
}
|
||||||
//add .. to shortened strings
|
//add .. to shortened strings
|
||||||
target.push('.').unwrap();
|
match target.push('.') {
|
||||||
target.push('.').unwrap();
|
Ok(_) => {}
|
||||||
return;
|
Err(_) => {
|
||||||
|
warn!(
|
||||||
|
"Error pushin . to limit {LIMIT} current value {target} input {input}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match target.push('.') {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(_) => {
|
||||||
|
warn!(
|
||||||
|
"Error pushin . to limit {LIMIT} current value {target} input {input}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
while target.len() < LIMIT {
|
while target.len() < LIMIT {
|
||||||
target.push(' ').unwrap();
|
match target.push(' ') {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(_) => {
|
||||||
|
warn!("Error pushing space to limit {LIMIT} current value {target} input {input}")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
#[derive(IntoStaticStr, Serialize, PartialEq, Eq, PartialOrd, Ord, Clone, UnitEnum)]
|
#[derive(IntoStaticStr, Serialize, PartialEq, Eq, PartialOrd, Ord, Clone, UnitEnum)]
|
||||||
pub enum LogMessage {
|
pub enum LogMessage {
|
||||||
#[strum(
|
#[strum(serialize = "")]
|
||||||
serialize = ""
|
|
||||||
)]
|
|
||||||
Empty,
|
Empty,
|
||||||
#[strum(
|
#[strum(
|
||||||
serialize = "Reset due to ${txt_long} requires rtc clear ${number_a} and force config mode ${number_b}"
|
serialize = "Reset due to ${txt_long} requires rtc clear ${number_a} and force config mode ${number_b}"
|
||||||
@@ -180,7 +267,7 @@ pub enum LogMessage {
|
|||||||
StayAlive,
|
StayAlive,
|
||||||
#[strum(serialize = "Connecting mqtt ${txt_short} with id ${txt_long}")]
|
#[strum(serialize = "Connecting mqtt ${txt_short} with id ${txt_long}")]
|
||||||
MqttInfo,
|
MqttInfo,
|
||||||
#[strum(serialize = "Received stay alive with value ${txt_short}")]
|
#[strum(serialize = "Received stay alive with value ${number_a}")]
|
||||||
MqttStayAliveRec,
|
MqttStayAliveRec,
|
||||||
#[strum(serialize = "Unknown topic recieved ${txt_long}")]
|
#[strum(serialize = "Unknown topic recieved ${txt_long}")]
|
||||||
UnknownTopic,
|
UnknownTopic,
|
||||||
@@ -224,6 +311,20 @@ pub enum LogMessage {
|
|||||||
PumpOpenLoopCurrent,
|
PumpOpenLoopCurrent,
|
||||||
#[strum(serialize = "Pump Open current sensor required but did not work: ${number_a}")]
|
#[strum(serialize = "Pump Open current sensor required but did not work: ${number_a}")]
|
||||||
PumpMissingSensorCurrent,
|
PumpMissingSensorCurrent,
|
||||||
|
#[strum(
|
||||||
|
serialize = "Fertilizer applied for ${number_a}s on plant ${number_b} (last application ${txt_short} minutes ago)"
|
||||||
|
)]
|
||||||
|
FertilizerApplied,
|
||||||
|
#[strum(serialize = "MPPT Current sensor could not be reached")]
|
||||||
|
MPPTError,
|
||||||
|
#[strum(
|
||||||
|
serialize = "Trace: a: ${number_a} b: ${number_b} txt_s ${txt_short} long ${txt_long}"
|
||||||
|
)]
|
||||||
|
Trace,
|
||||||
|
#[strum(serialize = "Parsing error reading message")]
|
||||||
|
UnknownMessage,
|
||||||
|
#[strum(serialize = "Going to deep sleep for ${number_a} minutes")]
|
||||||
|
DeepSleep,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
@@ -242,9 +343,9 @@ impl From<&LogMessage> for MessageTranslation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl LogMessage {
|
impl LogMessage {
|
||||||
pub fn to_log_localisation_config() -> Vec<MessageTranslation> {
|
pub fn log_localisation_config() -> Vec<MessageTranslation> {
|
||||||
Vec::from_iter((0..LogMessage::len()).map(|i| {
|
Vec::from_iter((0..LogMessage::len()).map(|i| {
|
||||||
let msg_type = LogMessage::from_ordinal(i).unwrap();
|
let msg_type = LogMessage::from_ordinal(i).unwrap_or(LogMessage::UnknownMessage);
|
||||||
(&msg_type).into()
|
(&msg_type).into()
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|||||||
987
rust/src/main.rs
987
rust/src/main.rs
File diff suppressed because it is too large
Load Diff
34
rust/src/mcutie_3_0_0/Cargo.toml
Normal file
34
rust/src/mcutie_3_0_0/Cargo.toml
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
[package]
|
||||||
|
name = "mcutie"
|
||||||
|
version = "3.0.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
path = "lib.rs"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = []
|
||||||
|
homeassistant = []
|
||||||
|
serde = ["dep:serde", "heapless/serde"]
|
||||||
|
defmt = []
|
||||||
|
log = ["dep:log"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
embassy-net = { version = "0.8.0", default-features = false, features = ["tcp", "dns", "proto-ipv4", "proto-ipv6", "medium-ethernet"] }
|
||||||
|
embassy-sync = { version = "0.8.0", default-features = false }
|
||||||
|
embassy-time = { version = "0.5.1", default-features = false }
|
||||||
|
embassy-futures = { version = "0.1.2", default-features = false }
|
||||||
|
embedded-io = { version = "0.7.1", default-features = false }
|
||||||
|
embedded-io-async = { version = "0.7.0", default-features = false }
|
||||||
|
heapless = { version = "0.7.17", default-features = false }
|
||||||
|
mqttrs = { version = "0.4.1", default-features = false }
|
||||||
|
once_cell = { version = "1.21.3", default-features = false, features = ["critical-section"] }
|
||||||
|
pin-project = { version = "1.1.10", default-features = false }
|
||||||
|
hex = { version = "0.4.3", default-features = false }
|
||||||
|
serde = { version = "1.0.228", default-features = false, features = ["derive"], optional = true }
|
||||||
|
log = { version = "0.4.28", default-features = false, optional = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
futures-executor = "0.3.31"
|
||||||
|
futures-timer = "3.0.3"
|
||||||
|
futures-util = "0.3.31"
|
||||||
124
rust/src/mcutie_3_0_0/buffer.rs
Normal file
124
rust/src/mcutie_3_0_0/buffer.rs
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
use core::{cmp, fmt, ops::Deref};
|
||||||
|
|
||||||
|
use embedded_io::{SliceWriteError, Write};
|
||||||
|
use mqttrs::{encode_slice, Packet};
|
||||||
|
|
||||||
|
use crate::Error;
|
||||||
|
|
||||||
|
/// A stack allocated buffer that can be written to and then read back from.
|
||||||
|
/// Dereferencing as a [`u8`] slice allows access to previously written data.
|
||||||
|
///
|
||||||
|
/// Can be written to with [`write!`] and supports [`embedded_io::Write`] and
|
||||||
|
/// [`embedded_io_async::Write`].
|
||||||
|
pub struct Buffer<const N: usize> {
|
||||||
|
bytes: [u8; N],
|
||||||
|
cursor: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> Default for Buffer<N> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> Buffer<N> {
|
||||||
|
/// Creates a new buffer.
|
||||||
|
pub(crate) const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
bytes: [0; N],
|
||||||
|
cursor: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new buffer and writes the given data into it.
|
||||||
|
pub(crate) fn from(buf: &[u8]) -> Result<Self, Error> {
|
||||||
|
let mut buffer = Self::new();
|
||||||
|
match buffer.write_all(buf) {
|
||||||
|
Ok(()) => Ok(buffer),
|
||||||
|
Err(_) => Err(Error::TooLarge),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn encode_packet(&mut self, packet: &Packet<'_>) -> Result<(), mqttrs::Error> {
|
||||||
|
let len = encode_slice(packet, &mut self.bytes[self.cursor..])?;
|
||||||
|
self.cursor += len;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
/// Serializes a value into this buffer using JSON.
|
||||||
|
pub(crate) fn serialize_json<T: serde::Serialize>(
|
||||||
|
&mut self,
|
||||||
|
value: &T,
|
||||||
|
) -> Result<(), serde_json_core::ser::Error> {
|
||||||
|
let len = serde_json_core::to_slice(value, &mut self.bytes[self.cursor..])?;
|
||||||
|
self.cursor += len;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
/// Deserializes this buffer using JSON into the given type.
|
||||||
|
pub fn deserialize_json<'a, T: serde::Deserialize<'a>>(
|
||||||
|
&'a self,
|
||||||
|
) -> Result<T, serde_json_core::de::Error> {
|
||||||
|
let (result, _) = serde_json_core::from_slice(self)?;
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The number of bytes available for writing into this buffer.
|
||||||
|
pub fn available(&self) -> usize {
|
||||||
|
N - self.cursor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> Deref for Buffer<N> {
|
||||||
|
type Target = [u8];
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.bytes[0..self.cursor]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> fmt::Write for Buffer<N> {
|
||||||
|
fn write_str(&mut self, s: &str) -> fmt::Result {
|
||||||
|
self.write_all(s.as_bytes()).map_err(|_| fmt::Error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> embedded_io::ErrorType for Buffer<N> {
|
||||||
|
type Error = SliceWriteError;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> embedded_io::Write for Buffer<N> {
|
||||||
|
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
|
||||||
|
if buf.is_empty() {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let writable = cmp::min(self.available(), buf.len());
|
||||||
|
if writable == 0 {
|
||||||
|
Err(SliceWriteError::Full)
|
||||||
|
} else {
|
||||||
|
self.bytes[self.cursor..self.cursor + writable].copy_from_slice(buf);
|
||||||
|
self.cursor += writable;
|
||||||
|
Ok(writable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize> embedded_io_async::Write for Buffer<N> {
|
||||||
|
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
|
||||||
|
<Self as embedded_io::Write>::write(self, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn flush(&mut self) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
80
rust/src/mcutie_3_0_0/fmt.rs
Normal file
80
rust/src/mcutie_3_0_0/fmt.rs
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
#![macro_use]
|
||||||
|
|
||||||
|
#[cfg(all(feature = "defmt", feature = "log"))]
|
||||||
|
compile_error!("The `defmt` and `log` features cannot both be enabled at the same time.");
|
||||||
|
|
||||||
|
#[cfg(not(feature = "defmt"))]
|
||||||
|
use core::fmt;
|
||||||
|
|
||||||
|
#[cfg(feature = "defmt")]
|
||||||
|
pub(crate) use ::defmt::Debug2Format;
|
||||||
|
|
||||||
|
#[cfg(not(feature = "defmt"))]
|
||||||
|
pub(crate) struct Debug2Format<D: fmt::Debug>(pub(crate) D);
|
||||||
|
|
||||||
|
#[cfg(feature = "log")]
|
||||||
|
impl<D: fmt::Debug> fmt::Debug for Debug2Format<D> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
self.0.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[collapse_debuginfo(yes)]
|
||||||
|
macro_rules! trace {
|
||||||
|
($s:literal $(, $x:expr)* $(,)?) => {
|
||||||
|
#[cfg(feature = "defmt")]
|
||||||
|
::defmt::trace!($s $(, $x)*);
|
||||||
|
#[cfg(feature = "log")]
|
||||||
|
::log::trace!($s $(, $x)*);
|
||||||
|
#[cfg(not(any(feature="defmt", feature="log")))]
|
||||||
|
let _ = ($( & $x ),*);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[collapse_debuginfo(yes)]
|
||||||
|
macro_rules! debug {
|
||||||
|
($s:literal $(, $x:expr)* $(,)?) => {
|
||||||
|
#[cfg(feature = "defmt")]
|
||||||
|
::defmt::debug!($s $(, $x)*);
|
||||||
|
#[cfg(feature = "log")]
|
||||||
|
::log::debug!($s $(, $x)*);
|
||||||
|
#[cfg(not(any(feature="defmt", feature="log")))]
|
||||||
|
let _ = ($( & $x ),*);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[collapse_debuginfo(yes)]
|
||||||
|
macro_rules! info {
|
||||||
|
($s:literal $(, $x:expr)* $(,)?) => {
|
||||||
|
#[cfg(feature = "defmt")]
|
||||||
|
::defmt::info!($s $(, $x)*);
|
||||||
|
#[cfg(feature = "log")]
|
||||||
|
::log::info!($s $(, $x)*);
|
||||||
|
#[cfg(not(any(feature="defmt", feature="log")))]
|
||||||
|
let _ = ($( & $x ),*);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[collapse_debuginfo(yes)]
|
||||||
|
macro_rules! warn {
|
||||||
|
($s:literal $(, $x:expr)* $(,)?) => {
|
||||||
|
#[cfg(feature = "defmt")]
|
||||||
|
::defmt::warn!($s $(, $x)*);
|
||||||
|
#[cfg(feature = "log")]
|
||||||
|
::log::warn!($s $(, $x)*);
|
||||||
|
#[cfg(not(any(feature="defmt", feature="log")))]
|
||||||
|
let _ = ($( & $x ),*);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[collapse_debuginfo(yes)]
|
||||||
|
macro_rules! error {
|
||||||
|
($s:literal $(, $x:expr)* $(,)?) => {
|
||||||
|
#[cfg(feature = "defmt")]
|
||||||
|
::defmt::error!($s $(, $x)*);
|
||||||
|
#[cfg(feature = "log")]
|
||||||
|
::log::error!($s $(, $x)*);
|
||||||
|
#[cfg(not(any(feature="defmt", feature="log")))]
|
||||||
|
let _ = ($( & $x ),*);
|
||||||
|
};
|
||||||
|
}
|
||||||
120
rust/src/mcutie_3_0_0/homeassistant/binary_sensor.rs
Normal file
120
rust/src/mcutie_3_0_0/homeassistant/binary_sensor.rs
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
//! Tools for publishing a [Home Assistant binary sensor](https://www.home-assistant.io/integrations/binary_sensor.mqtt/).
|
||||||
|
use core::ops::Deref;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::{homeassistant::Component, Error, Publishable, Topic};
|
||||||
|
|
||||||
|
/// The state of the sensor. Can be easily converted to or from a [`bool`].
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(from = "&str", into = "&'static str")]
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub enum BinarySensorState {
|
||||||
|
On,
|
||||||
|
Off,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<BinarySensorState> for &'static str {
|
||||||
|
fn from(state: BinarySensorState) -> Self {
|
||||||
|
match state {
|
||||||
|
BinarySensorState::On => "ON",
|
||||||
|
BinarySensorState::Off => "OFF",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> From<&'a str> for BinarySensorState {
|
||||||
|
fn from(st: &'a str) -> Self {
|
||||||
|
if st == "ON" {
|
||||||
|
Self::On
|
||||||
|
} else {
|
||||||
|
Self::Off
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<bool> for BinarySensorState {
|
||||||
|
fn from(val: bool) -> Self {
|
||||||
|
if val {
|
||||||
|
BinarySensorState::On
|
||||||
|
} else {
|
||||||
|
BinarySensorState::Off
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<BinarySensorState> for bool {
|
||||||
|
fn from(val: BinarySensorState) -> Self {
|
||||||
|
match val {
|
||||||
|
BinarySensorState::On => true,
|
||||||
|
BinarySensorState::Off => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<[u8]> for BinarySensorState {
|
||||||
|
fn as_ref(&self) -> &'static [u8] {
|
||||||
|
match self {
|
||||||
|
Self::On => "ON".as_bytes(),
|
||||||
|
Self::Off => "OFF".as_bytes(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type of sensor.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub enum BinarySensorClass {
|
||||||
|
Battery,
|
||||||
|
BatteryCharging,
|
||||||
|
CarbonMonoxide,
|
||||||
|
Cold,
|
||||||
|
Connectivity,
|
||||||
|
Door,
|
||||||
|
GarageDoor,
|
||||||
|
Gas,
|
||||||
|
Heat,
|
||||||
|
Light,
|
||||||
|
Lock,
|
||||||
|
Moisture,
|
||||||
|
Motion,
|
||||||
|
Moving,
|
||||||
|
Occupancy,
|
||||||
|
Opening,
|
||||||
|
Plug,
|
||||||
|
Power,
|
||||||
|
Presence,
|
||||||
|
Problem,
|
||||||
|
Running,
|
||||||
|
Safety,
|
||||||
|
Smoke,
|
||||||
|
Sound,
|
||||||
|
Tamper,
|
||||||
|
Update,
|
||||||
|
Vibration,
|
||||||
|
Window,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A binary sensor that can publish a [`BinarySensorState`] status.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct BinarySensor {
|
||||||
|
/// The type of sensor
|
||||||
|
pub device_class: Option<BinarySensorClass>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Component for BinarySensor {
|
||||||
|
type State = BinarySensorState;
|
||||||
|
|
||||||
|
fn platform() -> &'static str {
|
||||||
|
"binary_sensor"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_state<T: Deref<Target = str>>(
|
||||||
|
&self,
|
||||||
|
topic: &Topic<T>,
|
||||||
|
state: Self::State,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
topic.with_bytes(state).publish().await
|
||||||
|
}
|
||||||
|
}
|
||||||
40
rust/src/mcutie_3_0_0/homeassistant/button.rs
Normal file
40
rust/src/mcutie_3_0_0/homeassistant/button.rs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
//! Tools for publishing a [Home Assistant button](https://www.home-assistant.io/integrations/button.mqtt/).
|
||||||
|
use core::ops::Deref;
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::{homeassistant::Component, Error, Topic};
|
||||||
|
|
||||||
|
/// The type of button.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub enum ButtonClass {
|
||||||
|
Identify,
|
||||||
|
Restart,
|
||||||
|
Update,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A button that can be pressed.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct Button {
|
||||||
|
/// The type of button.
|
||||||
|
pub device_class: Option<ButtonClass>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Component for Button {
|
||||||
|
type State = ();
|
||||||
|
|
||||||
|
fn platform() -> &'static str {
|
||||||
|
"button"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_state<T: Deref<Target = str>>(
|
||||||
|
&self,
|
||||||
|
_topic: &Topic<T>,
|
||||||
|
_state: Self::State,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
// Buttons don't have a state
|
||||||
|
Err(Error::Invalid)
|
||||||
|
}
|
||||||
|
}
|
||||||
384
rust/src/mcutie_3_0_0/homeassistant/light.rs
Normal file
384
rust/src/mcutie_3_0_0/homeassistant/light.rs
Normal file
@@ -0,0 +1,384 @@
|
|||||||
|
//! Tools for publishing a [Home Assistant light](https://www.home-assistant.io/integrations/light.mqtt/).
|
||||||
|
use core::{ops::Deref, str};
|
||||||
|
|
||||||
|
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
fmt::Debug2Format,
|
||||||
|
homeassistant::{binary_sensor::BinarySensorState, ser::List, Component},
|
||||||
|
Error, Payload, Publishable, Topic,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub enum SupportedColorMode {
|
||||||
|
OnOff,
|
||||||
|
Brightness,
|
||||||
|
#[serde(rename = "color_temp")]
|
||||||
|
ColorTemp,
|
||||||
|
Hs,
|
||||||
|
Xy,
|
||||||
|
Rgb,
|
||||||
|
Rgbw,
|
||||||
|
Rgbww,
|
||||||
|
White,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Default)]
|
||||||
|
struct SerializedColor {
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
h: Option<f32>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
s: Option<f32>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
x: Option<f32>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
y: Option<f32>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
r: Option<u8>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
g: Option<u8>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
b: Option<u8>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
w: Option<u8>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
c: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct LedPayload<'a> {
|
||||||
|
state: BinarySensorState,
|
||||||
|
#[serde(default)]
|
||||||
|
brightness: Option<u8>,
|
||||||
|
#[serde(default)]
|
||||||
|
color_temp: Option<u32>,
|
||||||
|
#[serde(default)]
|
||||||
|
color: Option<SerializedColor>,
|
||||||
|
#[serde(default)]
|
||||||
|
effect: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The color of the light in various forms.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase", tag = "color_mode", content = "color")]
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub enum Color {
|
||||||
|
None,
|
||||||
|
Brightness(u8),
|
||||||
|
ColorTemp(u32),
|
||||||
|
Hs {
|
||||||
|
#[serde(rename = "h")]
|
||||||
|
hue: f32,
|
||||||
|
#[serde(rename = "s")]
|
||||||
|
saturation: f32,
|
||||||
|
},
|
||||||
|
Xy {
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
},
|
||||||
|
Rgb {
|
||||||
|
#[serde(rename = "r")]
|
||||||
|
red: u8,
|
||||||
|
#[serde(rename = "g")]
|
||||||
|
green: u8,
|
||||||
|
#[serde(rename = "b")]
|
||||||
|
blue: u8,
|
||||||
|
},
|
||||||
|
Rgbw {
|
||||||
|
#[serde(rename = "r")]
|
||||||
|
red: u8,
|
||||||
|
#[serde(rename = "g")]
|
||||||
|
green: u8,
|
||||||
|
#[serde(rename = "b")]
|
||||||
|
blue: u8,
|
||||||
|
#[serde(rename = "w")]
|
||||||
|
white: u8,
|
||||||
|
},
|
||||||
|
Rgbww {
|
||||||
|
#[serde(rename = "r")]
|
||||||
|
red: u8,
|
||||||
|
#[serde(rename = "g")]
|
||||||
|
green: u8,
|
||||||
|
#[serde(rename = "b")]
|
||||||
|
blue: u8,
|
||||||
|
#[serde(rename = "c")]
|
||||||
|
cool_white: u8,
|
||||||
|
#[serde(rename = "w")]
|
||||||
|
warm_white: u8,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The state of the light. This can be sent to the broker and received as a
|
||||||
|
/// command from Home Assistant.
|
||||||
|
pub struct LightState<'a> {
|
||||||
|
/// Whether the light is on or off.
|
||||||
|
pub state: BinarySensorState,
|
||||||
|
/// The color of the light.
|
||||||
|
pub color: Color,
|
||||||
|
/// Any effect that is applied.
|
||||||
|
pub effect: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> LightState<'a> {
|
||||||
|
/// Parses the state from a command payload.
|
||||||
|
pub fn from_payload(payload: &'a Payload) -> Result<Self, Error> {
|
||||||
|
let parsed: LedPayload<'a> = match payload.deserialize_json() {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Failed to deserialize packet: {:?}", Debug2Format(&e));
|
||||||
|
if let Ok(s) = str::from_utf8(payload) {
|
||||||
|
trace!("{}", s);
|
||||||
|
}
|
||||||
|
return Err(Error::PacketError);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let color = if let Some(color) = parsed.color {
|
||||||
|
if let Some(x) = color.x {
|
||||||
|
Color::Xy {
|
||||||
|
x,
|
||||||
|
y: color.y.unwrap_or_default(),
|
||||||
|
}
|
||||||
|
} else if let Some(h) = color.h {
|
||||||
|
Color::Hs {
|
||||||
|
hue: h,
|
||||||
|
saturation: color.s.unwrap_or_default(),
|
||||||
|
}
|
||||||
|
} else if let Some(c) = color.c {
|
||||||
|
Color::Rgbww {
|
||||||
|
red: color.r.unwrap_or_default(),
|
||||||
|
green: color.g.unwrap_or_default(),
|
||||||
|
blue: color.b.unwrap_or_default(),
|
||||||
|
cool_white: c,
|
||||||
|
warm_white: color.w.unwrap_or_default(),
|
||||||
|
}
|
||||||
|
} else if let Some(w) = color.w {
|
||||||
|
Color::Rgbw {
|
||||||
|
red: color.r.unwrap_or_default(),
|
||||||
|
green: color.g.unwrap_or_default(),
|
||||||
|
blue: color.b.unwrap_or_default(),
|
||||||
|
white: w,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Color::Rgb {
|
||||||
|
red: color.r.unwrap_or_default(),
|
||||||
|
green: color.g.unwrap_or_default(),
|
||||||
|
blue: color.b.unwrap_or_default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if let Some(color_temp) = parsed.color_temp {
|
||||||
|
Color::ColorTemp(color_temp)
|
||||||
|
} else if let Some(brightness) = parsed.brightness {
|
||||||
|
Color::Brightness(brightness)
|
||||||
|
} else {
|
||||||
|
Color::None
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(LightState {
|
||||||
|
state: parsed.state,
|
||||||
|
color,
|
||||||
|
effect: parsed.effect,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Serialize for LightState<'_> {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
let mut len = 1;
|
||||||
|
|
||||||
|
if self.effect.is_some() {
|
||||||
|
len += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.color {
|
||||||
|
Color::None => {}
|
||||||
|
Color::Brightness(_) | Color::ColorTemp(_) => len += 1,
|
||||||
|
_ => len += 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut serializer = serializer.serialize_struct("LightState", len)?;
|
||||||
|
|
||||||
|
serializer.serialize_field("state", &self.state)?;
|
||||||
|
|
||||||
|
if let Some(effect) = self.effect {
|
||||||
|
serializer.serialize_field("effect", effect)?;
|
||||||
|
} else {
|
||||||
|
serializer.skip_field("effect")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.color {
|
||||||
|
Color::None => {
|
||||||
|
serializer.skip_field("brightness")?;
|
||||||
|
serializer.skip_field("color_temp")?;
|
||||||
|
serializer.skip_field("color")?;
|
||||||
|
}
|
||||||
|
Color::Brightness(b) => {
|
||||||
|
serializer.skip_field("color_temp")?;
|
||||||
|
serializer.skip_field("color")?;
|
||||||
|
|
||||||
|
serializer.serialize_field("brightness", &b)?
|
||||||
|
}
|
||||||
|
Color::ColorTemp(c) => {
|
||||||
|
serializer.skip_field("brightness")?;
|
||||||
|
serializer.skip_field("color")?;
|
||||||
|
|
||||||
|
serializer.serialize_field("color_temp", &c)?
|
||||||
|
}
|
||||||
|
Color::Hs { hue, saturation } => {
|
||||||
|
serializer.skip_field("brightness")?;
|
||||||
|
serializer.skip_field("color_temp")?;
|
||||||
|
|
||||||
|
serializer.serialize_field("color_mode", "hs")?;
|
||||||
|
|
||||||
|
let color = SerializedColor {
|
||||||
|
h: Some(hue),
|
||||||
|
s: Some(saturation),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
serializer.serialize_field("color", &color)?
|
||||||
|
}
|
||||||
|
Color::Xy { x, y } => {
|
||||||
|
serializer.skip_field("brightness")?;
|
||||||
|
serializer.skip_field("color_temp")?;
|
||||||
|
|
||||||
|
serializer.serialize_field("color_mode", "xy")?;
|
||||||
|
|
||||||
|
let color = SerializedColor {
|
||||||
|
x: Some(x),
|
||||||
|
y: Some(y),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
serializer.serialize_field("color", &color)?
|
||||||
|
}
|
||||||
|
Color::Rgb { red, green, blue } => {
|
||||||
|
serializer.skip_field("brightness")?;
|
||||||
|
serializer.skip_field("color_temp")?;
|
||||||
|
|
||||||
|
serializer.serialize_field("color_mode", "rgb")?;
|
||||||
|
|
||||||
|
let color = SerializedColor {
|
||||||
|
r: Some(red),
|
||||||
|
g: Some(green),
|
||||||
|
b: Some(blue),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
serializer.serialize_field("color", &color)?
|
||||||
|
}
|
||||||
|
Color::Rgbw {
|
||||||
|
red,
|
||||||
|
green,
|
||||||
|
blue,
|
||||||
|
white,
|
||||||
|
} => {
|
||||||
|
serializer.skip_field("brightness")?;
|
||||||
|
serializer.skip_field("color_temp")?;
|
||||||
|
|
||||||
|
serializer.serialize_field("color_mode", "rgbw")?;
|
||||||
|
|
||||||
|
let color = SerializedColor {
|
||||||
|
r: Some(red),
|
||||||
|
g: Some(green),
|
||||||
|
b: Some(blue),
|
||||||
|
w: Some(white),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
serializer.serialize_field("color", &color)?
|
||||||
|
}
|
||||||
|
Color::Rgbww {
|
||||||
|
red,
|
||||||
|
green,
|
||||||
|
blue,
|
||||||
|
cool_white,
|
||||||
|
warm_white,
|
||||||
|
} => {
|
||||||
|
serializer.skip_field("brightness")?;
|
||||||
|
serializer.skip_field("color_temp")?;
|
||||||
|
|
||||||
|
serializer.serialize_field("color_mode", "rgbww")?;
|
||||||
|
|
||||||
|
let color = SerializedColor {
|
||||||
|
r: Some(red),
|
||||||
|
g: Some(green),
|
||||||
|
b: Some(blue),
|
||||||
|
c: Some(cool_white),
|
||||||
|
w: Some(warm_white),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
serializer.serialize_field("color", &color)?
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
serializer.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A light entity
|
||||||
|
pub struct Light<'a, const C: usize, const E: usize> {
|
||||||
|
/// The color modes supported by the light.
|
||||||
|
pub supported_color_modes: [SupportedColorMode; C],
|
||||||
|
/// Any effects that can be used.
|
||||||
|
pub effects: [&'a str; E],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const C: usize, const E: usize> Serialize for Light<'_, C, E> {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
let mut len = 2;
|
||||||
|
|
||||||
|
if C > 0 {
|
||||||
|
len += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if E > 0 {
|
||||||
|
len += 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut serializer = serializer.serialize_struct("Light", len)?;
|
||||||
|
|
||||||
|
serializer.serialize_field("schema", "json")?;
|
||||||
|
|
||||||
|
if C > 0 {
|
||||||
|
serializer.serialize_field("sup_clrm", &List::new(&self.supported_color_modes))?;
|
||||||
|
} else {
|
||||||
|
serializer.skip_field("sup_clrm")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if E > 0 {
|
||||||
|
serializer.serialize_field("effect", &true)?;
|
||||||
|
serializer.serialize_field("fx_list", &List::new(&self.effects))?;
|
||||||
|
} else {
|
||||||
|
serializer.skip_field("effect")?;
|
||||||
|
serializer.skip_field("fx_list")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
serializer.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const C: usize, const E: usize> Component for Light<'_, C, E> {
|
||||||
|
type State = LightState<'static>;
|
||||||
|
|
||||||
|
fn platform() -> &'static str {
|
||||||
|
"light"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_state<T: Deref<Target = str>>(
|
||||||
|
&self,
|
||||||
|
topic: &Topic<T>,
|
||||||
|
state: Self::State,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
topic.with_json(state).publish().await
|
||||||
|
}
|
||||||
|
}
|
||||||
295
rust/src/mcutie_3_0_0/homeassistant/mod.rs
Normal file
295
rust/src/mcutie_3_0_0/homeassistant/mod.rs
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
//! Home Assistant auto-discovery and related messages.
|
||||||
|
//!
|
||||||
|
//! Normally you would declare your entities statically in your binary. It is
|
||||||
|
//! then trivial to send out discovery messages or state changes.
|
||||||
|
//!
|
||||||
|
//! ```
|
||||||
|
//! # use mcutie::{Publishable, Topic};
|
||||||
|
//! # use mcutie::homeassistant::{Entity, Device, Origin, AvailabilityState, AvailabilityTopics};
|
||||||
|
//! # use mcutie::homeassistant::binary_sensor::{BinarySensor, BinarySensorClass, BinarySensorState};
|
||||||
|
//! const DEVICE_AVAILABILITY_TOPIC: Topic<&'static str> = Topic::Device("status");
|
||||||
|
//! const MOTION_STATE_TOPIC: Topic<&'static str> = Topic::Device("motion/status");
|
||||||
|
//!
|
||||||
|
//! const DEVICE: Device<'static> = Device::new();
|
||||||
|
//! const ORIGIN: Origin<'static> = Origin::new();
|
||||||
|
//!
|
||||||
|
//! const MOTION_SENSOR: Entity<'static, 1, BinarySensor> = Entity {
|
||||||
|
//! device: DEVICE,
|
||||||
|
//! origin: ORIGIN,
|
||||||
|
//! object_id: "motion",
|
||||||
|
//! unique_id: Some("motion"),
|
||||||
|
//! name: "Motion",
|
||||||
|
//! availability: AvailabilityTopics::All([DEVICE_AVAILABILITY_TOPIC]),
|
||||||
|
//! state_topic: Some(MOTION_STATE_TOPIC),
|
||||||
|
//! command_topic: None,
|
||||||
|
//! component: BinarySensor {
|
||||||
|
//! device_class: Some(BinarySensorClass::Motion),
|
||||||
|
//! },
|
||||||
|
//! };
|
||||||
|
//!
|
||||||
|
//! async fn send_discovery_messages() {
|
||||||
|
//! MOTION_SENSOR.publish_discovery().await.unwrap();
|
||||||
|
//! DEVICE_AVAILABILITY_TOPIC.with_bytes(AvailabilityState::Online).publish().await.unwrap();
|
||||||
|
//! }
|
||||||
|
//!
|
||||||
|
//! async fn send_state(state: BinarySensorState) {
|
||||||
|
//! MOTION_SENSOR.publish_state(state).await.unwrap();
|
||||||
|
//! }
|
||||||
|
//! ```
|
||||||
|
use core::{future::Future, ops::Deref};
|
||||||
|
|
||||||
|
use mqttrs::QoS;
|
||||||
|
use serde::{
|
||||||
|
ser::{Error as _, SerializeStruct},
|
||||||
|
Serialize, Serializer,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
device_id, device_type, homeassistant::ser::DiscoverySerializer, io::publish, Error,
|
||||||
|
McutieTask, MqttMessage, Payload, Publishable, Topic, TopicString, DATA_CHANNEL,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub mod binary_sensor;
|
||||||
|
pub mod button;
|
||||||
|
pub mod light;
|
||||||
|
pub mod sensor;
|
||||||
|
mod ser;
|
||||||
|
|
||||||
|
const HA_STATUS_TOPIC: Topic<&'static str> = Topic::General("homeassistant/status");
|
||||||
|
const STATE_ONLINE: &str = "online";
|
||||||
|
const STATE_OFFLINE: &str = "offline";
|
||||||
|
|
||||||
|
/// A trait representing a specific type of entity in Home Assistant
|
||||||
|
pub trait Component: Serialize {
|
||||||
|
/// The state to publish.
|
||||||
|
type State;
|
||||||
|
|
||||||
|
/// The platform identifier for this entity. Internal.
|
||||||
|
fn platform() -> &'static str;
|
||||||
|
|
||||||
|
/// Publishes this entity's state to the MQTT broker.
|
||||||
|
fn publish_state<T: Deref<Target = str>>(
|
||||||
|
&self,
|
||||||
|
topic: &Topic<T>,
|
||||||
|
state: Self::State,
|
||||||
|
) -> impl Future<Output = Result<(), Error>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'t, T, L, const S: usize> McutieTask<'t, T, L, S>
|
||||||
|
where
|
||||||
|
T: Deref<Target = str> + 't,
|
||||||
|
L: Publishable + 't,
|
||||||
|
{
|
||||||
|
pub(super) async fn ha_after_connected(&self) {
|
||||||
|
let _ = HA_STATUS_TOPIC.subscribe(false).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn ha_handle_update(
|
||||||
|
&self,
|
||||||
|
topic: &Topic<TopicString>,
|
||||||
|
payload: &Payload,
|
||||||
|
) -> bool {
|
||||||
|
if topic == &HA_STATUS_TOPIC {
|
||||||
|
if payload.as_ref() == STATE_ONLINE.as_bytes() {
|
||||||
|
DATA_CHANNEL.send(MqttMessage::HomeAssistantOnline).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Deref<Target = str>> Serialize for Topic<T> {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: serde::Serializer,
|
||||||
|
{
|
||||||
|
let mut topic = TopicString::new();
|
||||||
|
self.to_string(&mut topic)
|
||||||
|
.map_err(|_| S::Error::custom("topic was too large to serialize"))?;
|
||||||
|
serializer.serialize_str(&topic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name_or_device<S>(name: &Option<&str>, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
serializer.serialize_str(name.unwrap_or_else(|| device_type()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents the device in Home Assistant.
|
||||||
|
///
|
||||||
|
/// Can just be the default in which case useful properties such as the ID are
|
||||||
|
/// automatically included.
|
||||||
|
#[derive(Clone, Copy, Default)]
|
||||||
|
pub struct Device<'a> {
|
||||||
|
/// A name to identify the device. If not provided the default device type is
|
||||||
|
/// used.
|
||||||
|
pub name: Option<&'a str>,
|
||||||
|
/// An optional configuration URL for the device.
|
||||||
|
pub configuration_url: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Device<'_> {
|
||||||
|
/// Creates a new default device.
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
name: None,
|
||||||
|
configuration_url: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Serialize for Device<'_> {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
let mut len = 2;
|
||||||
|
if self.configuration_url.is_some() {
|
||||||
|
len += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut serializer = serializer.serialize_struct("Device", len)?;
|
||||||
|
|
||||||
|
serializer.serialize_field("name", self.name.unwrap_or_else(|| device_type()))?;
|
||||||
|
serializer.serialize_field("ids", device_id())?;
|
||||||
|
|
||||||
|
if let Some(cu) = self.configuration_url {
|
||||||
|
serializer.serialize_field("cu", cu)?;
|
||||||
|
} else {
|
||||||
|
serializer.skip_field("cu")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
serializer.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents the device's origin in Home Assistant.
|
||||||
|
///
|
||||||
|
/// Can just be the default in which case useful properties are automatically
|
||||||
|
/// included.
|
||||||
|
#[derive(Clone, Copy, Default, Serialize)]
|
||||||
|
pub struct Origin<'a> {
|
||||||
|
/// A name to identify the device's origin. If not provided the default
|
||||||
|
/// device type is used.
|
||||||
|
#[serde(serialize_with = "name_or_device")]
|
||||||
|
pub name: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Origin<'_> {
|
||||||
|
/// Creates a new default origin.
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self { name: None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single entity for Home Assistant.
|
||||||
|
///
|
||||||
|
/// Calling [`Entity::publish_discovery`] will publish the discovery message to
|
||||||
|
/// allow Home Assistant to detect this entity. Read the
|
||||||
|
/// [Home Assistant MQTT docs](https://www.home-assistant.io/integrations/mqtt/)
|
||||||
|
/// for information on what some of these properties mean.
|
||||||
|
pub struct Entity<'a, const A: usize, C: Component> {
|
||||||
|
/// The device this entity is a part of.
|
||||||
|
pub device: Device<'a>,
|
||||||
|
/// The origin of the device.
|
||||||
|
pub origin: Origin<'a>,
|
||||||
|
/// An object identifier to allow for entity ID customisation in Home Assistant.
|
||||||
|
pub object_id: &'a str,
|
||||||
|
/// An optional unique identifier for the entity.
|
||||||
|
pub unique_id: Option<&'a str>,
|
||||||
|
/// A friendly name for the entity.
|
||||||
|
pub name: &'a str,
|
||||||
|
/// Specifies the availability topics that Home Assistant will listen to to
|
||||||
|
/// determine this entity's availability.
|
||||||
|
pub availability: AvailabilityTopics<'a, A>,
|
||||||
|
/// The state topic that this entity's state is published to.
|
||||||
|
pub state_topic: Option<Topic<&'a str>>,
|
||||||
|
/// The command topic that this entity receives commands from.
|
||||||
|
pub command_topic: Option<Topic<&'a str>>,
|
||||||
|
/// The specific entity.
|
||||||
|
pub component: C,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const A: usize, C: Component> Entity<'_, A, C> {
|
||||||
|
/// Publishes the discovery message for this entity to the broker.
|
||||||
|
pub async fn publish_discovery(&self) -> Result<(), Error> {
|
||||||
|
let mut topic = TopicString::new();
|
||||||
|
topic
|
||||||
|
.push_str(option_env!("HA_DISCOVERY_PREFIX").unwrap_or("homeassistant"))
|
||||||
|
.map_err(|_| Error::TooLarge)?;
|
||||||
|
topic.push('/').map_err(|_| Error::TooLarge)?;
|
||||||
|
topic.push_str(C::platform()).map_err(|_| Error::TooLarge)?;
|
||||||
|
topic.push('/').map_err(|_| Error::TooLarge)?;
|
||||||
|
topic
|
||||||
|
.push_str(self.object_id)
|
||||||
|
.map_err(|_| Error::TooLarge)?;
|
||||||
|
topic.push_str("/config").map_err(|_| Error::TooLarge)?;
|
||||||
|
|
||||||
|
let mut payload = Payload::new();
|
||||||
|
payload.serialize_json(self).map_err(|_| Error::TooLarge)?;
|
||||||
|
|
||||||
|
publish(&topic, &payload, QoS::AtMostOnce, false).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Publishes this entity's state to the broker.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// - [`Error::Invalid`] if the entity doesn't have a state topic.
|
||||||
|
pub async fn publish_state(&self, state: C::State) -> Result<(), Error> {
|
||||||
|
if let Some(topic) = self.state_topic {
|
||||||
|
self.component.publish_state(&topic, state).await
|
||||||
|
} else {
|
||||||
|
Err(Error::Invalid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A payload representing a device or entity's availability.
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub enum AvailabilityState {
|
||||||
|
Online,
|
||||||
|
Offline,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<[u8]> for AvailabilityState {
|
||||||
|
fn as_ref(&self) -> &'static [u8] {
|
||||||
|
match self {
|
||||||
|
Self::Online => STATE_ONLINE.as_bytes(),
|
||||||
|
Self::Offline => STATE_OFFLINE.as_bytes(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The availiabity topics that home assistant will use to determine an entity's
|
||||||
|
/// availability.
|
||||||
|
pub enum AvailabilityTopics<'a, const A: usize> {
|
||||||
|
/// The entity is always available.
|
||||||
|
None,
|
||||||
|
/// The entity is available if all of the topics are publishes as online.
|
||||||
|
All([Topic<&'a str>; A]),
|
||||||
|
/// The entity is available if any of the topics are publishes as online.
|
||||||
|
Any([Topic<&'a str>; A]),
|
||||||
|
/// The entity is available based on the most recent of the topics to
|
||||||
|
/// publish state.
|
||||||
|
Latest([Topic<&'a str>; A]),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const A: usize, C: Component> Serialize for Entity<'_, A, C> {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
let outer = DiscoverySerializer {
|
||||||
|
discovery: self,
|
||||||
|
inner: serializer,
|
||||||
|
};
|
||||||
|
|
||||||
|
self.component.serialize(outer)
|
||||||
|
}
|
||||||
|
}
|
||||||
103
rust/src/mcutie_3_0_0/homeassistant/sensor.rs
Normal file
103
rust/src/mcutie_3_0_0/homeassistant/sensor.rs
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
//! Tools for publishing a [Home Assistant sensor](https://www.home-assistant.io/integrations/sensor.mqtt/).
|
||||||
|
use core::ops::Deref;
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::{homeassistant::Component, Error, Publishable, Topic};
|
||||||
|
|
||||||
|
/// The type of sensor.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
pub enum SensorClass {
|
||||||
|
ApparentPower,
|
||||||
|
Aqi,
|
||||||
|
AtmosphericPressure,
|
||||||
|
Battery,
|
||||||
|
CarbonDioxide,
|
||||||
|
CarbonMonoxide,
|
||||||
|
Current,
|
||||||
|
DataRate,
|
||||||
|
DataSize,
|
||||||
|
Date,
|
||||||
|
Distance,
|
||||||
|
Duration,
|
||||||
|
Energy,
|
||||||
|
EnergyStorage,
|
||||||
|
Enum,
|
||||||
|
Frequency,
|
||||||
|
Gas,
|
||||||
|
Humidity,
|
||||||
|
Illuminance,
|
||||||
|
Irradiance,
|
||||||
|
Moisture,
|
||||||
|
Monetary,
|
||||||
|
NitrogenDioxide,
|
||||||
|
NitrogenMonoxide,
|
||||||
|
NitrousOxide,
|
||||||
|
Ozone,
|
||||||
|
Ph,
|
||||||
|
Pm1,
|
||||||
|
Pm25,
|
||||||
|
Pm10,
|
||||||
|
PowerFactor,
|
||||||
|
Power,
|
||||||
|
Precipitation,
|
||||||
|
PrecipitationIntensity,
|
||||||
|
Pressure,
|
||||||
|
ReactivePower,
|
||||||
|
SignalStrength,
|
||||||
|
SoundPressure,
|
||||||
|
Speed,
|
||||||
|
SulphurDioxide,
|
||||||
|
Temperature,
|
||||||
|
Timestamp,
|
||||||
|
VolatileOrganicCompounds,
|
||||||
|
VolatileOrganicCompoundsParts,
|
||||||
|
Voltage,
|
||||||
|
Volume,
|
||||||
|
VolumeFlowRate,
|
||||||
|
VolumeStorage,
|
||||||
|
Water,
|
||||||
|
Weight,
|
||||||
|
WindSpeed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type of measurement that this entity publishes.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum SensorStateClass {
|
||||||
|
/// A measurement at a singe point in time.
|
||||||
|
Measurement,
|
||||||
|
/// A cumulative total that can increase or decrease over time.
|
||||||
|
Total,
|
||||||
|
/// A cumulative total that can only increase.
|
||||||
|
TotalIncreasing,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A binary sensor that can publish a [`f32`] value.
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct Sensor<'u> {
|
||||||
|
/// The type of sensor.
|
||||||
|
pub device_class: Option<SensorClass>,
|
||||||
|
/// The type of measurement that this sensor reports.
|
||||||
|
pub state_class: Option<SensorStateClass>,
|
||||||
|
/// The unit of measurement for this sensor.
|
||||||
|
pub unit_of_measurement: Option<&'u str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Component for Sensor<'_> {
|
||||||
|
type State = f32;
|
||||||
|
|
||||||
|
fn platform() -> &'static str {
|
||||||
|
"sensor"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_state<T: Deref<Target = str>>(
|
||||||
|
&self,
|
||||||
|
topic: &Topic<T>,
|
||||||
|
state: Self::State,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
topic.with_display(state).publish().await
|
||||||
|
}
|
||||||
|
}
|
||||||
333
rust/src/mcutie_3_0_0/homeassistant/ser.rs
Normal file
333
rust/src/mcutie_3_0_0/homeassistant/ser.rs
Normal file
@@ -0,0 +1,333 @@
|
|||||||
|
use core::ops::Deref;
|
||||||
|
|
||||||
|
use serde::{
|
||||||
|
ser::{SerializeSeq, SerializeStruct},
|
||||||
|
Serialize, Serializer,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
homeassistant::{AvailabilityTopics, Component, Entity},
|
||||||
|
Topic,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub(super) struct AvailabilityTopicItem<'a> {
|
||||||
|
topic: Topic<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AvailabilityTopicList<'a, T: Deref<Target = str>, const N: usize> {
|
||||||
|
list: &'a [Topic<T>; N],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, const N: usize, T: Deref<Target = str>> AvailabilityTopicList<'a, T, N> {
|
||||||
|
pub(super) fn new(list: &'a [Topic<T>; N]) -> Self {
|
||||||
|
Self { list }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Deref<Target = str>, const N: usize> Serialize for AvailabilityTopicList<'_, T, N> {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
let mut serializer = serializer.serialize_seq(Some(N))?;
|
||||||
|
|
||||||
|
for topic in self.list {
|
||||||
|
serializer.serialize_element(&AvailabilityTopicItem {
|
||||||
|
topic: topic.as_ref(),
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
|
serializer.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct List<'a, T: Serialize, const N: usize> {
|
||||||
|
list: &'a [T; N],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: Serialize, const N: usize> List<'a, T, N> {
|
||||||
|
pub(super) fn new(list: &'a [T; N]) -> Self {
|
||||||
|
Self { list }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Serialize, const N: usize> Serialize for List<'_, T, N> {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
let mut serializer = serializer.serialize_seq(Some(N))?;
|
||||||
|
|
||||||
|
for item in self.list {
|
||||||
|
serializer.serialize_element(item)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
serializer.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct DiscoverySerializer<'a, const A: usize, C: Component, S: Serializer> {
|
||||||
|
pub(super) discovery: &'a Entity<'a, A, C>,
|
||||||
|
pub(super) inner: S,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const A: usize, C: Component, S: Serializer> Serializer for DiscoverySerializer<'_, A, C, S> {
|
||||||
|
type Ok = S::Ok;
|
||||||
|
type Error = S::Error;
|
||||||
|
type SerializeSeq = S::SerializeSeq;
|
||||||
|
type SerializeTuple = S::SerializeTuple;
|
||||||
|
type SerializeTupleStruct = S::SerializeTupleStruct;
|
||||||
|
type SerializeTupleVariant = S::SerializeTupleVariant;
|
||||||
|
type SerializeMap = S::SerializeMap;
|
||||||
|
type SerializeStruct = S::SerializeStruct;
|
||||||
|
type SerializeStructVariant = S::SerializeStructVariant;
|
||||||
|
|
||||||
|
fn serialize_struct(
|
||||||
|
self,
|
||||||
|
name: &'static str,
|
||||||
|
mut len: usize,
|
||||||
|
) -> Result<Self::SerializeStruct, Self::Error> {
|
||||||
|
len += 5;
|
||||||
|
if self.discovery.state_topic.is_some() {
|
||||||
|
len += 1;
|
||||||
|
}
|
||||||
|
if self.discovery.command_topic.is_some() {
|
||||||
|
len += 1;
|
||||||
|
}
|
||||||
|
if self.discovery.unique_id.is_some() {
|
||||||
|
len += 1;
|
||||||
|
}
|
||||||
|
if !matches!(self.discovery.availability, AvailabilityTopics::None) {
|
||||||
|
len += 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut serializer = self.inner.serialize_struct(name, len)?;
|
||||||
|
|
||||||
|
serializer.serialize_field("dev", &self.discovery.device)?;
|
||||||
|
serializer.serialize_field("o", &self.discovery.origin)?;
|
||||||
|
serializer.serialize_field("p", C::platform())?;
|
||||||
|
serializer.serialize_field("obj_id", self.discovery.object_id)?;
|
||||||
|
|
||||||
|
serializer.serialize_field("name", self.discovery.name)?;
|
||||||
|
|
||||||
|
if let Some(t) = self.discovery.state_topic {
|
||||||
|
serializer.serialize_field("stat_t", &t)?;
|
||||||
|
} else {
|
||||||
|
serializer.skip_field("stat_t")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(t) = self.discovery.command_topic {
|
||||||
|
serializer.serialize_field("cmd_t", &t)?;
|
||||||
|
} else {
|
||||||
|
serializer.skip_field("cmd_t")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
match &self.discovery.availability {
|
||||||
|
AvailabilityTopics::None => {
|
||||||
|
serializer.skip_field("avty")?;
|
||||||
|
serializer.skip_field("avty_mode")?;
|
||||||
|
}
|
||||||
|
AvailabilityTopics::All(topics) => {
|
||||||
|
serializer.serialize_field("avty_mode", "all")?;
|
||||||
|
serializer.serialize_field("avty", &AvailabilityTopicList::new(topics))?;
|
||||||
|
}
|
||||||
|
AvailabilityTopics::Any(topics) => {
|
||||||
|
serializer.serialize_field("avty_mode", "any")?;
|
||||||
|
serializer.serialize_field("avty", &AvailabilityTopicList::new(topics))?;
|
||||||
|
}
|
||||||
|
AvailabilityTopics::Latest(topics) => {
|
||||||
|
serializer.serialize_field("avty_mode", "latest")?;
|
||||||
|
serializer.serialize_field("avty", &AvailabilityTopicList::new(topics))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(v) = self.discovery.unique_id {
|
||||||
|
serializer.serialize_field("uniq_id", v)?;
|
||||||
|
} else {
|
||||||
|
serializer.skip_field("uniq_id")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(serializer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_some<T>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||||
|
where
|
||||||
|
T: ?Sized + Serialize,
|
||||||
|
{
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_unit_variant(
|
||||||
|
self,
|
||||||
|
_: &'static str,
|
||||||
|
_: u32,
|
||||||
|
_: &'static str,
|
||||||
|
) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_newtype_struct<T>(self, _: &'static str, _: &T) -> Result<Self::Ok, Self::Error>
|
||||||
|
where
|
||||||
|
T: ?Sized + Serialize,
|
||||||
|
{
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_newtype_variant<T>(
|
||||||
|
self,
|
||||||
|
_: &'static str,
|
||||||
|
_: u32,
|
||||||
|
_: &'static str,
|
||||||
|
_: &T,
|
||||||
|
) -> Result<Self::Ok, Self::Error>
|
||||||
|
where
|
||||||
|
T: ?Sized + Serialize,
|
||||||
|
{
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple_struct(
|
||||||
|
self,
|
||||||
|
_: &'static str,
|
||||||
|
_: usize,
|
||||||
|
) -> Result<Self::SerializeTupleStruct, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_tuple_variant(
|
||||||
|
self,
|
||||||
|
_: &'static str,
|
||||||
|
_: u32,
|
||||||
|
_: &'static str,
|
||||||
|
_: usize,
|
||||||
|
) -> Result<Self::SerializeTupleVariant, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_struct_variant(
|
||||||
|
self,
|
||||||
|
_: &'static str,
|
||||||
|
_: u32,
|
||||||
|
_: &'static str,
|
||||||
|
_: usize,
|
||||||
|
) -> Result<Self::SerializeStructVariant, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_i128(self, _: i128) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_u128(self, _: u128) -> Result<Self::Ok, Self::Error> {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_seq<I>(self, _: I) -> Result<Self::Ok, Self::Error>
|
||||||
|
where
|
||||||
|
I: IntoIterator,
|
||||||
|
<I as IntoIterator>::Item: Serialize,
|
||||||
|
{
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_map<K, V, I>(self, _: I) -> Result<Self::Ok, Self::Error>
|
||||||
|
where
|
||||||
|
K: Serialize,
|
||||||
|
V: Serialize,
|
||||||
|
I: IntoIterator<Item = (K, V)>,
|
||||||
|
{
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_str<T>(self, _: &T) -> Result<Self::Ok, Self::Error>
|
||||||
|
where
|
||||||
|
T: ?Sized + core::fmt::Display,
|
||||||
|
{
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_human_readable(&self) -> bool {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
483
rust/src/mcutie_3_0_0/io.rs
Normal file
483
rust/src/mcutie_3_0_0/io.rs
Normal file
@@ -0,0 +1,483 @@
|
|||||||
|
use core::ops::Deref;
|
||||||
|
|
||||||
|
pub(crate) use atomic16::assign_pid;
|
||||||
|
use embassy_futures::select::{select, select4, Either};
|
||||||
|
use embassy_net::{
|
||||||
|
dns::DnsQueryType,
|
||||||
|
tcp::{TcpReader, TcpSocket, TcpWriter},
|
||||||
|
Stack,
|
||||||
|
};
|
||||||
|
use embassy_sync::{
|
||||||
|
blocking_mutex::raw::CriticalSectionRawMutex,
|
||||||
|
pubsub::{PubSubChannel, Subscriber, WaitResult},
|
||||||
|
};
|
||||||
|
use embassy_time::Timer;
|
||||||
|
use embedded_io_async::Write;
|
||||||
|
use mqttrs::{
|
||||||
|
decode_slice, Connect, ConnectReturnCode, LastWill, Packet, Pid, Protocol, Publish, QoS, QosPid,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
device_id, fmt::Debug2Format, pipe::ConnectedPipe, ControlMessage, Error, MqttMessage, Payload,
|
||||||
|
Publishable, Topic, TopicString, CONFIRMATION_TIMEOUT, DATA_CHANNEL, DEFAULT_BACKOFF,
|
||||||
|
RESET_BACKOFF,
|
||||||
|
};
|
||||||
|
|
||||||
|
static SEND_QUEUE: ConnectedPipe<CriticalSectionRawMutex, Payload, 10> = ConnectedPipe::new();
|
||||||
|
|
||||||
|
pub(crate) static CONTROL_CHANNEL: PubSubChannel<CriticalSectionRawMutex, ControlMessage, 2, 5, 0> =
|
||||||
|
PubSubChannel::new();
|
||||||
|
|
||||||
|
type ControlSubscriber = Subscriber<'static, CriticalSectionRawMutex, ControlMessage, 2, 5, 0>;
|
||||||
|
|
||||||
|
pub(crate) async fn subscribe() -> ControlSubscriber {
|
||||||
|
loop {
|
||||||
|
if let Ok(sub) = CONTROL_CHANNEL.subscriber() {
|
||||||
|
return sub;
|
||||||
|
}
|
||||||
|
|
||||||
|
Timer::after_millis(50).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_has_atomic = "16")]
|
||||||
|
mod atomic16 {
|
||||||
|
use core::sync::atomic::{AtomicU16, Ordering};
|
||||||
|
|
||||||
|
use mqttrs::Pid;
|
||||||
|
|
||||||
|
static PID: AtomicU16 = AtomicU16::new(0);
|
||||||
|
|
||||||
|
pub(crate) async fn assign_pid() -> Pid {
|
||||||
|
Pid::new() + PID.fetch_add(1, Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_has_atomic = "16"))]
|
||||||
|
mod atomic16 {
|
||||||
|
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
|
||||||
|
use mqttrs::Pid;
|
||||||
|
|
||||||
|
static PID_MUTEX: Mutex<CriticalSectionRawMutex, u16> = Mutex::new(0);
|
||||||
|
|
||||||
|
pub(crate) async fn assign_pid() -> Pid {
|
||||||
|
let mut locked = PID_MUTEX.lock().await;
|
||||||
|
*locked += 1;
|
||||||
|
|
||||||
|
Pid::new() + *locked
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn send_packet(packet: Packet<'_>) -> Result<(), Error> {
|
||||||
|
let mut buffer = Payload::new();
|
||||||
|
|
||||||
|
match buffer.encode_packet(&packet) {
|
||||||
|
Ok(()) => {
|
||||||
|
debug!(
|
||||||
|
"Sending packet to broker: {:?}",
|
||||||
|
Debug2Format(&packet.get_type())
|
||||||
|
);
|
||||||
|
SEND_QUEUE.push(buffer).await;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
error!("Failed to send packet");
|
||||||
|
Err(Error::PacketError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn wait_for_publish(
|
||||||
|
mut subscriber: ControlSubscriber,
|
||||||
|
expected_pid: Pid,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
match select(
|
||||||
|
async {
|
||||||
|
loop {
|
||||||
|
match subscriber.next_message().await {
|
||||||
|
WaitResult::Lagged(_) => {
|
||||||
|
// Maybe we missed the message?
|
||||||
|
}
|
||||||
|
WaitResult::Message(ControlMessage::Published(published_pid)) => {
|
||||||
|
if published_pid == expected_pid {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Timer::after_millis(CONFIRMATION_TIMEOUT),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Either::First(r) => r,
|
||||||
|
Either::Second(_) => Err(Error::TimedOut),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn publish(
|
||||||
|
topic_name: &str,
|
||||||
|
payload: &[u8],
|
||||||
|
qos: QoS,
|
||||||
|
retain: bool,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
let subscriber = subscribe().await;
|
||||||
|
|
||||||
|
let (qospid, pid) = match qos {
|
||||||
|
QoS::AtMostOnce => (QosPid::AtMostOnce, None),
|
||||||
|
QoS::AtLeastOnce => {
|
||||||
|
let pid = assign_pid().await;
|
||||||
|
(QosPid::AtLeastOnce(pid), Some(pid))
|
||||||
|
}
|
||||||
|
QoS::ExactlyOnce => {
|
||||||
|
let pid = assign_pid().await;
|
||||||
|
(QosPid::ExactlyOnce(pid), Some(pid))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let packet = Packet::Publish(Publish {
|
||||||
|
dup: false,
|
||||||
|
qospid,
|
||||||
|
retain,
|
||||||
|
topic_name,
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
send_packet(packet).await?;
|
||||||
|
|
||||||
|
if let Some(expected_pid) = pid {
|
||||||
|
wait_for_publish(subscriber, expected_pid).await
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn packet_size(buffer: &[u8]) -> Option<usize> {
|
||||||
|
let mut pos = 1;
|
||||||
|
let mut multiplier = 1;
|
||||||
|
let mut value = 0;
|
||||||
|
|
||||||
|
while pos < buffer.len() {
|
||||||
|
value += (buffer[pos] & 127) as usize * multiplier;
|
||||||
|
multiplier *= 128;
|
||||||
|
|
||||||
|
if (buffer[pos] & 128) == 0 {
|
||||||
|
return Some(value + pos + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
pos += 1;
|
||||||
|
if pos == 5 {
|
||||||
|
return Some(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The MQTT task that must be run in order for the stack to operate.
|
||||||
|
pub struct McutieTask<'t, T, L, const S: usize>
|
||||||
|
where
|
||||||
|
T: Deref<Target = str> + 't,
|
||||||
|
L: Publishable + 't,
|
||||||
|
{
|
||||||
|
pub(crate) network: Stack<'t>,
|
||||||
|
pub(crate) broker: &'t str,
|
||||||
|
pub(crate) last_will: Option<L>,
|
||||||
|
pub(crate) username: Option<&'t str>,
|
||||||
|
pub(crate) password: Option<&'t str>,
|
||||||
|
pub(crate) subscriptions: [Topic<T>; S],
|
||||||
|
pub(crate) keep_alive: u16
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'t, T, L, const S: usize> McutieTask<'t, T, L, S>
|
||||||
|
where
|
||||||
|
T: Deref<Target = str> + 't,
|
||||||
|
L: Publishable + 't,
|
||||||
|
{
|
||||||
|
#[cfg(not(feature = "homeassistant"))]
|
||||||
|
async fn ha_handle_update(&self, _topic: &Topic<TopicString>, _payload: &Payload) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn recv_loop(&self, mut reader: TcpReader<'_>) -> Result<(), Error> {
|
||||||
|
let mut buffer = [0_u8; 4096];
|
||||||
|
let mut cursor: usize = 0;
|
||||||
|
|
||||||
|
let controller = CONTROL_CHANNEL.immediate_publisher();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
match reader.read(&mut buffer[cursor..]).await {
|
||||||
|
Ok(0) => {
|
||||||
|
error!("Receive socket closed");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Ok(len) => {
|
||||||
|
cursor += len;
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
error!("I/O failure reading packet");
|
||||||
|
return Err(Error::IOError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut start_pos = 0;
|
||||||
|
loop {
|
||||||
|
let packet_length = match packet_size(&buffer[start_pos..cursor]) {
|
||||||
|
Some(0) => {
|
||||||
|
error!("Invalid MQTT packet");
|
||||||
|
return Err(Error::PacketError);
|
||||||
|
}
|
||||||
|
Some(len) => len,
|
||||||
|
None => {
|
||||||
|
// None is returned when there is not yet enough data to decode a packet.
|
||||||
|
if start_pos != 0 {
|
||||||
|
// Adjust the buffer to reclaim any unused data
|
||||||
|
buffer.copy_within(start_pos..cursor, 0);
|
||||||
|
cursor -= start_pos;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let packet = match decode_slice(&buffer[start_pos..(start_pos + packet_length)]) {
|
||||||
|
Ok(Some(p)) => p,
|
||||||
|
Ok(None) => {
|
||||||
|
error!("Packet length calculation failed.");
|
||||||
|
return Err(Error::PacketError);
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
error!("Invalid MQTT packet");
|
||||||
|
return Err(Error::PacketError);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
debug!(
|
||||||
|
"Received packet from broker: {:?}",
|
||||||
|
Debug2Format(&packet.get_type())
|
||||||
|
);
|
||||||
|
|
||||||
|
match packet {
|
||||||
|
Packet::Connack(connack) => match connack.code {
|
||||||
|
ConnectReturnCode::Accepted => {
|
||||||
|
#[cfg(feature = "homeassistant")]
|
||||||
|
self.ha_after_connected().await;
|
||||||
|
|
||||||
|
for topic in &self.subscriptions {
|
||||||
|
let _ = topic.subscribe(false).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
DATA_CHANNEL.send(MqttMessage::Connected).await;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
error!("Connection request to broker was not accepted");
|
||||||
|
return Err(Error::IOError);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Packet::Pingresp => {}
|
||||||
|
|
||||||
|
Packet::Publish(publish) => {
|
||||||
|
match (
|
||||||
|
Topic::from_str(publish.topic_name),
|
||||||
|
Payload::from(publish.payload),
|
||||||
|
) {
|
||||||
|
(Ok(topic), Ok(payload)) => {
|
||||||
|
if !self.ha_handle_update(&topic, &payload).await {
|
||||||
|
DATA_CHANNEL
|
||||||
|
.send(MqttMessage::Publish(topic, payload))
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
error!("Unable to process publish data as it was too large");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match publish.qospid {
|
||||||
|
mqttrs::QosPid::AtMostOnce => {}
|
||||||
|
mqttrs::QosPid::AtLeastOnce(pid) => {
|
||||||
|
send_packet(Packet::Puback(pid)).await?;
|
||||||
|
}
|
||||||
|
mqttrs::QosPid::ExactlyOnce(pid) => {
|
||||||
|
send_packet(Packet::Pubrec(pid)).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Packet::Puback(pid) => {
|
||||||
|
controller.publish_immediate(ControlMessage::Published(pid));
|
||||||
|
}
|
||||||
|
Packet::Pubrec(pid) => {
|
||||||
|
controller.publish_immediate(ControlMessage::Published(pid));
|
||||||
|
send_packet(Packet::Pubrel(pid)).await?;
|
||||||
|
}
|
||||||
|
Packet::Pubrel(pid) => send_packet(Packet::Pubrel(pid)).await?,
|
||||||
|
Packet::Pubcomp(_) => {}
|
||||||
|
|
||||||
|
Packet::Suback(suback) => {
|
||||||
|
if let Some(return_code) = suback.return_codes.first() {
|
||||||
|
controller.publish_immediate(ControlMessage::Subscribed(
|
||||||
|
suback.pid,
|
||||||
|
*return_code,
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
warn!("Unexpected suback with no return codes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Packet::Unsuback(pid) => {
|
||||||
|
controller.publish_immediate(ControlMessage::Unsubscribed(pid));
|
||||||
|
}
|
||||||
|
|
||||||
|
Packet::Connect(_)
|
||||||
|
| Packet::Subscribe(_)
|
||||||
|
| Packet::Pingreq
|
||||||
|
| Packet::Unsubscribe(_)
|
||||||
|
| Packet::Disconnect => {
|
||||||
|
debug!(
|
||||||
|
"Unexpected packet from broker: {:?}",
|
||||||
|
Debug2Format(&packet.get_type())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
start_pos += packet_length;
|
||||||
|
if start_pos == cursor {
|
||||||
|
cursor = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn write_loop(&self, mut writer: TcpWriter<'_>) {
|
||||||
|
let mut buffer = Payload::new();
|
||||||
|
|
||||||
|
let mut last_will_topic = TopicString::new();
|
||||||
|
let mut last_will_payload = Payload::new();
|
||||||
|
|
||||||
|
let last_will = self.last_will.as_ref().and_then(|p| {
|
||||||
|
if p.write_topic(&mut last_will_topic).is_ok()
|
||||||
|
&& p.write_payload(&mut last_will_payload).is_ok()
|
||||||
|
{
|
||||||
|
Some(LastWill {
|
||||||
|
topic: &last_will_topic,
|
||||||
|
message: &last_will_payload,
|
||||||
|
qos: p.qos(),
|
||||||
|
retain: p.retain(),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send our connection request.
|
||||||
|
if buffer
|
||||||
|
.encode_packet(&Packet::Connect(Connect {
|
||||||
|
protocol: Protocol::MQTT311,
|
||||||
|
keep_alive: self.keep_alive,
|
||||||
|
client_id: device_id(),
|
||||||
|
clean_session: true,
|
||||||
|
last_will,
|
||||||
|
username: self.username,
|
||||||
|
password: self.password.map(|s| s.as_bytes()),
|
||||||
|
}))
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
error!("Failed to encode connection packet");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(e) = writer.write(&buffer).await {
|
||||||
|
error!("Failed to send connection packet: {:?}", e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let reader = SEND_QUEUE.reader();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let buffer = reader.receive().await;
|
||||||
|
|
||||||
|
trace!("Writer sending packet");
|
||||||
|
if let Err(e) = writer.write(&buffer).await {
|
||||||
|
error!("Failed to send data: {:?}", e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the MQTT stack. The future returned from this must be awaited for everything to work.
|
||||||
|
pub async fn run(self) {
|
||||||
|
let mut timeout: Option<u64> = None;
|
||||||
|
|
||||||
|
let mut rx_buffer = [0; 4096];
|
||||||
|
let mut tx_buffer = [0; 4096];
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if let Some(millis) = timeout.replace(DEFAULT_BACKOFF) {
|
||||||
|
Timer::after_millis(millis).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.network.is_config_up() {
|
||||||
|
debug!("Waiting for network to configure.");
|
||||||
|
self.network.wait_config_up().await;
|
||||||
|
debug!("Network configured.");
|
||||||
|
}
|
||||||
|
|
||||||
|
let ip_addrs = match self.network.dns_query(self.broker, DnsQueryType::A).await {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
error!("Failed to lookup '{}' for broker: {:?}", self.broker, e);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let ip = match ip_addrs.first() {
|
||||||
|
Some(i) => *i,
|
||||||
|
None => {
|
||||||
|
error!("No IP address found for broker '{}'", self.broker);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
debug!("Connecting to {}:1883", ip);
|
||||||
|
|
||||||
|
let mut socket = TcpSocket::new(self.network, &mut rx_buffer, &mut tx_buffer);
|
||||||
|
if let Err(e) = socket.connect((ip, 1883)).await {
|
||||||
|
error!("Failed to connect to {}:1883: {:?}", ip, e);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
info!("Connected to {}", self.broker);
|
||||||
|
timeout = Some(RESET_BACKOFF);
|
||||||
|
|
||||||
|
let (reader, writer) = socket.split();
|
||||||
|
|
||||||
|
let recv_loop = self.recv_loop(reader);
|
||||||
|
let send_loop = self.write_loop(writer);
|
||||||
|
|
||||||
|
let ping_loop = async {
|
||||||
|
loop {
|
||||||
|
Timer::after_secs(45).await;
|
||||||
|
|
||||||
|
let _ = send_packet(Packet::Pingreq).await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let link_down = async {
|
||||||
|
self.network.wait_link_down().await;
|
||||||
|
warn!("Network link lost");
|
||||||
|
};
|
||||||
|
|
||||||
|
let ip_down = async {
|
||||||
|
self.network.wait_config_down().await;
|
||||||
|
warn!("Network config lost");
|
||||||
|
};
|
||||||
|
|
||||||
|
select4(send_loop, ping_loop, recv_loop, select(link_down, ip_down)).await;
|
||||||
|
|
||||||
|
socket.close();
|
||||||
|
|
||||||
|
warn!("Lost connection with broker");
|
||||||
|
DATA_CHANNEL.send(MqttMessage::Disconnected).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
227
rust/src/mcutie_3_0_0/lib.rs
Normal file
227
rust/src/mcutie_3_0_0/lib.rs
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
#![no_std]
|
||||||
|
#![deny(unreachable_pub)]
|
||||||
|
#![warn(missing_docs)]
|
||||||
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||||
|
//! MQTT client support crate vendored into this repository.
|
||||||
|
|
||||||
|
use core::{ops::Deref, str};
|
||||||
|
|
||||||
|
pub use buffer::Buffer;
|
||||||
|
use embassy_net::{HardwareAddress, Stack};
|
||||||
|
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, channel::Channel};
|
||||||
|
use heapless::String;
|
||||||
|
pub use io::McutieTask;
|
||||||
|
pub use mqttrs::QoS;
|
||||||
|
use mqttrs::{Pid, SubscribeReturnCodes};
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
pub use publish::*;
|
||||||
|
pub use topic::Topic;
|
||||||
|
|
||||||
|
// This must come first so the macros are visible
|
||||||
|
pub(crate) mod fmt;
|
||||||
|
|
||||||
|
mod buffer;
|
||||||
|
#[cfg(feature = "homeassistant")]
|
||||||
|
pub mod homeassistant;
|
||||||
|
mod io;
|
||||||
|
mod pipe;
|
||||||
|
mod publish;
|
||||||
|
mod topic;
|
||||||
|
|
||||||
|
// This really needs to match that used by mqttrs.
|
||||||
|
const TOPIC_LENGTH: usize = 256;
|
||||||
|
const PAYLOAD_LENGTH: usize = 2048;
|
||||||
|
|
||||||
|
/// A fixed length stack allocated string. The length is fixed by the mqttrs crate.
|
||||||
|
pub type TopicString = String<TOPIC_LENGTH>;
|
||||||
|
/// A fixed length buffer of 2048 bytes.
|
||||||
|
pub type Payload = Buffer<PAYLOAD_LENGTH>;
|
||||||
|
|
||||||
|
// By default in the event of an error connecting to the broker we will wait for 5s.
|
||||||
|
const DEFAULT_BACKOFF: u64 = 5000;
|
||||||
|
// If the connection dropped then re-connect more quickly.
|
||||||
|
const RESET_BACKOFF: u64 = 200;
|
||||||
|
// How long to wait for the broker to confirm actions.
|
||||||
|
const CONFIRMATION_TIMEOUT: u64 = 2000;
|
||||||
|
|
||||||
|
static DATA_CHANNEL: Channel<CriticalSectionRawMutex, MqttMessage, 10> = Channel::new();
|
||||||
|
|
||||||
|
static DEVICE_TYPE: OnceCell<String<32>> = OnceCell::new();
|
||||||
|
static DEVICE_ID: OnceCell<String<32>> = OnceCell::new();
|
||||||
|
|
||||||
|
fn device_id() -> &'static str {
|
||||||
|
DEVICE_ID.get().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn device_type() -> &'static str {
|
||||||
|
DEVICE_TYPE.get().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Various errors
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
||||||
|
pub enum Error {
|
||||||
|
/// An IO error occured.
|
||||||
|
IOError,
|
||||||
|
/// The operation timed out.
|
||||||
|
TimedOut,
|
||||||
|
/// An attempt was made to encode something too large.
|
||||||
|
TooLarge,
|
||||||
|
/// A packet or payload could not be decoded or encoded.
|
||||||
|
PacketError,
|
||||||
|
/// An invalid or unsupported operation was attempted.
|
||||||
|
Invalid,
|
||||||
|
/// A value was rejected.
|
||||||
|
Rejected,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
|
/// A message from the MQTT broker.
|
||||||
|
pub enum MqttMessage {
|
||||||
|
/// The broker has been connected to successfully. Generally in response to this message a
|
||||||
|
/// device should subscribe to topics of interest and send out any device state.
|
||||||
|
Connected,
|
||||||
|
/// New data received from the broker.
|
||||||
|
Publish(Topic<TopicString>, Payload),
|
||||||
|
/// The connection to the broker has been dropped.
|
||||||
|
Disconnected,
|
||||||
|
/// Home Assistant has come online and you should send any discovery messages.
|
||||||
|
#[cfg(feature = "homeassistant")]
|
||||||
|
HomeAssistantOnline,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
enum ControlMessage {
|
||||||
|
Published(Pid),
|
||||||
|
Subscribed(Pid, SubscribeReturnCodes),
|
||||||
|
Unsubscribed(Pid),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Receives messages from the broker.
|
||||||
|
pub struct McutieReceiver;
|
||||||
|
|
||||||
|
impl McutieReceiver {
|
||||||
|
/// Waits for the next message from the broker.
|
||||||
|
pub async fn receive(&self) -> MqttMessage {
|
||||||
|
DATA_CHANNEL.receive().await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A builder to configure the MQTT stack.
|
||||||
|
pub struct McutieBuilder<'t, T, L, const S: usize>
|
||||||
|
where
|
||||||
|
T: Deref<Target = str> + 't,
|
||||||
|
L: Publishable + 't,
|
||||||
|
{
|
||||||
|
network: Stack<'t>,
|
||||||
|
device_type: &'t str,
|
||||||
|
device_id: Option<&'t str>,
|
||||||
|
broker: &'t str,
|
||||||
|
last_will: Option<L>,
|
||||||
|
username: Option<&'t str>,
|
||||||
|
password: Option<&'t str>,
|
||||||
|
subscriptions: [Topic<T>; S],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'t, T: Deref<Target = str> + 't, L: Publishable + 't> McutieBuilder<'t, T, L, 0> {
|
||||||
|
/// Creates a new builder with the initial required configuration.
|
||||||
|
///
|
||||||
|
/// `device_type` is expected to be the same for all devices of the same type.
|
||||||
|
/// `broker` may be an IP address or a DNS name for the broker to connect to.
|
||||||
|
pub fn new(network: Stack<'t>, device_type: &'t str, broker: &'t str) -> Self {
|
||||||
|
Self {
|
||||||
|
network,
|
||||||
|
device_type,
|
||||||
|
broker,
|
||||||
|
device_id: None,
|
||||||
|
last_will: None,
|
||||||
|
username: None,
|
||||||
|
password: None,
|
||||||
|
subscriptions: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'t, T: Deref<Target = str> + 't, L: Publishable + 't, const S: usize>
|
||||||
|
McutieBuilder<'t, T, L, S>
|
||||||
|
{
|
||||||
|
/// Add some default topics to subscribe to.
|
||||||
|
pub fn with_subscriptions<const N: usize>(
|
||||||
|
self,
|
||||||
|
subscriptions: [Topic<T>; N],
|
||||||
|
) -> McutieBuilder<'t, T, L, N> {
|
||||||
|
McutieBuilder {
|
||||||
|
network: self.network,
|
||||||
|
device_type: self.device_type,
|
||||||
|
broker: self.broker,
|
||||||
|
device_id: self.device_id,
|
||||||
|
last_will: self.last_will,
|
||||||
|
username: self.username,
|
||||||
|
password: self.password,
|
||||||
|
subscriptions,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'t, T: Deref<Target = str> + 't, L: Publishable + 't, const S: usize>
|
||||||
|
McutieBuilder<'t, T, L, S>
|
||||||
|
{
|
||||||
|
/// Adds authentication for the broker.
|
||||||
|
pub fn with_authentication(self, username: &'t str, password: &'t str) -> Self {
|
||||||
|
Self {
|
||||||
|
username: Some(username),
|
||||||
|
password: Some(password),
|
||||||
|
..self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets a last will message to be published in the event of disconnection.
|
||||||
|
pub fn with_last_will(self, last_will: L) -> Self {
|
||||||
|
Self {
|
||||||
|
last_will: Some(last_will),
|
||||||
|
..self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets a custom unique device identifier. If none is set then the network
|
||||||
|
/// MAC address is used.
|
||||||
|
pub fn with_device_id(self, device_id: &'t str) -> Self {
|
||||||
|
Self {
|
||||||
|
device_id: Some(device_id),
|
||||||
|
..self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialises the MQTT stack returning a receiver for listening to
|
||||||
|
/// messages from the broker and a future that must be run in order for the
|
||||||
|
/// stack to operate.
|
||||||
|
pub fn build(self, keep_alive: u16) -> (McutieReceiver, McutieTask<'t, T, L, S>) {
|
||||||
|
let mut dtype = String::<32>::new();
|
||||||
|
dtype.push_str(self.device_type).unwrap();
|
||||||
|
DEVICE_TYPE.set(dtype).unwrap();
|
||||||
|
|
||||||
|
let mut did = String::<32>::new();
|
||||||
|
if let Some(device_id) = self.device_id {
|
||||||
|
did.push_str(device_id).unwrap();
|
||||||
|
} else if let HardwareAddress::Ethernet(address) = self.network.hardware_address() {
|
||||||
|
let mut buffer = [0_u8; 12];
|
||||||
|
hex::encode_to_slice(address.as_bytes(), &mut buffer).unwrap();
|
||||||
|
did.push_str(str::from_utf8(&buffer).unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
DEVICE_ID.set(did).unwrap();
|
||||||
|
|
||||||
|
(
|
||||||
|
McutieReceiver {},
|
||||||
|
McutieTask {
|
||||||
|
network: self.network,
|
||||||
|
broker: self.broker,
|
||||||
|
last_will: self.last_will,
|
||||||
|
username: self.username,
|
||||||
|
password: self.password,
|
||||||
|
subscriptions: self.subscriptions,
|
||||||
|
keep_alive
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
267
rust/src/mcutie_3_0_0/pipe.rs
Normal file
267
rust/src/mcutie_3_0_0/pipe.rs
Normal file
@@ -0,0 +1,267 @@
|
|||||||
|
use core::{
|
||||||
|
cell::RefCell,
|
||||||
|
future::Future,
|
||||||
|
pin::Pin,
|
||||||
|
task::{Context, Poll, Waker},
|
||||||
|
};
|
||||||
|
|
||||||
|
use embassy_sync::blocking_mutex::{raw::RawMutex, Mutex};
|
||||||
|
use pin_project::pin_project;
|
||||||
|
|
||||||
|
struct PipeData<T, const N: usize> {
|
||||||
|
connect_count: usize,
|
||||||
|
receiver_waker: Option<Waker>,
|
||||||
|
sender_waker: Option<Waker>,
|
||||||
|
pending: Option<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn swap_wakers(waker: &mut Option<Waker>, new_waker: &Waker) {
|
||||||
|
if let Some(old_waker) = waker.take() {
|
||||||
|
if old_waker.will_wake(new_waker) {
|
||||||
|
*waker = Some(old_waker)
|
||||||
|
} else {
|
||||||
|
if !new_waker.will_wake(&old_waker) {
|
||||||
|
old_waker.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
*waker = Some(new_waker.clone());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
*waker = Some(new_waker.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct ReceiveFuture<'a, M: RawMutex, T, const N: usize> {
|
||||||
|
pipe: &'a ConnectedPipe<M, T, N>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<M: RawMutex, T, const N: usize> Future for ReceiveFuture<'_, M, T, N> {
|
||||||
|
type Output = T;
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
self.pipe.inner.lock(|cell| {
|
||||||
|
let mut inner = cell.borrow_mut();
|
||||||
|
|
||||||
|
if let Some(waker) = inner.sender_waker.take() {
|
||||||
|
waker.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(item) = inner.pending.take() {
|
||||||
|
if let Some(old_waker) = inner.receiver_waker.take() {
|
||||||
|
old_waker.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
Poll::Ready(item)
|
||||||
|
} else {
|
||||||
|
swap_wakers(&mut inner.receiver_waker, cx.waker());
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct PipeReader<'a, M: RawMutex, T, const N: usize> {
|
||||||
|
pipe: &'a ConnectedPipe<M, T, N>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<M: RawMutex, T, const N: usize> PipeReader<'_, M, T, N> {
|
||||||
|
#[must_use]
|
||||||
|
pub(crate) fn receive(&self) -> ReceiveFuture<'_, M, T, N> {
|
||||||
|
ReceiveFuture { pipe: self.pipe }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<M: RawMutex, T, const N: usize> Drop for PipeReader<'_, M, T, N> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.pipe.inner.lock(|cell| {
|
||||||
|
let mut inner = cell.borrow_mut();
|
||||||
|
inner.connect_count -= 1;
|
||||||
|
|
||||||
|
if inner.connect_count == 0 {
|
||||||
|
inner.pending = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(waker) = inner.sender_waker.take() {
|
||||||
|
waker.wake();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pin_project]
|
||||||
|
pub(crate) struct PushFuture<'a, M: RawMutex, T, const N: usize> {
|
||||||
|
data: Option<T>,
|
||||||
|
pipe: &'a ConnectedPipe<M, T, N>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<M: RawMutex, T, const N: usize> Future for PushFuture<'_, M, T, N> {
|
||||||
|
type Output = ();
|
||||||
|
|
||||||
|
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
self.pipe.inner.lock(|cell| {
|
||||||
|
let project = self.project();
|
||||||
|
let mut inner = cell.borrow_mut();
|
||||||
|
|
||||||
|
if let Some(receiver) = inner.receiver_waker.take() {
|
||||||
|
receiver.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
if project.data.is_none() || inner.connect_count == 0 {
|
||||||
|
trace!("Dropping packet");
|
||||||
|
Poll::Ready(())
|
||||||
|
} else if inner.pending.is_some() {
|
||||||
|
swap_wakers(&mut inner.sender_waker, cx.waker());
|
||||||
|
Poll::Pending
|
||||||
|
} else {
|
||||||
|
inner.pending = project.data.take();
|
||||||
|
|
||||||
|
Poll::Ready(())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A pipe that knows whether a receiver is connected. If so pushing to the
|
||||||
|
/// queue waits until there is space in the queue, otherwise data is simply
|
||||||
|
/// dropped.
|
||||||
|
pub(crate) struct ConnectedPipe<M: RawMutex, T, const N: usize> {
|
||||||
|
inner: Mutex<M, RefCell<PipeData<T, N>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<M: RawMutex, T, const N: usize> ConnectedPipe<M, T, N> {
|
||||||
|
pub(crate) const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
inner: Mutex::new(RefCell::new(PipeData {
|
||||||
|
connect_count: 0,
|
||||||
|
receiver_waker: None,
|
||||||
|
sender_waker: None,
|
||||||
|
pending: None,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A future that waits for a new item to be available.
|
||||||
|
pub(crate) fn reader(&self) -> PipeReader<'_, M, T, N> {
|
||||||
|
self.inner.lock(|cell| {
|
||||||
|
let mut inner = cell.borrow_mut();
|
||||||
|
inner.connect_count += 1;
|
||||||
|
|
||||||
|
PipeReader { pipe: self }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pushes an item to the reader, waiting for a slot to become available if
|
||||||
|
/// connected.
|
||||||
|
#[must_use]
|
||||||
|
pub(crate) fn push(&self, data: T) -> PushFuture<'_, M, T, N> {
|
||||||
|
PushFuture {
|
||||||
|
data: Some(data),
|
||||||
|
pipe: self,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use futures_executor::{LocalPool, ThreadPool};
|
||||||
|
use futures_timer::Delay;
|
||||||
|
use futures_util::{future::select, pin_mut, task::SpawnExt, FutureExt};
|
||||||
|
|
||||||
|
use super::ConnectedPipe;
|
||||||
|
|
||||||
|
async fn wait_milis(milis: u64) {
|
||||||
|
Delay::new(Duration::from_millis(milis)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// #[futures_test::test]
|
||||||
|
#[test]
|
||||||
|
fn test_send_receive() {
|
||||||
|
let mut executor = LocalPool::new();
|
||||||
|
let spawner = executor.spawner();
|
||||||
|
|
||||||
|
static PIPE: ConnectedPipe<CriticalSectionRawMutex, usize, 5> = ConnectedPipe::new();
|
||||||
|
|
||||||
|
// Task that sends
|
||||||
|
spawner
|
||||||
|
.spawn(async {
|
||||||
|
wait_milis(10).await;
|
||||||
|
|
||||||
|
PIPE.push(23).await;
|
||||||
|
PIPE.push(56).await;
|
||||||
|
PIPE.push(67).await;
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Task that receives
|
||||||
|
spawner
|
||||||
|
.spawn(async {
|
||||||
|
let reader = PIPE.reader();
|
||||||
|
let value = reader.receive().await;
|
||||||
|
assert_eq!(value, 23);
|
||||||
|
let value = reader.receive().await;
|
||||||
|
assert_eq!(value, 56);
|
||||||
|
let value = reader.receive().await;
|
||||||
|
assert_eq!(value, 67);
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
executor.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[futures_test::test]
|
||||||
|
async fn test_send_drop() {
|
||||||
|
static PIPE: ConnectedPipe<CriticalSectionRawMutex, usize, 5> = ConnectedPipe::new();
|
||||||
|
|
||||||
|
PIPE.push(23).await;
|
||||||
|
PIPE.push(56).await;
|
||||||
|
PIPE.push(67).await;
|
||||||
|
|
||||||
|
// Create a reader after sending
|
||||||
|
let reader = PIPE.reader();
|
||||||
|
let receive = reader.receive().fuse();
|
||||||
|
pin_mut!(receive);
|
||||||
|
|
||||||
|
let timeout = wait_milis(50).fuse();
|
||||||
|
pin_mut!(timeout);
|
||||||
|
|
||||||
|
let either = select(receive, timeout).await;
|
||||||
|
|
||||||
|
match either {
|
||||||
|
futures_util::future::Either::Left(_) => {
|
||||||
|
panic!("There should be nothing to receive!");
|
||||||
|
}
|
||||||
|
futures_util::future::Either::Right(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[futures_test::test]
|
||||||
|
async fn test_bulk_send_publish() {
|
||||||
|
static PIPE: ConnectedPipe<CriticalSectionRawMutex, usize, 5> = ConnectedPipe::new();
|
||||||
|
|
||||||
|
let executor = ThreadPool::new().unwrap();
|
||||||
|
|
||||||
|
executor
|
||||||
|
.spawn(async {
|
||||||
|
for i in 0..1000 {
|
||||||
|
PIPE.push(i).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
executor
|
||||||
|
.spawn(async {
|
||||||
|
for i in 1000..2000 {
|
||||||
|
PIPE.push(i).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let reader = PIPE.reader();
|
||||||
|
for _ in 0..800 {
|
||||||
|
reader.receive().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
173
rust/src/mcutie_3_0_0/publish.rs
Normal file
173
rust/src/mcutie_3_0_0/publish.rs
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
use core::{fmt::Display, future::Future, ops::Deref};
|
||||||
|
|
||||||
|
use embedded_io::Write;
|
||||||
|
use mqttrs::QoS;
|
||||||
|
|
||||||
|
use crate::{io::publish, Error, Payload, Topic, TopicString};
|
||||||
|
|
||||||
|
/// A message that can be published to an MQTT broker.
|
||||||
|
pub trait Publishable {
|
||||||
|
/// Write this message's topic into the supplied buffer.
|
||||||
|
fn write_topic(&self, buffer: &mut TopicString) -> Result<(), Error>;
|
||||||
|
|
||||||
|
/// Write this message's payload into the supplied buffer.
|
||||||
|
fn write_payload(&self, buffer: &mut Payload) -> Result<(), Error>;
|
||||||
|
|
||||||
|
/// Get this message's QoS level.
|
||||||
|
fn qos(&self) -> QoS {
|
||||||
|
QoS::AtMostOnce
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the broker should retain this message.
|
||||||
|
fn retain(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Publishes this message to the broker. If the stack has not yet been
|
||||||
|
/// initialized this is likely to panic.
|
||||||
|
fn publish(&self) -> impl Future<Output = Result<(), Error>> {
|
||||||
|
async {
|
||||||
|
let mut topic = TopicString::new();
|
||||||
|
self.write_topic(&mut topic)?;
|
||||||
|
|
||||||
|
let mut payload = Payload::new();
|
||||||
|
self.write_payload(&mut payload)?;
|
||||||
|
|
||||||
|
publish(&topic, &payload, self.qos(), self.retain()).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [`Publishable`] with a raw byte payload.
|
||||||
|
pub struct PublishBytes<'a, T, B: AsRef<[u8]>> {
|
||||||
|
pub(crate) topic: &'a Topic<T>,
|
||||||
|
pub(crate) data: B,
|
||||||
|
pub(crate) qos: QoS,
|
||||||
|
pub(crate) retain: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, B: AsRef<[u8]>> PublishBytes<'_, T, B> {
|
||||||
|
/// Sets the QoS level for this message.
|
||||||
|
pub fn qos(mut self, qos: QoS) -> Self {
|
||||||
|
self.qos = qos;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets whether the broker should retain this message.
|
||||||
|
pub fn retain(mut self, retain: bool) -> Self {
|
||||||
|
self.retain = retain;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: Deref<Target = str> + 'a, B: AsRef<[u8]>> Publishable for PublishBytes<'a, T, B> {
|
||||||
|
fn write_topic(&self, buffer: &mut TopicString) -> Result<(), Error> {
|
||||||
|
self.topic.to_string(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_payload(&self, buffer: &mut Payload) -> Result<(), Error> {
|
||||||
|
buffer
|
||||||
|
.write_all(self.data.as_ref())
|
||||||
|
.map_err(|_| Error::TooLarge)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn qos(&self) -> QoS {
|
||||||
|
self.qos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn retain(&self) -> bool {
|
||||||
|
self.retain
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish(&self) -> Result<(), Error> {
|
||||||
|
let mut topic = TopicString::new();
|
||||||
|
self.write_topic(&mut topic)?;
|
||||||
|
|
||||||
|
publish(&topic, self.data.as_ref(), self.qos(), self.retain()).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [`Publishable`] with a payload that implements [`Display`].
|
||||||
|
pub struct PublishDisplay<'a, T, D: Display> {
|
||||||
|
pub(crate) topic: &'a Topic<T>,
|
||||||
|
pub(crate) data: D,
|
||||||
|
pub(crate) qos: QoS,
|
||||||
|
pub(crate) retain: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, D: Display> PublishDisplay<'_, T, D> {
|
||||||
|
/// Sets the QoS level for this message.
|
||||||
|
pub fn qos(mut self, qos: QoS) -> Self {
|
||||||
|
self.qos = qos;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets whether the broker should retain this message.
|
||||||
|
pub fn retain(mut self, retain: bool) -> Self {
|
||||||
|
self.retain = retain;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: Deref<Target = str> + 'a, D: Display> Publishable for PublishDisplay<'a, T, D> {
|
||||||
|
fn write_topic(&self, buffer: &mut TopicString) -> Result<(), Error> {
|
||||||
|
self.topic.to_string(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_payload(&self, buffer: &mut Payload) -> Result<(), Error> {
|
||||||
|
write!(buffer, "{}", self.data).map_err(|_| Error::TooLarge)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn qos(&self) -> QoS {
|
||||||
|
self.qos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn retain(&self) -> bool {
|
||||||
|
self.retain
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
/// A [`Publishable`] with that serializes a JSON payload.
|
||||||
|
pub struct PublishJson<'a, T, D: serde::Serialize> {
|
||||||
|
pub(crate) topic: &'a Topic<T>,
|
||||||
|
pub(crate) data: D,
|
||||||
|
pub(crate) qos: QoS,
|
||||||
|
pub(crate) retain: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
impl<T, D: serde::Serialize> PublishJson<'_, T, D> {
|
||||||
|
/// Sets the QoS level for this message.
|
||||||
|
pub fn qos(mut self, qos: QoS) -> Self {
|
||||||
|
self.qos = qos;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets whether the broker should retain this message.
|
||||||
|
pub fn retain(mut self, retain: bool) -> Self {
|
||||||
|
self.retain = retain;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
impl<'a, T: Deref<Target = str> + 'a, D: serde::Serialize> Publishable for PublishJson<'a, T, D> {
|
||||||
|
fn write_topic(&self, buffer: &mut TopicString) -> Result<(), Error> {
|
||||||
|
self.topic.to_string(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_payload(&self, buffer: &mut Payload) -> Result<(), Error> {
|
||||||
|
buffer
|
||||||
|
.serialize_json(&self.data)
|
||||||
|
.map_err(|_| Error::TooLarge)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn qos(&self) -> QoS {
|
||||||
|
self.qos
|
||||||
|
}
|
||||||
|
|
||||||
|
fn retain(&self) -> bool {
|
||||||
|
self.retain
|
||||||
|
}
|
||||||
|
}
|
||||||
284
rust/src/mcutie_3_0_0/topic.rs
Normal file
284
rust/src/mcutie_3_0_0/topic.rs
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
use core::{fmt::Display, ops::Deref};
|
||||||
|
|
||||||
|
use embassy_futures::select::{select, Either};
|
||||||
|
use embassy_sync::pubsub::WaitResult;
|
||||||
|
use embassy_time::Timer;
|
||||||
|
use heapless::{String, Vec};
|
||||||
|
use mqttrs::{Packet, QoS, Subscribe, SubscribeReturnCodes, SubscribeTopic, Unsubscribe};
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
use crate::publish::PublishJson;
|
||||||
|
use crate::{
|
||||||
|
device_id, device_type,
|
||||||
|
io::{assign_pid, send_packet, subscribe},
|
||||||
|
publish::{PublishBytes, PublishDisplay},
|
||||||
|
ControlMessage, Error, TopicString, CONFIRMATION_TIMEOUT,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// An MQTT topic that is optionally prefixed with the device type and unique ID.
|
||||||
|
/// Normally you will define all your application's topics as consts with static
|
||||||
|
/// lifetimes.
|
||||||
|
///
|
||||||
|
/// A [`Topic`] is the main entry to publishing messages to the broker.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # use mcutie::{Publishable, Topic};
|
||||||
|
/// const DEVICE_AVAILABILITY: Topic<&'static str> = Topic::Device("state");
|
||||||
|
///
|
||||||
|
/// async fn send_status(status: &'static str) {
|
||||||
|
/// let _ = DEVICE_AVAILABILITY.with_bytes(status.as_bytes()).publish().await;
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub enum Topic<T> {
|
||||||
|
/// A topic that is prefixed with the device type.
|
||||||
|
DeviceType(T),
|
||||||
|
/// A topic that is prefixed with the device type and unique ID.
|
||||||
|
Device(T),
|
||||||
|
/// Any topic.
|
||||||
|
General(T),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<A, B> PartialEq<Topic<A>> for Topic<B>
|
||||||
|
where
|
||||||
|
B: PartialEq<A>,
|
||||||
|
{
|
||||||
|
fn eq(&self, other: &Topic<A>) -> bool {
|
||||||
|
match (self, other) {
|
||||||
|
(Topic::DeviceType(l0), Topic::DeviceType(r0)) => l0 == r0,
|
||||||
|
(Topic::Device(l0), Topic::Device(r0)) => l0 == r0,
|
||||||
|
(Topic::General(l0), Topic::General(r0)) => l0 == r0,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Topic<T> {
|
||||||
|
/// Creates a publishable message with something that can return a reference
|
||||||
|
/// to the payload in bytes.
|
||||||
|
///
|
||||||
|
/// Defaults to non-retained with QoS of 0 (AtMostOnce).
|
||||||
|
pub fn with_bytes<B: AsRef<[u8]>>(&self, data: B) -> PublishBytes<'_, T, B> {
|
||||||
|
PublishBytes {
|
||||||
|
topic: self,
|
||||||
|
data,
|
||||||
|
qos: QoS::AtMostOnce,
|
||||||
|
retain: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a publishable message with something that implements [`Display`].
|
||||||
|
///
|
||||||
|
/// Defaults to non-retained with QoS of 0 (AtMostOnce).
|
||||||
|
pub fn with_display<D: Display>(&self, data: D) -> PublishDisplay<'_, T, D> {
|
||||||
|
PublishDisplay {
|
||||||
|
topic: self,
|
||||||
|
data,
|
||||||
|
qos: QoS::AtMostOnce,
|
||||||
|
retain: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
/// Creates a publishable message with something that can be serialized to
|
||||||
|
/// JSON.
|
||||||
|
///
|
||||||
|
/// Defaults to non-retained with QoS of 0 (AtMostOnce).
|
||||||
|
pub fn with_json<D: serde::Serialize>(&self, data: D) -> PublishJson<'_, T, D> {
|
||||||
|
PublishJson {
|
||||||
|
topic: self,
|
||||||
|
data,
|
||||||
|
qos: QoS::AtMostOnce,
|
||||||
|
retain: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Topic<TopicString> {
|
||||||
|
pub(crate) fn from_str(mut st: &str) -> Result<Self, Error> {
|
||||||
|
let mut strip_prefix = |pr: &str| -> bool {
|
||||||
|
if st.starts_with(pr) && st.len() > pr.len() && &st[pr.len()..pr.len() + 1] == "/" {
|
||||||
|
st = &st[pr.len() + 1..];
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if strip_prefix(device_type()) {
|
||||||
|
if strip_prefix(device_id()) {
|
||||||
|
let mut topic = TopicString::new();
|
||||||
|
topic.push_str(st).map_err(|_| Error::TooLarge)?;
|
||||||
|
Ok(Topic::Device(topic))
|
||||||
|
} else {
|
||||||
|
let mut topic = TopicString::new();
|
||||||
|
topic.push_str(st).map_err(|_| Error::TooLarge)?;
|
||||||
|
Ok(Topic::DeviceType(topic))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let mut topic = TopicString::new();
|
||||||
|
topic.push_str(st).map_err(|_| Error::TooLarge)?;
|
||||||
|
Ok(Topic::General(topic))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Deref<Target = str>> Topic<T> {
|
||||||
|
pub(crate) fn to_string<const N: usize>(&self, result: &mut String<N>) -> Result<(), Error> {
|
||||||
|
match self {
|
||||||
|
Topic::Device(st) => {
|
||||||
|
result
|
||||||
|
.push_str(device_type())
|
||||||
|
.map_err(|_| Error::TooLarge)?;
|
||||||
|
result.push_str("/").map_err(|_| Error::TooLarge)?;
|
||||||
|
result.push_str(device_id()).map_err(|_| Error::TooLarge)?;
|
||||||
|
result.push_str("/").map_err(|_| Error::TooLarge)?;
|
||||||
|
result.push_str(st.as_ref()).map_err(|_| Error::TooLarge)?;
|
||||||
|
}
|
||||||
|
Topic::DeviceType(st) => {
|
||||||
|
result
|
||||||
|
.push_str(device_type())
|
||||||
|
.map_err(|_| Error::TooLarge)?;
|
||||||
|
result.push_str("/").map_err(|_| Error::TooLarge)?;
|
||||||
|
result.push_str(st.as_ref()).map_err(|_| Error::TooLarge)?;
|
||||||
|
}
|
||||||
|
Topic::General(st) => {
|
||||||
|
result.push_str(st.as_ref()).map_err(|_| Error::TooLarge)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts to a topic containing an [`str`]. Particularly useful for converting from an owned
|
||||||
|
/// string for match patterns.
|
||||||
|
pub fn as_ref(&self) -> Topic<&str> {
|
||||||
|
match self {
|
||||||
|
Topic::DeviceType(st) => Topic::DeviceType(st.as_ref()),
|
||||||
|
Topic::Device(st) => Topic::Device(st.as_ref()),
|
||||||
|
Topic::General(st) => Topic::General(st.as_ref()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Subscribes to this topic. If `wait_for_ack` is true then this will wait until confirmation
|
||||||
|
/// is received from the broker before returning.
|
||||||
|
pub async fn subscribe(&self, wait_for_ack: bool) -> Result<(), Error> {
|
||||||
|
let mut subscriber = subscribe().await;
|
||||||
|
|
||||||
|
let mut topic_path = TopicString::new();
|
||||||
|
if self.to_string(&mut topic_path).is_err() {
|
||||||
|
return Err(Error::TooLarge);
|
||||||
|
}
|
||||||
|
|
||||||
|
let pid = assign_pid().await;
|
||||||
|
|
||||||
|
let mut subscribe_topic_path = String::<256>::new();
|
||||||
|
subscribe_topic_path
|
||||||
|
.push_str(topic_path.as_str())
|
||||||
|
.map_err(|_| Error::TooLarge)?;
|
||||||
|
let subscribe_topic = SubscribeTopic {
|
||||||
|
topic_path: subscribe_topic_path,
|
||||||
|
qos: QoS::AtLeastOnce,
|
||||||
|
};
|
||||||
|
|
||||||
|
// The size of this vec must match that used by mqttrs.
|
||||||
|
let topics = match Vec::<SubscribeTopic, 5>::from_slice(&[subscribe_topic]) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(_) => return Err(Error::TooLarge),
|
||||||
|
};
|
||||||
|
|
||||||
|
let packet = Packet::Subscribe(Subscribe { pid, topics });
|
||||||
|
|
||||||
|
send_packet(packet).await?;
|
||||||
|
|
||||||
|
if wait_for_ack {
|
||||||
|
match select(
|
||||||
|
async {
|
||||||
|
loop {
|
||||||
|
match subscriber.next_message().await {
|
||||||
|
WaitResult::Lagged(_) => {
|
||||||
|
// Maybe we missed the message?
|
||||||
|
}
|
||||||
|
WaitResult::Message(ControlMessage::Subscribed(
|
||||||
|
subscribed_pid,
|
||||||
|
return_code,
|
||||||
|
)) => {
|
||||||
|
if subscribed_pid == pid {
|
||||||
|
if matches!(return_code, SubscribeReturnCodes::Success(_)) {
|
||||||
|
return Ok(());
|
||||||
|
} else {
|
||||||
|
return Err(Error::IOError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Timer::after_millis(CONFIRMATION_TIMEOUT),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Either::First(r) => r,
|
||||||
|
Either::Second(_) => Err(Error::TimedOut),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unsubscribes from a topic. If `wait_for_ack` is true then this will wait until confirmation is
|
||||||
|
/// received from the broker before returning.
|
||||||
|
pub async fn unsubscribe(&self, wait_for_ack: bool) -> Result<(), Error> {
|
||||||
|
let mut subscriber = subscribe().await;
|
||||||
|
|
||||||
|
let mut topic_path = TopicString::new();
|
||||||
|
if self.to_string(&mut topic_path).is_err() {
|
||||||
|
return Err(Error::TooLarge);
|
||||||
|
}
|
||||||
|
|
||||||
|
let pid = assign_pid().await;
|
||||||
|
|
||||||
|
// The size of this vec must match that used by mqttrs.
|
||||||
|
let mut unsubscribe_topic_path = String::<256>::new();
|
||||||
|
unsubscribe_topic_path
|
||||||
|
.push_str(topic_path.as_str())
|
||||||
|
.map_err(|_| Error::TooLarge)?;
|
||||||
|
let topics = match Vec::<String<256>, 5>::from_slice(&[unsubscribe_topic_path]) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(_) => return Err(Error::TooLarge),
|
||||||
|
};
|
||||||
|
|
||||||
|
let packet = Packet::Unsubscribe(Unsubscribe { pid, topics });
|
||||||
|
|
||||||
|
send_packet(packet).await?;
|
||||||
|
|
||||||
|
if wait_for_ack {
|
||||||
|
match select(
|
||||||
|
async {
|
||||||
|
loop {
|
||||||
|
match subscriber.next_message().await {
|
||||||
|
WaitResult::Lagged(_) => {
|
||||||
|
// Maybe we missed the message?
|
||||||
|
}
|
||||||
|
WaitResult::Message(ControlMessage::Unsubscribed(subscribed_pid)) => {
|
||||||
|
if subscribed_pid == pid {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Timer::after_millis(CONFIRMATION_TIMEOUT),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Either::First(r) => r,
|
||||||
|
Either::Second(_) => Err(Error::TimedOut),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
315
rust/src/mqtt.rs
Normal file
315
rust/src/mqtt.rs
Normal file
@@ -0,0 +1,315 @@
|
|||||||
|
use crate::bail;
|
||||||
|
use crate::config::NetworkConfig;
|
||||||
|
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||||
|
use crate::hal::PlantHal;
|
||||||
|
use crate::log::{log, LogMessage};
|
||||||
|
use alloc::string::String;
|
||||||
|
use alloc::{format, string::ToString, vec::Vec};
|
||||||
|
use core::sync::atomic::Ordering;
|
||||||
|
use embassy_executor::Spawner;
|
||||||
|
use embassy_net::Stack;
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::mutex::Mutex;
|
||||||
|
use embassy_sync::once_lock::OnceLock;
|
||||||
|
use embassy_time::{Duration, Timer, WithTimeout};
|
||||||
|
use log::info;
|
||||||
|
use mcutie::{
|
||||||
|
Error, McutieBuilder, McutieReceiver, McutieTask, MqttMessage, PublishDisplay, Publishable,
|
||||||
|
QoS, Topic,
|
||||||
|
};
|
||||||
|
use portable_atomic::AtomicBool;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
|
||||||
|
pub struct PumpInfo {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub pump_ineffective: bool,
|
||||||
|
pub median_current_ma: u16,
|
||||||
|
pub max_current_ma: u16,
|
||||||
|
pub min_current_ma: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Debug, PartialEq)]
|
||||||
|
pub struct Solar {
|
||||||
|
pub current_ma: u32,
|
||||||
|
pub voltage_ma: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false);
|
||||||
|
static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false);
|
||||||
|
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
|
||||||
|
static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new();
|
||||||
|
static MQTT_CONFIG_UPDATE_PAYLOAD: Mutex<CriticalSectionRawMutex, Option<String>> = Mutex::new(None);
|
||||||
|
|
||||||
|
pub fn is_stay_alive() -> bool {
|
||||||
|
MQTT_STAY_ALIVE.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn publish(subtopic: &str, message: &str) {
|
||||||
|
let online = MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed);
|
||||||
|
if !online {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let roundtrip_ok = MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed);
|
||||||
|
if !roundtrip_ok {
|
||||||
|
info!("MQTT roundtrip not received yet, dropping message");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match publish_inner(subtopic, message).await {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(err) => {
|
||||||
|
info!(
|
||||||
|
"Error during mqtt send on topic {subtopic} with message {message:#?} error is {err:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn publish_inner(subtopic: &str, message: &str) -> FatResult<()> {
|
||||||
|
if !subtopic.starts_with("/") {
|
||||||
|
bail!("Subtopic without / at start {}", subtopic);
|
||||||
|
}
|
||||||
|
if subtopic.len() > 192 {
|
||||||
|
bail!("Subtopic exceeds 192 chars {}", subtopic);
|
||||||
|
}
|
||||||
|
let base_topic = MQTT_BASE_TOPIC
|
||||||
|
.try_get()
|
||||||
|
.context("missing base topic in static!")?;
|
||||||
|
|
||||||
|
let full_topic = format!("{base_topic}{subtopic}");
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let result = Topic::General(full_topic.as_str())
|
||||||
|
.with_display(message)
|
||||||
|
.retain(true)
|
||||||
|
.publish()
|
||||||
|
.await;
|
||||||
|
match result {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(err) => {
|
||||||
|
let retry = match err {
|
||||||
|
Error::IOError => false,
|
||||||
|
Error::TimedOut => true,
|
||||||
|
Error::TooLarge => false,
|
||||||
|
Error::PacketError => false,
|
||||||
|
Error::Invalid => false,
|
||||||
|
Error::Rejected => false,
|
||||||
|
};
|
||||||
|
if !retry {
|
||||||
|
bail!(
|
||||||
|
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
|
||||||
|
&full_topic,
|
||||||
|
message,
|
||||||
|
err
|
||||||
|
);
|
||||||
|
}
|
||||||
|
info!(
|
||||||
|
"Retransmit for {} with message {:#?} error is {:?} retrying {}",
|
||||||
|
&full_topic, message, err, retry
|
||||||
|
);
|
||||||
|
Timer::after(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::util::mk_static;
|
||||||
|
|
||||||
|
pub async fn mqtt_init(
|
||||||
|
network_config: &'static NetworkConfig,
|
||||||
|
stack: Stack<'static>,
|
||||||
|
spawner: Spawner,
|
||||||
|
) -> FatResult<()> {
|
||||||
|
let base_topic = network_config
|
||||||
|
.base_topic
|
||||||
|
.as_ref()
|
||||||
|
.context("missing base topic")?;
|
||||||
|
if base_topic.is_empty() {
|
||||||
|
bail!("Mqtt base_topic was empty")
|
||||||
|
}
|
||||||
|
MQTT_BASE_TOPIC
|
||||||
|
.init(base_topic.to_string())
|
||||||
|
.map_err(|_| FatError::String {
|
||||||
|
error: "Error setting basetopic".to_string(),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mqtt_url = network_config
|
||||||
|
.mqtt_url
|
||||||
|
.as_ref()
|
||||||
|
.context("missing mqtt url")?;
|
||||||
|
if mqtt_url.is_empty() {
|
||||||
|
bail!("Mqtt url was empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
let last_will_topic = format!("{base_topic}/state");
|
||||||
|
let round_trip_topic = format!("{base_topic}/internal/roundtrip");
|
||||||
|
let stay_alive_topic = format!("{base_topic}/stay_alive");
|
||||||
|
let config_update_payload_topic = format!("{base_topic}/config/update_payload");
|
||||||
|
let config_update_topic = format!("{base_topic}/config/update");
|
||||||
|
|
||||||
|
let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> =
|
||||||
|
McutieBuilder::new(stack, "plant ctrl", mqtt_url);
|
||||||
|
if let (Some(mqtt_user), Some(mqtt_password)) = (
|
||||||
|
network_config.mqtt_user.as_ref(),
|
||||||
|
network_config.mqtt_password.as_ref(),
|
||||||
|
) {
|
||||||
|
builder = builder.with_authentication(mqtt_user, mqtt_password);
|
||||||
|
info!("With authentification");
|
||||||
|
}
|
||||||
|
|
||||||
|
let lwt = Topic::General(last_will_topic);
|
||||||
|
let lwt = mk_static!(Topic<String>, lwt);
|
||||||
|
let lwt = lwt.with_display("lost").retain(true).qos(QoS::AtLeastOnce);
|
||||||
|
builder = builder.with_last_will(lwt);
|
||||||
|
//TODO make configurable
|
||||||
|
builder = builder.with_device_id("plantctrl");
|
||||||
|
|
||||||
|
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 4> = builder
|
||||||
|
.with_subscriptions([
|
||||||
|
Topic::General(round_trip_topic.clone()),
|
||||||
|
Topic::General(stay_alive_topic.clone()),
|
||||||
|
Topic::General(config_update_payload_topic.clone()),
|
||||||
|
Topic::General(config_update_topic.clone()),
|
||||||
|
]);
|
||||||
|
|
||||||
|
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
|
||||||
|
let (receiver, task) = builder.build(keep_alive);
|
||||||
|
|
||||||
|
spawner.spawn(mqtt_incoming_task(
|
||||||
|
receiver,
|
||||||
|
round_trip_topic.clone(),
|
||||||
|
stay_alive_topic.clone(),
|
||||||
|
config_update_payload_topic.clone(),
|
||||||
|
config_update_topic.clone(),
|
||||||
|
)?);
|
||||||
|
spawner.spawn(mqtt_runner(task)?);
|
||||||
|
|
||||||
|
log(LogMessage::StayAlive, 0, 0, "", &stay_alive_topic);
|
||||||
|
|
||||||
|
log(LogMessage::MqttInfo, 0, 0, "", mqtt_url);
|
||||||
|
|
||||||
|
let mqtt_timeout = 15000;
|
||||||
|
let res = async {
|
||||||
|
while !MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed) {
|
||||||
|
PlantHal::feed_watchdog();
|
||||||
|
Timer::after(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
Ok::<(), FatError>(())
|
||||||
|
}
|
||||||
|
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
bail!("Timeout waiting MQTT connect event")
|
||||||
|
}
|
||||||
|
|
||||||
|
let _ = Topic::General(round_trip_topic.clone())
|
||||||
|
.with_display("online_text")
|
||||||
|
.publish()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let res = async {
|
||||||
|
while !MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed) {
|
||||||
|
PlantHal::feed_watchdog();
|
||||||
|
Timer::after(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
Ok::<(), FatError>(())
|
||||||
|
}
|
||||||
|
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
||||||
|
bail!("Timeout waiting MQTT roundtrip")
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn mqtt_runner(
|
||||||
|
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 4>,
|
||||||
|
) {
|
||||||
|
task.run().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn mqtt_incoming_task(
|
||||||
|
receiver: McutieReceiver,
|
||||||
|
round_trip_topic: String,
|
||||||
|
stay_alive_topic: String,
|
||||||
|
config_update_payload_topic: String,
|
||||||
|
config_update_topic: String,
|
||||||
|
) {
|
||||||
|
loop {
|
||||||
|
let message = receiver.receive().await;
|
||||||
|
match message {
|
||||||
|
MqttMessage::Connected => {
|
||||||
|
info!("Mqtt connected");
|
||||||
|
MQTT_CONNECTED_EVENT_RECEIVED.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
MqttMessage::Publish(topic, payload) => match topic {
|
||||||
|
Topic::DeviceType(_type_topic) => {}
|
||||||
|
Topic::Device(_device_topic) => {}
|
||||||
|
Topic::General(topic) => {
|
||||||
|
let subtopic = topic.as_str();
|
||||||
|
|
||||||
|
if subtopic.eq(round_trip_topic.as_str()) {
|
||||||
|
MQTT_ROUND_TRIP_RECEIVED.store(true, Ordering::Relaxed);
|
||||||
|
} else if subtopic.eq(stay_alive_topic.as_str()) {
|
||||||
|
let value = payload.eq_ignore_ascii_case("true".as_ref())
|
||||||
|
|| payload.eq_ignore_ascii_case("1".as_ref());
|
||||||
|
let a = match value {
|
||||||
|
true => 1,
|
||||||
|
false => 0,
|
||||||
|
};
|
||||||
|
log(LogMessage::MqttStayAliveRec, a, 0, "", "");
|
||||||
|
MQTT_STAY_ALIVE.store(value, Ordering::Relaxed);
|
||||||
|
} else if subtopic.eq(config_update_payload_topic.as_str()) {
|
||||||
|
let payload_str = String::from_utf8_lossy(&payload[..]).to_string();
|
||||||
|
let mut buffer = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
|
||||||
|
*buffer = Some(payload_str);
|
||||||
|
info!("MQTT config update payload received");
|
||||||
|
} else if subtopic.eq(config_update_topic.as_str()) {
|
||||||
|
let update_requested = payload.eq_ignore_ascii_case("true".as_ref())
|
||||||
|
|| payload.eq_ignore_ascii_case("1".as_ref());
|
||||||
|
if update_requested {
|
||||||
|
info!("MQTT config update requested");
|
||||||
|
let payload_lock = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
|
||||||
|
if let Some(payload_str) = payload_lock.as_ref() {
|
||||||
|
match serde_json::from_str::<crate::config::PlantControllerConfig>(payload_str) {
|
||||||
|
Ok(config) => {
|
||||||
|
info!("Deserialized config, applying...");
|
||||||
|
let board_mutex = crate::BOARD_ACCESS.get().await;
|
||||||
|
let mut board = board_mutex.lock().await;
|
||||||
|
if let Err(e) = board.board_hal.get_esp().save_config(payload_str.as_bytes().to_vec()).await {
|
||||||
|
info!("Error saving config to flash: {}", e);
|
||||||
|
let _ = publish("/config/update", "false").await;
|
||||||
|
} else {
|
||||||
|
board.board_hal.set_config(config);
|
||||||
|
info!("Config applied, rebooting");
|
||||||
|
let _ = publish("/config/update", "false").await;
|
||||||
|
board.board_hal.get_esp().deep_sleep_ms(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
info!("Error deserializing config: {}", e);
|
||||||
|
let _ = publish("/config/update", "false").await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
info!("No config update payload available");
|
||||||
|
let _ = publish("/config/update", "false").await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log(LogMessage::UnknownTopic, 0, 0, "", &topic);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
MqttMessage::Disconnected => {
|
||||||
|
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
||||||
|
info!("Mqtt disconnected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
419
rust/src/network.rs
Normal file
419
rust/src/network.rs
Normal file
@@ -0,0 +1,419 @@
|
|||||||
|
use crate::bail;
|
||||||
|
use crate::config::NetworkConfig;
|
||||||
|
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||||
|
use crate::hal::{PlantHal, HAL};
|
||||||
|
use crate::mqtt;
|
||||||
|
use crate::util::mk_static;
|
||||||
|
use alloc::string::{String, ToString};
|
||||||
|
use alloc::sync::Arc;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use core::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
|
||||||
|
use embassy_executor::Spawner;
|
||||||
|
use embassy_net::dns::DnsQueryType;
|
||||||
|
use embassy_net::udp::{PacketMetadata, UdpSocket};
|
||||||
|
use embassy_net::{DhcpConfig, Runner, Stack, StackResources, StaticConfigV4};
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::mutex::{Mutex, MutexGuard};
|
||||||
|
use embassy_time::{Duration, Timer, WithTimeout};
|
||||||
|
use option_lock::OptionLock;
|
||||||
|
use edge_dhcp::{
|
||||||
|
io::{self, DEFAULT_SERVER_PORT},
|
||||||
|
server::{Server, ServerOptions},
|
||||||
|
};
|
||||||
|
use edge_nal::UdpBind;
|
||||||
|
use edge_nal_embassy::{Udp, UdpBuffers};
|
||||||
|
use esp_hal::rng::Rng;
|
||||||
|
use esp_println::println;
|
||||||
|
use esp_radio::wifi::ap::AccessPointConfig;
|
||||||
|
use esp_radio::wifi::sta::StationConfig;
|
||||||
|
use esp_radio::wifi::{AuthenticationMethod, Config, Interface};
|
||||||
|
use log::{info, warn, error};
|
||||||
|
use serde::Serialize;
|
||||||
|
use sntpc::{NtpContext, NtpTimestampGenerator, NtpUdpSocket, get_time};
|
||||||
|
|
||||||
|
const NTP_SERVER: &str = "pool.ntp.org";
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Default)]
|
||||||
|
struct Timestamp {
|
||||||
|
stamp: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NtpTimestampGenerator for Timestamp {
|
||||||
|
fn init(&mut self) {
|
||||||
|
self.stamp = DateTime::default();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timestamp_sec(&self) -> u64 {
|
||||||
|
self.stamp.timestamp() as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timestamp_subsec_micros(&self) -> u32 {
|
||||||
|
self.stamp.timestamp_subsec_micros()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EmbassyNtpSocket<'a, 'b> {
|
||||||
|
socket: &'a UdpSocket<'b>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, 'b> EmbassyNtpSocket<'a, 'b> {
|
||||||
|
fn new(socket: &'a UdpSocket<'b>) -> Self {
|
||||||
|
Self { socket }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NtpUdpSocket for EmbassyNtpSocket<'_, '_> {
|
||||||
|
async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> sntpc::Result<usize> {
|
||||||
|
self.socket
|
||||||
|
.send_to(buf, addr)
|
||||||
|
.await
|
||||||
|
.map_err(|_| sntpc::Error::Network)?;
|
||||||
|
Ok(buf.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn recv_from(&self, buf: &mut [u8]) -> sntpc::Result<(usize, SocketAddr)> {
|
||||||
|
let (len, metadata) = self
|
||||||
|
.socket
|
||||||
|
.recv_from(buf)
|
||||||
|
.await
|
||||||
|
.map_err(|_| sntpc::Error::Network)?;
|
||||||
|
let addr = match metadata.endpoint.addr {
|
||||||
|
embassy_net::IpAddress::Ipv4(ip) => IpAddr::V4(ip),
|
||||||
|
embassy_net::IpAddress::Ipv6(ip) => IpAddr::V6(ip),
|
||||||
|
};
|
||||||
|
Ok((len, SocketAddr::new(addr, metadata.endpoint.port)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn sntp(max_wait_ms: u32, stack: Stack<'_>) -> FatResult<DateTime<Utc>> {
|
||||||
|
println!("start sntp");
|
||||||
|
let mut rx_meta = [PacketMetadata::EMPTY; 16];
|
||||||
|
let mut rx_buffer = [0; 4096];
|
||||||
|
let mut tx_meta = [PacketMetadata::EMPTY; 16];
|
||||||
|
let mut tx_buffer = [0; 4096];
|
||||||
|
|
||||||
|
let mut socket = UdpSocket::new(
|
||||||
|
stack,
|
||||||
|
&mut rx_meta,
|
||||||
|
&mut rx_buffer,
|
||||||
|
&mut tx_meta,
|
||||||
|
&mut tx_buffer,
|
||||||
|
);
|
||||||
|
socket.bind(123).context("Could not bind UDP socket")?;
|
||||||
|
|
||||||
|
let context = NtpContext::new(Timestamp::default());
|
||||||
|
let ntp_socket = EmbassyNtpSocket::new(&socket);
|
||||||
|
|
||||||
|
let ntp_addrs = stack
|
||||||
|
.dns_query(NTP_SERVER, DnsQueryType::A)
|
||||||
|
.await
|
||||||
|
.context("Failed to resolve DNS")?;
|
||||||
|
|
||||||
|
if ntp_addrs.is_empty() {
|
||||||
|
bail!("No IP addresses found for NTP server");
|
||||||
|
}
|
||||||
|
let ntp = ntp_addrs[0];
|
||||||
|
info!("NTP server: {ntp:?}");
|
||||||
|
|
||||||
|
let mut counter = 0;
|
||||||
|
loop {
|
||||||
|
let addr: IpAddr = ntp.into();
|
||||||
|
let timeout = get_time(SocketAddr::from((addr, 123)), &ntp_socket, context)
|
||||||
|
.with_timeout(Duration::from_millis((max_wait_ms / 10) as u64))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match timeout {
|
||||||
|
Ok(result) => {
|
||||||
|
let time = result?;
|
||||||
|
info!("Time: {time:?}");
|
||||||
|
return DateTime::from_timestamp(time.seconds as i64, 0)
|
||||||
|
.context("Could not convert Sntp result");
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
warn!("sntp timeout, retry: {err:?}");
|
||||||
|
counter += 1;
|
||||||
|
if counter > 10 {
|
||||||
|
bail!("Failed to get time from NTP server");
|
||||||
|
}
|
||||||
|
Timer::after(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Debug, PartialEq)]
|
||||||
|
pub enum SntpMode {
|
||||||
|
OFFLINE,
|
||||||
|
SYNC { current: DateTime<Utc> },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Debug, PartialEq)]
|
||||||
|
pub enum NetworkMode {
|
||||||
|
WIFI {
|
||||||
|
sntp: SntpMode,
|
||||||
|
mqtt: bool,
|
||||||
|
ip_address: String,
|
||||||
|
},
|
||||||
|
OFFLINE,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task(pool_size = 2)]
|
||||||
|
pub(crate) async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
|
||||||
|
runner.run().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
pub(crate) async fn run_dhcp(stack: Stack<'static>, ip: Ipv4Addr) {
|
||||||
|
let mut buf = [0u8; 1500];
|
||||||
|
|
||||||
|
let mut gw_buf = [Ipv4Addr::UNSPECIFIED];
|
||||||
|
|
||||||
|
let buffers = UdpBuffers::<3, 1024, 1024, 10>::new();
|
||||||
|
let unbound_socket = Udp::new(stack, &buffers);
|
||||||
|
let mut bound_socket = match unbound_socket
|
||||||
|
.bind(SocketAddr::V4(SocketAddrV4::new(
|
||||||
|
Ipv4Addr::UNSPECIFIED,
|
||||||
|
DEFAULT_SERVER_PORT,
|
||||||
|
)))
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => {
|
||||||
|
error!("dhcp task failed to bind socket: {:?}", e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loop {
|
||||||
|
_ = io::server::run(
|
||||||
|
&mut Server::<_, 64>::new_with_et(ip),
|
||||||
|
&ServerOptions::new(ip, Some(&mut gw_buf)),
|
||||||
|
&mut bound_socket,
|
||||||
|
&mut buf,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.inspect_err(|e| warn!("DHCP server error: {e:?}"));
|
||||||
|
Timer::after(Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn wifi_ap(
|
||||||
|
ssid: String,
|
||||||
|
interface_ap: Interface<'static>,
|
||||||
|
controller: &Arc<Mutex<CriticalSectionRawMutex, esp_radio::wifi::WifiController<'static>>>,
|
||||||
|
rng: &mut Rng,
|
||||||
|
spawner: Spawner,
|
||||||
|
) -> FatResult<Stack<'static>> {
|
||||||
|
let gw_ip_addr = Ipv4Addr::new(192, 168, 71, 1);
|
||||||
|
|
||||||
|
let config = embassy_net::Config::ipv4_static(StaticConfigV4 {
|
||||||
|
address: embassy_net::Ipv4Cidr::new(gw_ip_addr, 24),
|
||||||
|
gateway: Some(gw_ip_addr),
|
||||||
|
dns_servers: Default::default(),
|
||||||
|
});
|
||||||
|
|
||||||
|
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||||
|
|
||||||
|
println!("init secondary stack");
|
||||||
|
let (stack, runner) = embassy_net::new(
|
||||||
|
interface_ap,
|
||||||
|
config,
|
||||||
|
mk_static!(StackResources<4>, StackResources::<4>::new()),
|
||||||
|
seed,
|
||||||
|
);
|
||||||
|
let stack = mk_static!(Stack, stack);
|
||||||
|
|
||||||
|
let client_config =
|
||||||
|
Config::AccessPoint(AccessPointConfig::default().with_ssid(ssid.clone()));
|
||||||
|
controller.lock().await.set_config(&client_config)?;
|
||||||
|
|
||||||
|
println!("start net task");
|
||||||
|
spawner.spawn(net_task(runner)?);
|
||||||
|
println!("run dhcp");
|
||||||
|
spawner.spawn(run_dhcp(*stack, gw_ip_addr)?);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if stack.is_link_up() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Timer::after(Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
|
while !stack.is_config_up() {
|
||||||
|
Timer::after(Duration::from_millis(100)).await
|
||||||
|
}
|
||||||
|
println!("Connect to the AP `${ssid}` and point your browser to http://{gw_ip_addr}/");
|
||||||
|
stack
|
||||||
|
.config_v4()
|
||||||
|
.inspect(|c| println!("ipv4 config: {c:?}"));
|
||||||
|
|
||||||
|
Ok(*stack)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn wifi(
|
||||||
|
network_config: &NetworkConfig,
|
||||||
|
interface_sta: Interface<'static>,
|
||||||
|
controller: &Arc<Mutex<CriticalSectionRawMutex, esp_radio::wifi::WifiController<'static>>>,
|
||||||
|
rng: &mut Rng,
|
||||||
|
spawner: Spawner,
|
||||||
|
) -> FatResult<Stack<'static>> {
|
||||||
|
esp_radio::wifi_set_log_verbose();
|
||||||
|
let ssid = match &network_config.ssid {
|
||||||
|
Some(ssid) => {
|
||||||
|
if ssid.is_empty() {
|
||||||
|
bail!("Wifi ssid was empty")
|
||||||
|
}
|
||||||
|
ssid.as_str().to_string()
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
bail!("Wifi ssid was empty")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
info!("attempting to connect wifi {ssid}");
|
||||||
|
let password = match network_config.password {
|
||||||
|
Some(ref password) => password.as_str().to_string(),
|
||||||
|
None => "".to_string(),
|
||||||
|
};
|
||||||
|
let max_wait = network_config.max_wait;
|
||||||
|
|
||||||
|
let config = embassy_net::Config::dhcpv4(DhcpConfig::default());
|
||||||
|
|
||||||
|
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||||
|
|
||||||
|
let (stack, runner) = embassy_net::new(
|
||||||
|
interface_sta,
|
||||||
|
config,
|
||||||
|
mk_static!(StackResources<8>, StackResources::<8>::new()),
|
||||||
|
seed,
|
||||||
|
);
|
||||||
|
let stack = mk_static!(Stack, stack);
|
||||||
|
|
||||||
|
let auth_method = if password.is_empty() {
|
||||||
|
AuthenticationMethod::None
|
||||||
|
} else {
|
||||||
|
AuthenticationMethod::Wpa2Personal
|
||||||
|
};
|
||||||
|
let client_config = StationConfig::default()
|
||||||
|
.with_ssid(ssid)
|
||||||
|
.with_auth_method(auth_method)
|
||||||
|
.with_scan_method(esp_radio::wifi::sta::ScanMethod::AllChannels)
|
||||||
|
.with_listen_interval(10)
|
||||||
|
.with_beacon_timeout(10)
|
||||||
|
.with_failure_retry_cnt(3)
|
||||||
|
.with_password(password);
|
||||||
|
|
||||||
|
controller
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.set_config(&Config::Station(client_config))?;
|
||||||
|
spawner.spawn(net_task(runner)?);
|
||||||
|
controller
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.connect_async()
|
||||||
|
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||||
|
.await
|
||||||
|
.context("Timeout waiting for wifi sta connected")??;
|
||||||
|
|
||||||
|
let res = async {
|
||||||
|
while !stack.is_link_up() {
|
||||||
|
Timer::after(Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
|
Ok::<(), FatError>(())
|
||||||
|
}
|
||||||
|
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
bail!("Timeout waiting for wifi link up")
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = async {
|
||||||
|
while !stack.is_config_up() {
|
||||||
|
Timer::after(Duration::from_millis(100)).await
|
||||||
|
}
|
||||||
|
Ok::<(), FatError>(())
|
||||||
|
}
|
||||||
|
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if res.is_err() {
|
||||||
|
bail!("Timeout waiting for wifi config up")
|
||||||
|
}
|
||||||
|
|
||||||
|
info!("Connected WIFI, dhcp: {:?}", stack.config_v4());
|
||||||
|
Ok(*stack)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn try_connect_wifi_sntp_mqtt(
|
||||||
|
board: &mut MutexGuard<'static, CriticalSectionRawMutex, HAL<'static>>,
|
||||||
|
stack_store: &mut OptionLock<Stack<'static>>,
|
||||||
|
spawner: Spawner,
|
||||||
|
) -> NetworkMode {
|
||||||
|
let nw_conf = &board.board_hal.get_config().network.clone();
|
||||||
|
let esp = board.board_hal.get_esp();
|
||||||
|
let device = match esp.interface_sta.take() {
|
||||||
|
Some(d) => d,
|
||||||
|
None => {
|
||||||
|
info!("Offline mode due to STA interface already taken");
|
||||||
|
board.board_hal.general_fault(true).await;
|
||||||
|
return NetworkMode::OFFLINE;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match wifi(nw_conf, device, &esp.controller, &mut esp.rng, spawner).await {
|
||||||
|
Ok(stack) => {
|
||||||
|
stack_store.replace(stack);
|
||||||
|
|
||||||
|
let sntp_mode: SntpMode = match sntp(1000 * 10, stack).await {
|
||||||
|
Ok(new_time) => {
|
||||||
|
info!("Using time from sntp {}", new_time.to_rfc3339());
|
||||||
|
let _ = board
|
||||||
|
.board_hal
|
||||||
|
.get_rtc_module()
|
||||||
|
.set_rtc_time(&new_time)
|
||||||
|
.await;
|
||||||
|
SntpMode::SYNC { current: new_time }
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
warn!("sntp error: {err}");
|
||||||
|
board.board_hal.general_fault(true).await;
|
||||||
|
SntpMode::OFFLINE
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mqtt_connected = if board.board_hal.get_config().network.mqtt_url.is_some() {
|
||||||
|
let nw_config = board.board_hal.get_config().network.clone();
|
||||||
|
let nw_config = mk_static!(NetworkConfig, nw_config);
|
||||||
|
match mqtt::mqtt_init(nw_config, stack, spawner).await {
|
||||||
|
Ok(_) => {
|
||||||
|
info!("Mqtt connection ready");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
warn!("Could not connect mqtt due to {err}");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
};
|
||||||
|
|
||||||
|
let ip = match stack.config_v4() {
|
||||||
|
Some(config) => config.address.address().to_string(),
|
||||||
|
None => match stack.config_v6() {
|
||||||
|
Some(config) => config.address.address().to_string(),
|
||||||
|
None => String::from("No IP"),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
NetworkMode::WIFI {
|
||||||
|
sntp: sntp_mode,
|
||||||
|
mqtt: mqtt_connected,
|
||||||
|
ip_address: ip,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
info!("Offline mode due to {err}");
|
||||||
|
board.board_hal.general_fault(true).await;
|
||||||
|
NetworkMode::OFFLINE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -118,7 +118,11 @@ fn map_range_moisture(
|
|||||||
impl PlantState {
|
impl PlantState {
|
||||||
pub async 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 {
|
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).await {
|
match board
|
||||||
|
.board_hal
|
||||||
|
.measure_moisture_hz(plant_id, Sensor::A)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(raw) => match map_range_moisture(
|
Ok(raw) => match map_range_moisture(
|
||||||
raw,
|
raw,
|
||||||
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
|
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
|
||||||
@@ -139,7 +143,11 @@ impl PlantState {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let sensor_b = if board.board_hal.get_config().plants[plant_id].sensor_b {
|
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).await {
|
match board
|
||||||
|
.board_hal
|
||||||
|
.measure_moisture_hz(plant_id, Sensor::B)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(raw) => match map_range_moisture(
|
Ok(raw) => match map_range_moisture(
|
||||||
raw,
|
raw,
|
||||||
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
|
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
|
||||||
@@ -264,50 +272,50 @@ impl PlantState {
|
|||||||
PlantWateringMode::TimerOnly => !self.pump_in_timeout(plant_conf, current_time),
|
PlantWateringMode::TimerOnly => !self.pump_in_timeout(plant_conf, current_time),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//
|
|
||||||
// pub fn to_mqtt_info(
|
pub fn to_mqtt_info(
|
||||||
// &self,
|
&self,
|
||||||
// plant_conf: &PlantConfig,
|
plant_conf: &PlantConfig,
|
||||||
// current_time: &DateTime<Tz>,
|
current_time: &DateTime<Tz>,
|
||||||
// ) -> PlantInfo<'_> {
|
) -> PlantInfo<'_> {
|
||||||
// PlantInfo {
|
PlantInfo {
|
||||||
// sensor_a: &self.sensor_a,
|
sensor_a: &self.sensor_a,
|
||||||
// sensor_b: &self.sensor_b,
|
sensor_b: &self.sensor_b,
|
||||||
// mode: plant_conf.mode,
|
mode: plant_conf.mode,
|
||||||
// do_water: self.needs_to_be_watered(plant_conf, current_time),
|
do_water: self.needs_to_be_watered(plant_conf, current_time),
|
||||||
// dry: if let Some(moisture_percent) = self.plant_moisture().0 {
|
dry: if let Some(moisture_percent) = self.plant_moisture().0 {
|
||||||
// moisture_percent < plant_conf.target_moisture
|
moisture_percent < plant_conf.target_moisture
|
||||||
// } else {
|
} else {
|
||||||
// false
|
false
|
||||||
// },
|
},
|
||||||
// cooldown: self.pump_in_timeout(plant_conf, current_time),
|
cooldown: self.pump_in_timeout(plant_conf, current_time),
|
||||||
// out_of_work_hour: in_time_range(
|
out_of_work_hour: in_time_range(
|
||||||
// current_time,
|
current_time,
|
||||||
// plant_conf.pump_hour_start,
|
plant_conf.pump_hour_start,
|
||||||
// plant_conf.pump_hour_end,
|
plant_conf.pump_hour_end,
|
||||||
// ),
|
),
|
||||||
// consecutive_pump_count: self.pump.consecutive_pump_count,
|
consecutive_pump_count: self.pump.consecutive_pump_count,
|
||||||
// pump_error: self.pump.is_err(plant_conf),
|
pump_error: self.pump.is_err(plant_conf),
|
||||||
// last_pump: self
|
last_pump: self
|
||||||
// .pump
|
.pump
|
||||||
// .previous_pump
|
.previous_pump
|
||||||
// .map(|t| t.with_timezone(¤t_time.timezone())),
|
.map(|t| t.with_timezone(¤t_time.timezone())),
|
||||||
// next_pump: if matches!(
|
next_pump: if matches!(
|
||||||
// plant_conf.mode,
|
plant_conf.mode,
|
||||||
// PlantWateringMode::TimerOnly
|
PlantWateringMode::TimerOnly
|
||||||
// | PlantWateringMode::TargetMoisture
|
| PlantWateringMode::TargetMoisture
|
||||||
// | PlantWateringMode::MinMoisture
|
| PlantWateringMode::MinMoisture
|
||||||
// ) {
|
) {
|
||||||
// self.pump.previous_pump.and_then(|last_pump| {
|
self.pump.previous_pump.and_then(|last_pump| {
|
||||||
// last_pump
|
last_pump
|
||||||
// .checked_add_signed(TimeDelta::minutes(plant_conf.pump_cooldown_min.into()))
|
.checked_add_signed(TimeDelta::minutes(plant_conf.pump_cooldown_min.into()))
|
||||||
// .map(|t| t.with_timezone(¤t_time.timezone()))
|
.map(|t| t.with_timezone(¤t_time.timezone()))
|
||||||
// })
|
})
|
||||||
// } else {
|
} else {
|
||||||
// None
|
None
|
||||||
// },
|
},
|
||||||
// }
|
}
|
||||||
// }
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Serialize)]
|
#[derive(Debug, PartialEq, Serialize)]
|
||||||
@@ -330,8 +338,8 @@ pub struct PlantInfo<'a> {
|
|||||||
/// how often has the pump been watered without reaching target moisture
|
/// how often has the pump been watered without reaching target moisture
|
||||||
consecutive_pump_count: u32,
|
consecutive_pump_count: u32,
|
||||||
pump_error: Option<PumpError>,
|
pump_error: Option<PumpError>,
|
||||||
// /// last time when the pump was active
|
/// last time when the pump was active
|
||||||
// last_pump: Option<DateTime<Tz>>,
|
last_pump: Option<DateTime<Tz>>,
|
||||||
// /// next time when pump should activate
|
/// next time when pump should activate
|
||||||
// next_pump: Option<DateTime<Tz>>,
|
next_pump: Option<DateTime<Tz>>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
use crate::alloc::string::{String, ToString};
|
use crate::alloc::string::{String, ToString};
|
||||||
use crate::config::TankConfig;
|
use crate::config::TankConfig;
|
||||||
|
use crate::hal::HAL;
|
||||||
|
use crate::fat_error::FatResult;
|
||||||
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::mutex::MutexGuard;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
const OPEN_TANK_VOLTAGE: f32 = 3.0;
|
const OPEN_TANK_VOLTAGE: f32 = 3.0;
|
||||||
@@ -113,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 mut tank_err: Option<TankError> = None;
|
||||||
let left_ml = match self.left_ml(config) {
|
let left_ml = match self.left_ml(config) {
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
@@ -150,40 +154,41 @@ impl TankState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// pub fn determine_tank_state(board: &mut std::sync::MutexGuard<'_, HAL<'_>>) -> TankState {
|
pub async fn determine_tank_state(
|
||||||
// if board.board_hal.get_config().tank.tank_sensor_enabled {
|
board: &mut MutexGuard<'static, CriticalSectionRawMutex, HAL<'static>>,
|
||||||
// match board
|
) -> TankState {
|
||||||
// .board_hal
|
if board.board_hal.get_config().tank.tank_sensor_enabled {
|
||||||
// .get_tank_sensor()
|
match board
|
||||||
// .context("no sensor")
|
.board_hal
|
||||||
// .and_then(|f| f.tank_sensor_voltage())
|
.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),
|
{
|
||||||
// Err(err) => TankState::Error(TankError::BoardError(err.to_string())),
|
Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv.await.unwrap()),
|
||||||
// }
|
Err(err) => TankState::Error(TankError::BoardError(err.to_string())),
|
||||||
// } else {
|
}
|
||||||
// TankState::Disabled
|
} else {
|
||||||
// }
|
TankState::Disabled
|
||||||
// }
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
/// Information structure send to mqtt for monitoring purposes
|
/// Information structure send to mqtt for monitoring purposes
|
||||||
pub struct TankInfo {
|
pub struct TankInfo {
|
||||||
/// there is enough water in the tank
|
/// there is enough water in the tank
|
||||||
enough_water: bool,
|
pub(crate) enough_water: bool,
|
||||||
/// warning that water needs to be refilled soon
|
/// 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
|
/// 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
|
/// 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 water sensor value
|
||||||
raw: Option<f32>,
|
pub(crate) raw: Option<f32>,
|
||||||
/// percent value
|
/// percent value
|
||||||
percent: Option<f32>,
|
pub(crate) percent: Option<f32>,
|
||||||
/// water in the tank might be frozen
|
/// water in the tank might be frozen
|
||||||
water_frozen: bool,
|
pub(crate) water_frozen: bool,
|
||||||
/// water temperature
|
/// water temperature
|
||||||
water_temp: Option<f32>,
|
pub(crate) water_temp: Option<f32>,
|
||||||
temp_sensor_error: Option<String>,
|
pub(crate) temp_sensor_error: Option<String>,
|
||||||
}
|
}
|
||||||
|
|||||||
10
rust/src/util.rs
Normal file
10
rust/src/util.rs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
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
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) use mk_static;
|
||||||
191
rust/src/webserver/backup_manager.rs
Normal file
191
rust/src/webserver/backup_manager.rs
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
|
use crate::hal::rtc::X25;
|
||||||
|
use crate::BOARD_ACCESS;
|
||||||
|
use alloc::borrow::ToOwned;
|
||||||
|
use alloc::format;
|
||||||
|
use alloc::string::{String, ToString};
|
||||||
|
use chrono::DateTime;
|
||||||
|
use edge_http::io::server::Connection;
|
||||||
|
use edge_nal::io::{Read, Write};
|
||||||
|
use log::info;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||||
|
pub struct WebBackupHeader {
|
||||||
|
timestamp: String,
|
||||||
|
size: u16,
|
||||||
|
}
|
||||||
|
pub(crate) async fn get_backup_config<T, const N: usize>(
|
||||||
|
conn: &mut Connection<'_, T, { N }>,
|
||||||
|
) -> FatResult<Option<u32>>
|
||||||
|
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(Some(409));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
chunk += 1;
|
||||||
|
}
|
||||||
|
// Second pass: stream data
|
||||||
|
conn.initiate_response(
|
||||||
|
200,
|
||||||
|
Some("OK"),
|
||||||
|
&[
|
||||||
|
("Access-Control-Allow-Origin", "*"),
|
||||||
|
("Access-Control-Allow-Headers", "*"),
|
||||||
|
("Access-Control-Allow-Methods", "*"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.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(Some(200))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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 = 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;
|
||||||
|
conn.initiate_response(
|
||||||
|
200,
|
||||||
|
Some("OK"),
|
||||||
|
&[
|
||||||
|
("Access-Control-Allow-Origin", "*"),
|
||||||
|
("Access-Control-Allow-Headers", "*"),
|
||||||
|
("Access-Control-Allow-Methods", "*"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(Some("saved".to_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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))
|
||||||
|
}
|
||||||
160
rust/src/webserver/file_manager.rs
Normal file
160
rust/src/webserver/file_manager.rs
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
|
use crate::BOARD_ACCESS;
|
||||||
|
use alloc::borrow::ToOwned;
|
||||||
|
use alloc::format;
|
||||||
|
use alloc::string::String;
|
||||||
|
use edge_http::io::server::Connection;
|
||||||
|
use edge_http::Method;
|
||||||
|
use edge_nal::io::{Read, Write};
|
||||||
|
use log::info;
|
||||||
|
|
||||||
|
pub(crate) 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))
|
||||||
|
}
|
||||||
|
pub(crate) async fn file_operations<T, const N: usize>(
|
||||||
|
conn: &mut Connection<'_, T, { N }>,
|
||||||
|
method: Method,
|
||||||
|
path: &&str,
|
||||||
|
prefix: &&str,
|
||||||
|
) -> Result<Option<u32>, FatError>
|
||||||
|
where
|
||||||
|
T: Read + Write,
|
||||||
|
{
|
||||||
|
let filename = &path[prefix.len()..];
|
||||||
|
info!("file request for {} with method {}", filename, method);
|
||||||
|
Ok(match method {
|
||||||
|
Method::Delete => {
|
||||||
|
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||||
|
board
|
||||||
|
.board_hal
|
||||||
|
.get_esp()
|
||||||
|
.delete_file(filename.to_owned())
|
||||||
|
.await?;
|
||||||
|
conn.initiate_response(
|
||||||
|
200,
|
||||||
|
Some("OK"),
|
||||||
|
&[
|
||||||
|
("Access-Control-Allow-Origin", "*"),
|
||||||
|
("Access-Control-Allow-Headers", "*"),
|
||||||
|
("Access-Control-Allow-Methods", "*"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Some(200)
|
||||||
|
}
|
||||||
|
Method::Get => {
|
||||||
|
let disposition = 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", disposition.as_str()),
|
||||||
|
("Content-Length", &format!("{}", size)),
|
||||||
|
("Access-Control-Allow-Origin", "*"),
|
||||||
|
("Access-Control-Allow-Headers", "*"),
|
||||||
|
("Access-Control-Allow-Methods", "*"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let mut chunk = 0;
|
||||||
|
loop {
|
||||||
|
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||||
|
board.board_hal.progress(chunk).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 the file is deleted first; 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;
|
||||||
|
conn.initiate_response(
|
||||||
|
200,
|
||||||
|
Some("OK"),
|
||||||
|
&[
|
||||||
|
("Access-Control-Allow-Origin", "*"),
|
||||||
|
("Access-Control-Allow-Headers", "*"),
|
||||||
|
("Access-Control-Allow-Methods", "*"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Some(200)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
184
rust/src/webserver/get_json.rs
Normal file
184
rust/src/webserver/get_json.rs
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
|
use crate::hal::PLANT_COUNT;
|
||||||
|
use crate::log::LogMessage;
|
||||||
|
use crate::plant_state::{MoistureSensorState, PlantState};
|
||||||
|
use crate::tank::determine_tank_state;
|
||||||
|
use crate::{get_version, BOARD_ACCESS};
|
||||||
|
use alloc::format;
|
||||||
|
use alloc::string::{String, ToString};
|
||||||
|
use alloc::vec::Vec;
|
||||||
|
use chrono_tz::Tz;
|
||||||
|
use core::str::FromStr;
|
||||||
|
use edge_http::io::server::Connection;
|
||||||
|
use edge_nal::io::{Read, Write};
|
||||||
|
use log::info;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[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,
|
||||||
|
}
|
||||||
|
pub(crate) async fn get_live_moisture<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;
|
||||||
|
let mut plant_state = Vec::new();
|
||||||
|
for i in 0..PLANT_COUNT {
|
||||||
|
plant_state.push(PlantState::read_hardware_state(i, &mut board).await);
|
||||||
|
}
|
||||||
|
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)?;
|
||||||
|
|
||||||
|
Ok(Some(json))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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,
|
||||||
|
))?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn get_timezones() -> FatResult<Option<String>> {
|
||||||
|
// Get all timezones compiled into the binary from 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))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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 = match conf.timezone.as_ref() {
|
||||||
|
None => Tz::UTC,
|
||||||
|
Some(tz_string) => match Tz::from_str(tz_string) {
|
||||||
|
Ok(tz) => tz,
|
||||||
|
Err(err) => {
|
||||||
|
info!("failed parsing timezone {err}");
|
||||||
|
Tz::UTC
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let native = board
|
||||||
|
.board_hal
|
||||||
|
.get_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))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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::log_localisation_config(),
|
||||||
|
)?))
|
||||||
|
}
|
||||||
36
rust/src/webserver/get_log.rs
Normal file
36
rust/src/webserver/get_log.rs
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
use crate::fat_error::FatResult;
|
||||||
|
use crate::log::LOG_ACCESS;
|
||||||
|
use edge_http::io::server::Connection;
|
||||||
|
use edge_nal::io::{Read, Write};
|
||||||
|
|
||||||
|
pub(crate) async fn get_log<T, const N: usize>(
|
||||||
|
conn: &mut Connection<'_, T, N>,
|
||||||
|
) -> FatResult<Option<u32>>
|
||||||
|
where
|
||||||
|
T: Read + Write,
|
||||||
|
{
|
||||||
|
let log = LOG_ACCESS.lock().await.get();
|
||||||
|
conn.initiate_response(
|
||||||
|
200,
|
||||||
|
Some("OK"),
|
||||||
|
&[
|
||||||
|
("Content-Type", "text/javascript"),
|
||||||
|
("Access-Control-Allow-Origin", "*"),
|
||||||
|
("Access-Control-Allow-Headers", "*"),
|
||||||
|
("Access-Control-Allow-Methods", "*"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.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(Some(200))
|
||||||
|
}
|
||||||
50
rust/src/webserver/get_static.rs
Normal file
50
rust/src/webserver/get_static.rs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
use crate::fat_error::FatError;
|
||||||
|
use edge_http::io::server::Connection;
|
||||||
|
use edge_nal::io::{Read, Write};
|
||||||
|
|
||||||
|
pub(crate) async fn serve_favicon<T, const N: usize>(
|
||||||
|
conn: &mut Connection<'_, T, { N }>,
|
||||||
|
) -> Result<Option<u32>, FatError>
|
||||||
|
where
|
||||||
|
T: Read + Write,
|
||||||
|
{
|
||||||
|
conn.initiate_response(200, Some("OK"), &[("Content-Type", "image/x-icon")])
|
||||||
|
.await?;
|
||||||
|
conn.write_all(include_bytes!("favicon.ico")).await?;
|
||||||
|
Ok(Some(200))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn serve_index<T, const N: usize>(
|
||||||
|
conn: &mut Connection<'_, T, { N }>,
|
||||||
|
) -> Result<Option<u32>, FatError>
|
||||||
|
where
|
||||||
|
T: Read + Write,
|
||||||
|
{
|
||||||
|
conn.initiate_response(
|
||||||
|
200,
|
||||||
|
Some("OK"),
|
||||||
|
&[("Content-Type", "text/html"), ("Content-Encoding", "gzip")],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
conn.write_all(include_bytes!("index.html.gz")).await?;
|
||||||
|
Ok(Some(200))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn serve_bundle<T, const N: usize>(
|
||||||
|
conn: &mut Connection<'_, T, { N }>,
|
||||||
|
) -> Result<Option<u32>, FatError>
|
||||||
|
where
|
||||||
|
T: Read + Write,
|
||||||
|
{
|
||||||
|
conn.initiate_response(
|
||||||
|
200,
|
||||||
|
Some("OK"),
|
||||||
|
&[
|
||||||
|
("Content-Type", "text/javascript"),
|
||||||
|
("Content-Encoding", "gzip"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
conn.write_all(include_bytes!("bundle.js.gz")).await?;
|
||||||
|
Ok(Some(200))
|
||||||
|
}
|
||||||
@@ -1,238 +1,42 @@
|
|||||||
//offer ota and config mode
|
//offer ota and config mode
|
||||||
|
|
||||||
use crate::config::PlantControllerConfig;
|
mod backup_manager;
|
||||||
use crate::{get_version, log::LogMessage, BOARD_ACCESS};
|
mod file_manager;
|
||||||
|
mod get_json;
|
||||||
|
mod get_log;
|
||||||
|
mod get_static;
|
||||||
|
mod post_json;
|
||||||
|
|
||||||
|
use crate::fat_error::{FatError, FatResult};
|
||||||
|
use crate::webserver::backup_manager::{backup_config, backup_info, get_backup_config};
|
||||||
|
use crate::webserver::file_manager::{file_operations, list_files};
|
||||||
|
use crate::webserver::get_json::{
|
||||||
|
get_battery_state, get_config, get_live_moisture, get_log_localization_config, get_solar_state,
|
||||||
|
get_time, get_timezones, get_version_web, tank_info,
|
||||||
|
};
|
||||||
|
use crate::webserver::get_log::get_log;
|
||||||
|
use crate::webserver::get_static::{serve_bundle, serve_favicon, serve_index};
|
||||||
|
use crate::webserver::post_json::{
|
||||||
|
board_test, night_lamp_test, pump_test, set_config, wifi_scan, write_time,
|
||||||
|
};
|
||||||
|
use crate::{bail, BOARD_ACCESS};
|
||||||
use alloc::borrow::ToOwned;
|
use alloc::borrow::ToOwned;
|
||||||
use alloc::format;
|
|
||||||
use alloc::string::{String, ToString};
|
use alloc::string::{String, ToString};
|
||||||
use alloc::sync::Arc;
|
use alloc::sync::Arc;
|
||||||
use alloc::vec::Vec;
|
use alloc::vec::Vec;
|
||||||
use anyhow::{bail};
|
|
||||||
use core::fmt::{Debug, Display};
|
use core::fmt::{Debug, Display};
|
||||||
use core::net::{IpAddr, Ipv4Addr, SocketAddr};
|
use core::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||||
use core::result::Result::Ok;
|
use core::result::Result::Ok;
|
||||||
use core::str::from_utf8;
|
|
||||||
use core::sync::atomic::{AtomicBool, Ordering};
|
use core::sync::atomic::{AtomicBool, Ordering};
|
||||||
use chrono::DateTime;
|
|
||||||
use edge_http::io::server::{Connection, Handler, Server};
|
use edge_http::io::server::{Connection, Handler, Server};
|
||||||
use edge_http::io::Error;
|
|
||||||
use edge_http::Method;
|
use edge_http::Method;
|
||||||
use edge_nal::{TcpBind};
|
use edge_nal::TcpBind;
|
||||||
|
use edge_nal::io::{Read, Write};
|
||||||
use edge_nal_embassy::{Tcp, TcpBuffers};
|
use edge_nal_embassy::{Tcp, TcpBuffers};
|
||||||
use embassy_net::Stack;
|
use embassy_net::Stack;
|
||||||
use embassy_time::Instant;
|
use embassy_time::Instant;
|
||||||
use embedded_io_async::{Read, Write};
|
|
||||||
use esp_println::println;
|
|
||||||
use log::info;
|
use log::info;
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use crate::hal::{esp_set_time, esp_time};
|
|
||||||
use crate::log::{LOG_ACCESS};
|
|
||||||
|
|
||||||
#[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_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 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");
|
|
||||||
//
|
|
||||||
// //TODO how to handle progress here? prior versions animated the fault leds while running
|
|
||||||
// board.board_hal.get_rtc_module().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_rtc_module().get_backup_config() {
|
|
||||||
// Ok(config) => from_utf8(&config)?.to_owned(),
|
|
||||||
// Err(err) => {
|
|
||||||
// log::info!("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_rtc_module().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(err) => {
|
|
||||||
// let wbh = WebBackupHeader {
|
|
||||||
// timestamp: err.to_string(),
|
|
||||||
// size: 0,
|
|
||||||
// };
|
|
||||||
// serde_json::to_string(&wbh)?
|
|
||||||
// }
|
|
||||||
// };
|
|
||||||
// anyhow::Ok(Some(json))
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
|
|
||||||
//
|
|
||||||
|
|
||||||
//
|
|
||||||
// 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();
|
|
||||||
//
|
|
||||||
// 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)?;
|
|
||||||
// board.board_hal.pump(pump_test.pump, false)?;
|
|
||||||
// anyhow::Ok(Some(serde_json::to_string(&pump_result)?))
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// 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
|
|
||||||
// .get_tank_sensor()
|
|
||||||
// .context("no sensor")
|
|
||||||
// .and_then(|f| f.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 })?;
|
|
||||||
// log::info!("Sending ssid list {}", &ssid_json);
|
|
||||||
// anyhow::Ok(Some(ssid_json))
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
|
|
||||||
//
|
|
||||||
// fn ota(
|
// fn ota(
|
||||||
// request: &mut Request<&mut EspHttpConnection>,
|
// request: &mut Request<&mut EspHttpConnection>,
|
||||||
// ) -> Result<Option<std::string::String>, anyhow::Error> {
|
// ) -> Result<Option<std::string::String>, anyhow::Error> {
|
||||||
@@ -280,17 +84,17 @@ pub struct NightLampCommand {
|
|||||||
// }
|
// }
|
||||||
//
|
//
|
||||||
|
|
||||||
struct HttpHandler {
|
struct HTTPRequestRouter {
|
||||||
reboot_now: Arc<AtomicBool>,
|
reboot_now: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Handler for HttpHandler {
|
impl Handler for HTTPRequestRouter {
|
||||||
type Error<E: core::fmt::Debug> = Error<E>;
|
type Error<E: Debug> = FatError;
|
||||||
async fn handle<'a, T, const N: usize>(
|
async fn handle<'a, T, const N: usize>(
|
||||||
&self,
|
&self,
|
||||||
_task_id: impl Display + Copy,
|
_task_id: impl Display + Copy,
|
||||||
conn: &mut Connection<'a, T, N>,
|
conn: &mut Connection<'a, T, N>,
|
||||||
) -> anyhow::Result<(), Self::Error<T::Error>>
|
) -> Result<(), FatError>
|
||||||
where
|
where
|
||||||
T: Read + Write,
|
T: Read + Write,
|
||||||
{
|
{
|
||||||
@@ -302,120 +106,15 @@ impl Handler for HttpHandler {
|
|||||||
|
|
||||||
let prefix = "/file?filename=";
|
let prefix = "/file?filename=";
|
||||||
let status = if path.starts_with(prefix) {
|
let status = if path.starts_with(prefix) {
|
||||||
let filename = &path[prefix.len()..];
|
file_operations(conn, method, &path, &prefix).await?
|
||||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
|
||||||
info!("file request for {} with method {}", filename, method);
|
|
||||||
match method {
|
|
||||||
Method::Delete => {
|
|
||||||
board
|
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.delete_file(filename.to_owned())
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
Some(200)
|
|
||||||
}
|
|
||||||
Method::Get => {
|
|
||||||
let disp = format!("attachment; filename=\"{filename}\"");
|
|
||||||
conn.initiate_response(
|
|
||||||
200,
|
|
||||||
Some("OK"),
|
|
||||||
&[
|
|
||||||
("Content-Type", "application/octet-stream"),
|
|
||||||
("Content-Disposition", disp.as_str()),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
let mut chunk = 0;
|
|
||||||
loop {
|
|
||||||
let read_chunk = board
|
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.get_file(filename.to_owned(), chunk)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let length = read_chunk.1;
|
|
||||||
info!("read {} bytes for file request for {}", length, filename);
|
|
||||||
if length == 0 {
|
|
||||||
info!("file request for {} finished", filename);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let data = &read_chunk.0[0..length];
|
|
||||||
conn.write_all(data).await?;
|
|
||||||
if length < 128 {
|
|
||||||
info!("file request for {} finished", filename);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
chunk = chunk + 1;
|
|
||||||
}
|
|
||||||
Some(200)
|
|
||||||
}
|
|
||||||
Method::Post => {
|
|
||||||
//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;
|
|
||||||
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 {
|
|
||||||
info!(
|
|
||||||
"writing {} bytes for file request for {}",
|
|
||||||
to_write, filename
|
|
||||||
);
|
|
||||||
board
|
|
||||||
.board_hal
|
|
||||||
.get_esp()
|
|
||||||
.write_file(filename.to_owned(), offset as u32, &buf[0..to_write])
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
offset = offset + to_write
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(200)
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
match method {
|
match method {
|
||||||
Method::Get => match path {
|
Method::Get => match path {
|
||||||
"/favicon.ico" => {
|
"/favicon.ico" => serve_favicon(conn).await?,
|
||||||
conn.initiate_response(
|
"/" => serve_index(conn).await?,
|
||||||
200,
|
"/bundle.js" => serve_bundle(conn).await?,
|
||||||
Some("OK"),
|
"/log" => get_log(conn).await?,
|
||||||
&[("Content-Type", "image/x-icon")],
|
"/get_backup_config" => get_backup_config(conn).await?,
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
conn.write_all(include_bytes!("favicon.ico")).await?;
|
|
||||||
Some(200)
|
|
||||||
}
|
|
||||||
"/" => {
|
|
||||||
conn.initiate_response(200, Some("OK"), &[("Content-Type", "text/html")])
|
|
||||||
.await?;
|
|
||||||
conn.write_all(include_bytes!("index.html")).await?;
|
|
||||||
Some(200)
|
|
||||||
}
|
|
||||||
"/bundle.js" => {
|
|
||||||
conn.initiate_response(
|
|
||||||
200,
|
|
||||||
Some("OK"),
|
|
||||||
&[("Content-Type", "text/javascript")],
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
conn.write_all(include_bytes!("bundle.js")).await?;
|
|
||||||
Some(200)
|
|
||||||
}
|
|
||||||
"/log" => {
|
|
||||||
let buf = get_log(conn).await;
|
|
||||||
Some(200)
|
|
||||||
},
|
|
||||||
&_ => {
|
&_ => {
|
||||||
let json = match path {
|
let json = match path {
|
||||||
"/version" => Some(get_version_web(conn).await),
|
"/version" => Some(get_version_web(conn).await),
|
||||||
@@ -425,7 +124,10 @@ impl Handler for HttpHandler {
|
|||||||
"/get_config" => Some(get_config(conn).await),
|
"/get_config" => Some(get_config(conn).await),
|
||||||
"/files" => Some(list_files(conn).await),
|
"/files" => Some(list_files(conn).await),
|
||||||
"/log_localization" => Some(get_log_localization_config(conn).await),
|
"/log_localization" => Some(get_log_localization_config(conn).await),
|
||||||
"/wifiscan" => Some(wifi_scan(conn).await),
|
"/tank" => Some(tank_info(conn).await),
|
||||||
|
"/backup_info" => Some(backup_info(conn).await),
|
||||||
|
"/timezones" => Some(get_timezones().await),
|
||||||
|
"/moisture" => Some(get_live_moisture(conn).await),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
match json {
|
match json {
|
||||||
@@ -439,12 +141,22 @@ impl Handler for HttpHandler {
|
|||||||
"/wifiscan" => Some(wifi_scan(conn).await),
|
"/wifiscan" => Some(wifi_scan(conn).await),
|
||||||
"/set_config" => Some(set_config(conn).await),
|
"/set_config" => Some(set_config(conn).await),
|
||||||
"/time" => Some(write_time(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().await),
|
||||||
"/reboot" => {
|
"/reboot" => {
|
||||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||||
board.board_hal.get_esp().set_restart_to_conf(true);
|
board.board_hal.get_esp().set_restart_to_conf(true);
|
||||||
self.reboot_now.store(true, Ordering::Relaxed);
|
self.reboot_now.store(true, Ordering::Relaxed);
|
||||||
Some(Ok(None))
|
Some(Ok(None))
|
||||||
}
|
}
|
||||||
|
"/exit" => {
|
||||||
|
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||||
|
board.board_hal.get_esp().set_restart_to_conf(false);
|
||||||
|
self.reboot_now.store(true, Ordering::Relaxed);
|
||||||
|
Some(Ok(None))
|
||||||
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
match json {
|
match json {
|
||||||
@@ -472,123 +184,10 @@ impl Handler for HttpHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// .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;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// log::info!("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();
|
|
||||||
// log::info!("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();
|
|
||||||
// log::info!("error handling get file {}", error_text);
|
|
||||||
// cors_response(request, 500, &error_text)?;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// drop(board);
|
|
||||||
// anyhow::Ok(())
|
|
||||||
// })
|
|
||||||
// .unwrap();
|
|
||||||
|
|
||||||
async fn write_time<T, const N: usize>(
|
|
||||||
request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error>
|
|
||||||
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;
|
|
||||||
anyhow::Ok(None)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async fn set_config<T, const N: usize>(
|
|
||||||
request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error>
|
|
||||||
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);
|
|
||||||
anyhow::Ok(Some("saved".to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn read_up_to_bytes_from_request<T, const N: usize>(
|
async fn read_up_to_bytes_from_request<T, const N: usize>(
|
||||||
request: &mut Connection<'_, T, N>,
|
request: &mut Connection<'_, T, N>,
|
||||||
limit: Option<usize>,
|
limit: Option<usize>,
|
||||||
) -> Result<Vec<u8>, anyhow::Error>
|
) -> FatResult<Vec<u8>>
|
||||||
where
|
where
|
||||||
T: Read + Write,
|
T: Read + Write,
|
||||||
{
|
{
|
||||||
@@ -597,10 +196,7 @@ where
|
|||||||
let mut total_read = 0;
|
let mut total_read = 0;
|
||||||
loop {
|
loop {
|
||||||
let mut buf = [0_u8; 64];
|
let mut buf = [0_u8; 64];
|
||||||
let read = match request.read(&mut buf).await {
|
let read = request.read(&mut buf).await?;
|
||||||
Ok(read) => read,
|
|
||||||
Err(e) => bail!("Error reading request {:?}", e),
|
|
||||||
};
|
|
||||||
if read == 0 {
|
if read == 0 {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -611,343 +207,36 @@ where
|
|||||||
}
|
}
|
||||||
data_store.push(actual_data.to_owned());
|
data_store.push(actual_data.to_owned());
|
||||||
}
|
}
|
||||||
let allvec = data_store.concat();
|
let final_buffer = data_store.concat();
|
||||||
log::info!("Raw data {}", from_utf8(&allvec)?);
|
Ok(final_buffer)
|
||||||
Ok(allvec)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn wifi_scan<T, const N: usize>(
|
|
||||||
_request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error> {
|
|
||||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
|
||||||
info!("start wifi scan");
|
|
||||||
//let scan_result = board.board_hal.get_esp().wifi_scan().await?
|
|
||||||
//FIXME currently panics
|
|
||||||
let mut ssids: Vec<String> = Vec::new();
|
|
||||||
//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);
|
|
||||||
anyhow::Ok(Some(ssid_json))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_log<T, const N: usize>(
|
|
||||||
conn: &mut Connection<'_, T, N>,
|
|
||||||
) -> anyhow::Result<()>
|
|
||||||
where
|
|
||||||
T: Read + Write,{
|
|
||||||
let log = LOG_ACCESS.lock().await.get();
|
|
||||||
conn.initiate_response(
|
|
||||||
200,
|
|
||||||
Some("OK"),
|
|
||||||
&[("Content-Type", "text/javascript")],
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
conn.write_all("[".as_bytes()).await.unwrap();
|
|
||||||
let mut append = false;
|
|
||||||
for entry in log {
|
|
||||||
if append {
|
|
||||||
conn.write_all(",".as_bytes()).await.unwrap();
|
|
||||||
}
|
|
||||||
append = true;
|
|
||||||
let json = serde_json::to_string(&entry)?;
|
|
||||||
conn.write_all(json.as_bytes()).await.unwrap();
|
|
||||||
}
|
|
||||||
conn.write_all("]".as_bytes()).await.unwrap();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_log_localization_config<T, const N: usize>(
|
|
||||||
_request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error> {
|
|
||||||
anyhow::Ok(Some(serde_json::to_string(
|
|
||||||
&LogMessage::to_log_localisation_config(),
|
|
||||||
)?))
|
|
||||||
}
|
|
||||||
async fn list_files<T, const N: usize>(
|
|
||||||
_request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error> {
|
|
||||||
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)?;
|
|
||||||
anyhow::Ok(Some(file_list_json))
|
|
||||||
}
|
|
||||||
async fn get_config<T, const N: usize>(
|
|
||||||
_request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error> {
|
|
||||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
|
||||||
let json = serde_json::to_string(&board.board_hal.get_config())?;
|
|
||||||
anyhow::Ok(Some(json))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_solar_state<T, const N: usize>(
|
|
||||||
_request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error> {
|
|
||||||
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(),
|
|
||||||
};
|
|
||||||
anyhow::Ok(Some(serde_json::to_string(&state)?))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_battery_state<T, const N: usize>(
|
|
||||||
_request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error> {
|
|
||||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
|
||||||
let battery_state = board
|
|
||||||
.board_hal
|
|
||||||
.get_battery_monitor()
|
|
||||||
.get_battery_state()
|
|
||||||
.await?;
|
|
||||||
anyhow::Ok(Some(serde_json::to_string(&battery_state)?))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_version_web<T, const N: usize>(
|
|
||||||
_request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error> {
|
|
||||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
|
||||||
anyhow::Ok(Some(serde_json::to_string(&get_version(&mut board).await)?))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_time<T, const N: usize>(
|
|
||||||
_request: &mut Connection<'_, T, N>,
|
|
||||||
) -> Result<Option<String>, anyhow::Error> {
|
|
||||||
let mut board = BOARD_ACCESS.get().await.lock().await;
|
|
||||||
//TODO do not fail if rtc module is missing
|
|
||||||
let native = esp_time().await.to_rfc3339();
|
|
||||||
let rtc = "todo";
|
|
||||||
// board
|
|
||||||
// .board_hal
|
|
||||||
// .get_rtc_module()
|
|
||||||
// .get_rtc_time()
|
|
||||||
// .await?
|
|
||||||
// .to_rfc3339();
|
|
||||||
|
|
||||||
let data = LoadData {
|
|
||||||
rtc,
|
|
||||||
native: native.as_str(),
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string(&data)?;
|
|
||||||
|
|
||||||
anyhow::Ok(Some(json))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
pub async fn httpd(reboot_now: Arc<AtomicBool>, stack: Stack<'static>) {
|
pub async fn http_server(reboot_now: Arc<AtomicBool>, stack: Stack<'static>) {
|
||||||
let buffer: TcpBuffers<2, 1024, 1024> = TcpBuffers::new();
|
let buffer: TcpBuffers<2, 1024, 1024> = TcpBuffers::new();
|
||||||
let tcp = Tcp::new(stack, &buffer);
|
let tcp = Tcp::new(stack, &buffer);
|
||||||
let acceptor = tcp
|
let acceptor = tcp
|
||||||
.bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 80))
|
.bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 80))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let mut server: Server<2, 512, 15> = Server::new();
|
let mut server: Server<2, 512, 15> = Server::new();
|
||||||
server
|
server
|
||||||
.run(Some(5000), acceptor, HttpHandler { reboot_now })
|
.run(Some(5000), acceptor, HTTPRequestRouter { reboot_now })
|
||||||
.await
|
.await
|
||||||
.expect("TODO: panic message");
|
.expect("Tcp stack error");
|
||||||
println!("Wait for connection...");
|
info!("Webserver started and waiting for connections");
|
||||||
|
|
||||||
// let server_config = Configuration {
|
//TODO https if mbed_esp lands
|
||||||
// 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("/solar", Method::Get, |request| {
|
|
||||||
// handle_error_to500(request, get_solar_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("/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
|
|
||||||
|
|
||||||
//
|
|
||||||
// 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
|
|
||||||
}
|
}
|
||||||
//
|
|
||||||
|
|
||||||
async fn handle_json<'a, T, const N: usize>(
|
async fn handle_json<'a, T, const N: usize>(
|
||||||
conn: &mut Connection<'a, T, N>,
|
conn: &mut Connection<'a, T, N>,
|
||||||
chain: anyhow::Result<Option<String>>,
|
chain: FatResult<Option<String>>,
|
||||||
) -> anyhow::Result<u32, Error<T::Error>>
|
) -> FatResult<u32>
|
||||||
where
|
where
|
||||||
T: Read + Write,
|
T: Read + Write,
|
||||||
<T as embedded_io_async::ErrorType>::Error: Debug,
|
<T as edge_nal::io::ErrorType>::Error: Debug,
|
||||||
{
|
{
|
||||||
match chain {
|
match chain {
|
||||||
Ok(answer) => match answer {
|
Ok(answer) => match answer {
|
||||||
|
|||||||
114
rust/src/webserver/post_json.rs
Normal file
114
rust/src/webserver/post_json.rs
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
use crate::config::PlantControllerConfig;
|
||||||
|
use crate::fat_error::FatResult;
|
||||||
|
use crate::webserver::read_up_to_bytes_from_request;
|
||||||
|
use crate::{do_secure_pump, BOARD_ACCESS};
|
||||||
|
use alloc::borrow::ToOwned;
|
||||||
|
use alloc::string::{String, ToString};
|
||||||
|
use alloc::vec::Vec;
|
||||||
|
use chrono::DateTime;
|
||||||
|
use edge_http::io::server::Connection;
|
||||||
|
use edge_nal::io::{Read, Write};
|
||||||
|
use esp_radio::wifi::ap::AccessPointInfo;
|
||||||
|
use log::info;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct NightLampCommand {
|
||||||
|
active: bool,
|
||||||
|
}
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
struct SSIDList {
|
||||||
|
ssids: Vec<String>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Debug)]
|
||||||
|
struct SetTime<'a> {
|
||||||
|
time: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
|
||||||
|
pub struct TestPump {
|
||||||
|
pump: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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: Vec<AccessPointInfo> = board.board_hal.get_esp().wifi_scan().await?;
|
||||||
|
scan_result
|
||||||
|
.iter()
|
||||||
|
.for_each(|s| ssids.push(s.ssid.as_str().to_owned()));
|
||||||
|
let ssid_json = serde_json::to_string(&SSIDList { ssids })?;
|
||||||
|
info!("Sending ssid list {}", &ssid_json);
|
||||||
|
Ok(Some(ssid_json))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn board_test() -> FatResult<Option<String>> {
|
||||||
|
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||||
|
board.board_hal.test().await?;
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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?)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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)?;
|
||||||
|
let mut board = BOARD_ACCESS.get().await.lock().await;
|
||||||
|
board.board_hal.set_time(&parsed).await?;
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) 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?;
|
||||||
|
info!("Wrote config config {:?} with size {}", config, length);
|
||||||
|
board.board_hal.set_config(config);
|
||||||
|
Ok(Some("saved".to_string()))
|
||||||
|
}
|
||||||
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": {
|
"devDependencies": {
|
||||||
|
"compression-webpack-plugin": "^11.1.0",
|
||||||
"html-webpack-harddisk-plugin": "^2.0.0",
|
"html-webpack-harddisk-plugin": "^2.0.0",
|
||||||
"html-webpack-plugin": "^5.6.3",
|
"html-webpack-plugin": "^5.6.3",
|
||||||
"raw-loader": "^4.0.2",
|
"raw-loader": "^4.0.2",
|
||||||
|
|||||||
@@ -69,45 +69,44 @@ export class Controller {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getBackupInfo(): Promise<void> {
|
async getBackupInfo(): Promise<void> {
|
||||||
return fetch(PUBLIC_URL + "/backup_info")
|
try {
|
||||||
.then(response => response.json())
|
const response = await fetch(PUBLIC_URL + "/backup_info");
|
||||||
.then(json => json as BackupHeader)
|
const json = await response.json();
|
||||||
.then(header => {
|
const header = json as BackupHeader;
|
||||||
controller.submitView.setBackupInfo(header)
|
controller.submitView.setBackupInfo(header);
|
||||||
})
|
} catch (error) {
|
||||||
.catch(error => {
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
populateTimezones(): Promise<void> {
|
async populateTimezones(): Promise<void> {
|
||||||
return fetch(PUBLIC_URL + '/timezones')
|
try {
|
||||||
.then(response => response.json())
|
const response = await fetch(PUBLIC_URL + '/timezones');
|
||||||
.then(json => json as string[])
|
const json = await response.json();
|
||||||
.then(timezones => {
|
const timezones = json as string[];
|
||||||
controller.timeView.timezones(timezones)
|
controller.timeView.timezones(timezones);
|
||||||
})
|
} catch (error) {
|
||||||
.catch(error => console.error('Error fetching timezones:', error));
|
return console.error('Error fetching timezones:', error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
updateFileList(): Promise<void> {
|
async updateFileList(): Promise<void> {
|
||||||
return fetch(PUBLIC_URL + "/files")
|
try {
|
||||||
.then(response => response.json())
|
const response = await fetch(PUBLIC_URL + "/files");
|
||||||
.then(json => json as FileList)
|
const json = await response.json();
|
||||||
.then(filelist => {
|
const filelist = json as FileList;
|
||||||
controller.fileview.setFileList(filelist, PUBLIC_URL)
|
controller.fileview.setFileList(filelist, PUBLIC_URL);
|
||||||
})
|
} catch (error) {
|
||||||
.catch(error => {
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
uploadFile(file: File, name: string) {
|
uploadFile(file: File, name: string) {
|
||||||
var current = 0;
|
let current = 0;
|
||||||
var max = 100;
|
let max = 100;
|
||||||
controller.progressview.addProgress("file_upload", (current / max) * 100, "Uploading File " + name + "(" + current + "/" + max + ")")
|
controller.progressview.addProgress("file_upload", (current / max) * 100, "Uploading File " + name + "(" + current + "/" + max + ")")
|
||||||
var ajax = new XMLHttpRequest();
|
const ajax = new XMLHttpRequest();
|
||||||
ajax.upload.addEventListener("progress", event => {
|
ajax.upload.addEventListener("progress", event => {
|
||||||
current = event.loaded / 1000;
|
current = event.loaded / 1000;
|
||||||
max = event.total / 1000;
|
max = event.total / 1000;
|
||||||
@@ -133,7 +132,7 @@ export class Controller {
|
|||||||
|
|
||||||
deleteFile(name: string) {
|
deleteFile(name: string) {
|
||||||
controller.progressview.addIndeterminate("file_delete", "Deleting " + name);
|
controller.progressview.addIndeterminate("file_delete", "Deleting " + name);
|
||||||
var ajax = new XMLHttpRequest();
|
const ajax = new XMLHttpRequest();
|
||||||
ajax.open("DELETE", PUBLIC_URL + "/file?filename=" + name);
|
ajax.open("DELETE", PUBLIC_URL + "/file?filename=" + name);
|
||||||
ajax.send();
|
ajax.send();
|
||||||
ajax.addEventListener("error", () => {
|
ajax.addEventListener("error", () => {
|
||||||
@@ -153,50 +152,47 @@ export class Controller {
|
|||||||
controller.updateFileList()
|
controller.updateFileList()
|
||||||
}
|
}
|
||||||
|
|
||||||
updateRTCData(): Promise<void> {
|
async updateRTCData(): Promise<void> {
|
||||||
return fetch(PUBLIC_URL + "/time")
|
try {
|
||||||
.then(response => response.json())
|
const response = await fetch(PUBLIC_URL + "/time");
|
||||||
.then(json => json as GetTime)
|
const json = await response.json();
|
||||||
.then(time => {
|
const time = json as GetTime;
|
||||||
controller.timeView.update(time.native, time.rtc)
|
controller.timeView.update(time.native, time.rtc);
|
||||||
})
|
} catch (error) {
|
||||||
.catch(error => {
|
controller.timeView.update("n/a", "n/a");
|
||||||
controller.timeView.update("n/a", "n/a")
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
updateBatteryData(): Promise<void> {
|
async updateBatteryData(): Promise<void> {
|
||||||
return fetch(PUBLIC_URL + "/battery")
|
try {
|
||||||
.then(response => response.json())
|
const response = await fetch(PUBLIC_URL + "/battery");
|
||||||
.then(json => json as BatteryState)
|
const json = await response.json();
|
||||||
.then(battery => {
|
const battery = json as BatteryState;
|
||||||
controller.batteryView.update(battery)
|
controller.batteryView.update(battery);
|
||||||
})
|
} catch (error) {
|
||||||
.catch(error => {
|
controller.batteryView.update(null);
|
||||||
controller.batteryView.update(null)
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
updateSolarData(): Promise<void> {
|
async updateSolarData(): Promise<void> {
|
||||||
return fetch(PUBLIC_URL + "/solar")
|
try {
|
||||||
.then(response => response.json())
|
const response = await fetch(PUBLIC_URL + "/solar");
|
||||||
.then(json => json as SolarState)
|
const json = await response.json();
|
||||||
.then(solar => {
|
const solar = json as SolarState;
|
||||||
controller.solarView.update(solar)
|
controller.solarView.update(solar);
|
||||||
})
|
} catch (error) {
|
||||||
.catch(error => {
|
controller.solarView.update(null);
|
||||||
controller.solarView.update(null)
|
|
||||||
console.log(error);
|
console.log(error);
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
uploadNewFirmware(file: File) {
|
uploadNewFirmware(file: File) {
|
||||||
var current = 0;
|
let current = 0;
|
||||||
var max = 100;
|
let max = 100;
|
||||||
controller.progressview.addProgress("ota_upload", (current / max) * 100, "Uploading firmeware (" + current + "/" + max + ")")
|
controller.progressview.addProgress("ota_upload", (current / max) * 100, "Uploading firmeware (" + current + "/" + max + ")")
|
||||||
var ajax = new XMLHttpRequest();
|
const ajax = new XMLHttpRequest();
|
||||||
ajax.upload.addEventListener("progress", event => {
|
ajax.upload.addEventListener("progress", event => {
|
||||||
current = event.loaded / 1000;
|
current = event.loaded / 1000;
|
||||||
max = event.total / 1000;
|
max = event.total / 1000;
|
||||||
@@ -218,15 +214,13 @@ export class Controller {
|
|||||||
ajax.send(file);
|
ajax.send(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
version(): Promise<void> {
|
async version(): Promise<void> {
|
||||||
controller.progressview.addIndeterminate("version", "Getting buildVersion")
|
controller.progressview.addIndeterminate("version", "Getting buildVersion")
|
||||||
return fetch(PUBLIC_URL + "/version")
|
const response = await fetch(PUBLIC_URL + "/version");
|
||||||
.then(response => response.json())
|
const json = await response.json();
|
||||||
.then(json => json as VersionInfo)
|
const versionInfo = json as VersionInfo;
|
||||||
.then(versionInfo => {
|
controller.progressview.removeProgress("version");
|
||||||
controller.progressview.removeProgress("version")
|
|
||||||
controller.firmWareView.setVersion(versionInfo);
|
controller.firmWareView.setVersion(versionInfo);
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getBackupConfig() {
|
getBackupConfig() {
|
||||||
@@ -243,7 +237,7 @@ export class Controller {
|
|||||||
controller.progressview.addIndeterminate("get_config", "Downloading Config")
|
controller.progressview.addIndeterminate("get_config", "Downloading Config")
|
||||||
const response = await fetch(PUBLIC_URL + "/get_config");
|
const response = await fetch(PUBLIC_URL + "/get_config");
|
||||||
const loaded = await response.json();
|
const loaded = await response.json();
|
||||||
var currentConfig = loaded as PlantControllerConfig;
|
const currentConfig = loaded as PlantControllerConfig;
|
||||||
controller.setInitialConfig(currentConfig);
|
controller.setInitialConfig(currentConfig);
|
||||||
controller.setConfig(currentConfig);
|
controller.setConfig(currentConfig);
|
||||||
//sync json view initially
|
//sync json view initially
|
||||||
@@ -263,17 +257,18 @@ export class Controller {
|
|||||||
})
|
})
|
||||||
.then(response => response.text())
|
.then(response => response.text())
|
||||||
.then(text => statusCallback(text))
|
.then(text => statusCallback(text))
|
||||||
controller.progressview.removeProgress("set_config")
|
.then( _ => {
|
||||||
//load from remote to be clean
|
controller.progressview.removeProgress("set_config");
|
||||||
controller.downloadConfig()
|
setTimeout(() => { controller.downloadConfig() }, 250)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
backupConfig(json: string): Promise<string> {
|
async backupConfig(json: string): Promise<string> {
|
||||||
return fetch(PUBLIC_URL + "/backup_config", {
|
const response = await fetch(PUBLIC_URL + "/backup_config", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: json,
|
body: json,
|
||||||
})
|
});
|
||||||
.then(response => response.text());
|
return await response.text();
|
||||||
}
|
}
|
||||||
|
|
||||||
syncRTCFromBrowser() {
|
syncRTCFromBrowser() {
|
||||||
@@ -310,9 +305,9 @@ export class Controller {
|
|||||||
}
|
}
|
||||||
|
|
||||||
testNightLamp(active: boolean) {
|
testNightLamp(active: boolean) {
|
||||||
var body: NightLampCommand = {
|
const body: NightLampCommand = {
|
||||||
active: active
|
active: active
|
||||||
}
|
};
|
||||||
var pretty = JSON.stringify(body, undefined, 1);
|
var pretty = JSON.stringify(body, undefined, 1);
|
||||||
fetch(PUBLIC_URL + "/lamptest", {
|
fetch(PUBLIC_URL + "/lamptest", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ const path = require('path');
|
|||||||
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
const HtmlWebpackPlugin = require('html-webpack-plugin');
|
||||||
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
|
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
|
||||||
const CopyPlugin = require("copy-webpack-plugin");
|
const CopyPlugin = require("copy-webpack-plugin");
|
||||||
|
const CompressionPlugin = require("compression-webpack-plugin");
|
||||||
|
|
||||||
const isDevServer = process.env.WEBPACK_SERVE;
|
const isDevServer = process.env.WEBPACK_SERVE;
|
||||||
console.log("Dev server is " + isDevServer);
|
console.log("Dev server is " + isDevServer);
|
||||||
var host;
|
var host;
|
||||||
if (isDevServer){
|
if (isDevServer) {
|
||||||
//ensure no trailing /
|
//ensure no trailing /
|
||||||
host = 'http://10.23.44.186';
|
host = 'http://10.23.44.186';
|
||||||
} else {
|
} else {
|
||||||
@@ -30,6 +31,12 @@ module.exports = {
|
|||||||
title: "PlantCtrl",
|
title: "PlantCtrl",
|
||||||
}),
|
}),
|
||||||
new HtmlWebpackHarddiskPlugin(),
|
new HtmlWebpackHarddiskPlugin(),
|
||||||
|
new CompressionPlugin({
|
||||||
|
algorithm: "gzip",
|
||||||
|
test: /\.js$|\.css$|\.html$/,
|
||||||
|
threshold: 0,
|
||||||
|
minRatio: 0.8
|
||||||
|
})
|
||||||
],
|
],
|
||||||
module: {
|
module: {
|
||||||
rules: [
|
rules: [
|
||||||
@@ -51,6 +58,5 @@ module.exports = {
|
|||||||
filename: 'bundle.js',
|
filename: 'bundle.js',
|
||||||
path: path.resolve(__dirname, '.'),
|
path: path.resolve(__dirname, '.'),
|
||||||
},
|
},
|
||||||
devServer: {
|
devServer: {}
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user