Compare commits

..

6 Commits

Author SHA1 Message Date
CaCO3
59ccd601fc . 2023-05-03 22:36:07 +02:00
CaCO3
becbfc463f Merge branch 'add-websocket2' of https://github.com/jomjol/AI-on-the-edge-device into add-websocket2 2023-05-03 21:47:17 +02:00
CaCO3
a5d2086159 add example UI 2023-05-03 21:46:59 +02:00
CaCO3
716dcb5a84 add websocket support 2023-05-03 21:46:59 +02:00
CaCO3
a5c66eb014 add example UI 2023-04-30 22:47:09 +02:00
CaCO3
6c86317d52 add websocket support 2023-04-30 21:37:35 +02:00
356 changed files with 11073 additions and 22279 deletions

View File

@@ -3,32 +3,7 @@
# Make sure to also add the response to .github/workflows/reply-bot.yml!
# Due to the way it works, you have to add each response twice, once for the issue, once for the discussions!
labels:
#######################################################################
# Bot Response: Documentation
#######################################################################
- name: bot-reply Documentation
labeled:
issue:
body: |
Please have a look on our documentation: https://jomjol.github.io/AI-on-the-edge-device-docs
discussion:
body: |
Please have a look on our documentation: https://jomjol.github.io/AI-on-the-edge-device-docs
#######################################################################
# Bot Response: ROI setup
#######################################################################
- name: bot-reply ROI Setup
labeled:
issue:
body: |
Make sure to setup your ROIs properly. Have a look on our documentation: https://jomjol.github.io/AI-on-the-edge-device-docs/ROI-Configuration/#how-to-setup-the-digit-rois-perfectly
discussion:
body: |
Make sure to setup your ROIs properly. Have a look on our documentation: https://jomjol.github.io/AI-on-the-edge-device-docs/ROI-Configuration/#how-to-setup-the-digit-rois-perfectly
labels:
#######################################################################
# Bot Response: Logfile
#######################################################################
@@ -115,9 +90,9 @@
labeled:
issue:
body: |
See [Digits](https://jomjol.github.io/neural-network-digital-counter-readout) resp. [Analogue Pointers](https://jomjol.github.io/neural-network-analog-needle-readout) for an overview of all trained data.
See [Digital Digits](https://jomjol.github.io/neural-network-digital-counter-readout) resp. [Analogue Pointers](https://jomjol.github.io/neural-network-analog-needle-readout) for an overview of all trained data.
If your type is not contained it can be added to our training material, see [here](https://jomjol.github.io/AI-on-the-edge-device-docs/collect-new-images/).
discussion:
body: |
See [Digits](https://jomjol.github.io/neural-network-digital-counter-readout) resp. [Analogue Pointers](https://jomjol.github.io/neural-network-analog-needle-readout) for an overview of all trained data.
See [Digital Digits](https://jomjol.github.io/neural-network-digital-counter-readout) resp. [Analogue Pointers](https://jomjol.github.io/neural-network-analog-needle-readout) for an overview of all trained data.
If your type is not contained it can be added to our training material, see [here](https://jomjol.github.io/AI-on-the-edge-device-docs/collect-new-images/).

View File

@@ -14,8 +14,8 @@ jobs:
uses: fkirc/skip-duplicate-actions@v5
with:
concurrent_skipping: same_content_newer
- uses: actions/checkout@v4
- uses: actions/checkout@v3
with:
submodules: recursive
@@ -25,40 +25,39 @@ jobs:
echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
- name: Update PIP cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: ~/.cache/pip
key: pip-${{ github.run_id }}
restore-keys: pip # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Update PlatformIO cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: ~/.platformio
key: platformio-${{ github.run_id }}
restore-keys: platformio # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Update Build cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: ./code/.pio/
key: build-${{ github.run_id }}
restore-keys: build # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Update generated-files cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: |
./code/.pio/build/esp32cam/firmware.bin
./code/.pio/build/esp32cam/partitions.bin
./code/.pio/build/esp32cam/bootloader.bin
./html/*
./demo/*
key: generated-files-${{ github.run_id }}
restore-keys: generated-files # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v4
with:
python-version: '3.10'
@@ -71,7 +70,7 @@ jobs:
#run: echo "Testing... ${{ github.ref_name }}, ${{ steps.vars.outputs.sha_short }}" > ./sd-card/html/version.txt; mkdir -p ./code/.pio/build/esp32cam/; cd ./code/.pio/build/esp32cam/; echo "${{ steps.vars.outputs.sha_short }}" > firmware.bin; cp firmware.bin partitions.bin; cp firmware.bin bootloader.bin # Testing
run: cd code; platformio run --environment esp32cam
- name: Prepare Web UI (generate tooltip pages and update hashes in all files)
- name: Prepare Web UI (copy data from repo, generate tooltip pages and update hashes in all files)
run: |
rm -rf ./html
mkdir html
@@ -80,19 +79,14 @@ jobs:
python -m pip install markdown
mkdir html/param-tooltips
cd tools/parameter-tooltip-generator
python generate-param-doc-tooltips.py
bash generate-param-doc-tooltips.sh
cd ../..
cp -r ./sd-card/html/* ./html/
echo "Replacing variables..."
cd html; find . -type f -exec sed -i 's/$COMMIT_HASH/${{ steps.vars.outputs.sha_short }}/g' {} \;
- name: Prepare Demo mode files
run: |
rm -rf ./demo
mkdir demo
cp -r ./sd-card/demo/* ./demo/
#########################################################################################
## Pack for Update
@@ -103,32 +97,30 @@ jobs:
# - /firmware.bin
# - (optional) /html/* (inkl. subfolders)
# - (optional) /config/*.tfl
# - (optional) /demo/*
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Update generated-files cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: |
./code/.pio/build/esp32cam/firmware.bin
./code/.pio/build/esp32cam/partitions.bin
./code/.pio/build/esp32cam/bootloader.bin
./html/*
./demo/*
key: generated-files-${{ github.run_id }}
restore-keys: generated-files # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Update update cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: update
key: update-${{ github.run_id }}
restore-keys: update # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Set Variables
id: vars
run: |
@@ -143,9 +135,6 @@ jobs:
- name: Add Web UI to update
run: cp -r ./html ./update/
- name: Add Demo mode files to update
run: cp -r ./demo ./update/
- name: Add CNN to update
run: |
@@ -155,12 +144,13 @@ jobs:
cp ./sd-card/config/*.tflite ./update/config/ 2>/dev/null || true
- name: Upload update as update.zip artifact (Firmware + Web UI + CNN)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v3
with:
name: "AI-on-the-edge-device__update__${{ steps.vars.outputs.branch }}_(${{ steps.vars.outputs.sha_short }})"
path: ./update/*
#########################################################################################
## Pack for Remote Setup
#########################################################################################
@@ -169,28 +159,26 @@ jobs:
# remote_setup__version.zip file with following content:
# - /firmware.bin
# - /html/* (inkl. subfolders)
# - /demo/*
# - /config/*
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Update generated-files cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: |
./code/.pio/build/esp32cam/firmware.bin
./code/.pio/build/esp32cam/partitions.bin
./code/.pio/build/esp32cam/bootloader.bin
./html/*
./demo/*
key: generated-files-${{ github.run_id }}
restore-keys: generated-files # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Update remote_setup cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: remote_setup
key: remote_setup-${{ github.run_id }}
@@ -210,9 +198,6 @@ jobs:
- name: Add Web UI to remote_setup
run: cp -r ./html ./remote_setup/
- name: Add Demo mode files to update
run: cp -r ./demo ./update/
- name: Add whole config folder to remote_setup
run: |
rm -rf ./remote_setup/config/
@@ -220,7 +205,7 @@ jobs:
cp ./sd-card/config/* ./remote_setup/config/ 2>/dev/null || true
- name: Upload remote_setup as remote_setup.zip artifact (Firmware + Web UI + Config)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v3
with:
name: "AI-on-the-edge-device__remote-setup__${{ steps.vars.outputs.branch }}_(${{ steps.vars.outputs.sha_short }})"
path: ./remote_setup/*
@@ -235,22 +220,21 @@ jobs:
needs: build
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Update generated-files cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: |
./code/.pio/build/esp32cam/firmware.bin
./code/.pio/build/esp32cam/partitions.bin
./code/.pio/build/esp32cam/bootloader.bin
./html/*
./demo/*
key: generated-files-${{ github.run_id }}
restore-keys: generated-files # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Update manual_setup cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: manual_setup
key: manual_setup-${{ github.run_id }}
@@ -274,14 +258,12 @@ jobs:
cp -f "./code/.pio/build/esp32cam/bootloader.bin" "manual_setup/bootloader.bin"
cp -f "./code/.pio/build/esp32cam/partitions.bin" "manual_setup/partitions.bin"
rm -rf ./sd-card/html
rm -rf ./sd-card/demo
cp -r ./html ./sd-card/ # Overwrite the Web UI with the preprocessed files
cp -r ./demo ./sd-card/
cd sd-card; zip -r ../manual_setup/sd-card.zip *; cd ..
cd ./manual_setup
- name: Upload manual_setup.zip artifact (Firmware + Bootloader + Partitions + Web UI)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v3
with:
name: "AI-on-the-edge-device__manual-setup__${{ steps.vars.outputs.branch }}_(${{ steps.vars.outputs.sha_short }})"
path: ./manual_setup
@@ -290,7 +272,7 @@ jobs:
#########################################################################################
## Prepare and create release
#########################################################################################
prepare-release:
release:
runs-on: ubuntu-latest
needs: [pack-for-update, pack-for-manual_setup, pack-for-remote_setup]
if: startsWith(github.ref, 'refs/tags/')
@@ -302,24 +284,24 @@ jobs:
id-token: write
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
- name: Update update cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: update
key: update-${{ github.run_id }}
restore-keys: update # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Update remote_setup cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: remote_setup
key: remote_setup-${{ github.run_id }}
restore-keys: remote_setup # This matches above key as it is only used as a prefix. it the restores the nearest cache, see https://github.com/restore-keys:/blob/main/tips-and-workarounds.md#update-a-cache
- name: Update manual_setup cache on every commit
uses: actions/cache@v4
uses: actions/cache@v3.2.3
with:
path: manual_setup
key: manual_setup-${{ github.run_id }}
@@ -350,18 +332,21 @@ jobs:
# extract the version used in next step
- id: get_version
uses: drewg13/get-version-action@98dda2a47a257e202c2e6c2ed2e6072ec23f448e
if: startsWith(github.ref, 'refs/tags/')
uses: Simply007/get-version-action@v2
# # the changelog [unreleased] will now be changed to the release version
# - name: Update changelog
# uses: thomaseizinger/keep-a-changelog-new-release@v1
# if: startsWith(github.ref, 'refs/tags/')
# with:
# changelogPath: Changelog.md
# version: ${{ steps.get_version.outputs.version-without-v }}
# # the release notes will be extracted from changelog
# - name: Extract release notes
# id: extract-release-notes
# if: startsWith(github.ref, 'refs/tags/')
# uses: ffurrer2/extract-release-notes@v1
# with:
# changelog_file: Changelog.md
@@ -369,11 +354,12 @@ jobs:
# Releases should only be created on master by tagging the last commit.
# all artifacts in firmware folder pushed to the release
- name: Release
uses: softprops/action-gh-release@v2.0.8
uses: softprops/action-gh-release@v1
# Note:
# If you get the error "Resource not accessible by integration",
# The access rights are not sufficient, see
# https://github.com/softprops/action-gh-release/issues/232#issuecomment-1131379440
if: startsWith(github.ref, 'refs/tags/')
with:
name: ${{ steps.get_version.outputs.version-without-v }}
body: ${{ steps.extract-release-notes.outputs.release_notes }}
@@ -382,6 +368,7 @@ jobs:
# # Commit&Push Changelog to master branch. Must be manually merged back to rolling
# - name: Commit changes and push changes
# if: startsWith(github.ref, 'refs/tags/')
# run: |
# git config user.name github-actions
# git config user.email github-actions@github.com
@@ -393,10 +380,9 @@ jobs:
#########################################################################################
## Update the Web Installer on a release
#########################################################################################
# Make sure to also update update-webinstaller.yml!
update-web-installer:
if: github.event_name == 'release' && github.event.action == 'published' # Only run on release but not on prerelease
needs: [prepare-release]
# This is the same as in the update-webinstaller.yml
update-web-installer:
needs: [release]
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
@@ -410,8 +396,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Get version of last release
id: last_release
uses: mindojo/get-latest-release@0b8ef1434d7468d6bffcc8263baff5c777f72321
@@ -419,26 +405,23 @@ jobs:
myToken: ${{ github.token }}
exclude_types: "draft|prerelease"
view_top: 1
- name: Add binary to Web Installer and update manifest
run: |
echo "Updating Web installer to use firmware from ${{ steps.last_release.outputs.tag_name }}..."
rm -f docs/binary/firmware.bin
wget ${{ github.server_url }}/${{ github.repository }}/releases/download/${{ steps.last_release.outputs.tag_name }}/AI-on-the-edge-device__update__${{ steps.last_release.outputs.tag_name }}.zip
wget https://github.com/jomjol/AI-on-the-edge-device/releases/download/${{ steps.last_release.outputs.tag_name }}/AI-on-the-edge-device__update__${{ steps.last_release.outputs.tag_name }}.zip
unzip AI-on-the-edge-device__update__${{ steps.last_release.outputs.tag_name }}.zip
cp -f firmware.bin docs/binary/firmware.bin
echo "Updating index and manifest file..."
sed -i 's/$VERSION/${{ steps.last_release.outputs.tag_name }}/g' docs/index.html
sed -i 's/$VERSION/${{ steps.last_release.outputs.tag_name }}/g' docs/manifest.json
cp -f docs/manifest_template.json docs/manifest.json
sed -i 's/VERSION/${{ steps.last_release.outputs.tag_name }}/g' docs/manifest.json
- name: Setup Pages
uses: actions/configure-pages@v4
uses: actions/configure-pages@v2
- name: Upload artifact
uses: actions/upload-pages-artifact@v2
uses: actions/upload-pages-artifact@v1
with:
path: 'docs'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v3 # Note: v4 does not work!
uses: actions/deploy-pages@v1

View File

@@ -1,21 +0,0 @@
# This updates the Contributors list in the README.md
# it only gets run on:
# - Manually triggered
name: Manually update contributors list
on:
workflow_dispatch: # Run on manual trigger
jobs:
manually-update-contributors-list:
runs-on: ubuntu-latest
name: A job to automatically update the contributors list in the README.md
permissions:
contents: write
pull-requests: write
steps:
- name: Contribute List
uses: akhilmhdh/contributors-readme-action@v2.3.10
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,7 +1,7 @@
# This updates the Web Installer with the files from the docs folder and the binary of the latest release
# it only gets run on:
# - Manually triggered
# Make sure to also update the lower part of build.yml!
# - Changes to the docs folder in the `rolling` branch
# - On a release
name: Manual Web Installer Update
@@ -12,7 +12,7 @@ on:
# - rolling
# paths:
# - docs # The path filter somehow does not work, so lets run it on every change to rolling
jobs:
manually-update-web-installer:
environment:
@@ -29,7 +29,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Get version of last release
id: last_release
uses: mindojo/get-latest-release@0b8ef1434d7468d6bffcc8263baff5c777f72321
@@ -37,17 +37,15 @@ jobs:
myToken: ${{ github.token }}
exclude_types: "draft|prerelease"
view_top: 1
- name: Add binary to Web Installer and update manifest
run: |
echo "Updating Web installer to use firmware from ${{ steps.last_release.outputs.tag_name }}..."
rm -f docs/binary/firmware.bin
wget https://github.com/jomjol/AI-on-the-edge-device/releases/download/${{ steps.last_release.outputs.tag_name }}/AI-on-the-edge-device__update__${{ steps.last_release.outputs.tag_name }}.zip
unzip AI-on-the-edge-device__update__${{ steps.last_release.outputs.tag_name }}.zip
cp -f firmware.bin docs/binary/firmware.bin
echo "Updating index and manifest file..."
sed -i 's/$VERSION/${{ steps.last_release.outputs.tag_name }}/g' docs/index.html
sed -i 's/$VERSION/${{ steps.last_release.outputs.tag_name }}/g' docs/manifest.json
cp -f docs/manifest_template.json docs/manifest.json
sed -i 's/VERSION/${{ steps.last_release.outputs.tag_name }}/g' docs/manifest.json
- name: Setup Pages
uses: actions/configure-pages@v2
@@ -60,3 +58,4 @@ jobs:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v1

View File

@@ -1,5 +1,5 @@
# Reply Bot
# It uses the configuration in .github/label-commenter-config.yaml
# It uses the configuration in .github/label-commenter-config.yml
# See https://github.com/peaceiris/actions-label-commenter
name: Reply-Bot
@@ -20,11 +20,12 @@ jobs:
comment:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v3
####################################################################
## Remove labels again (issues only)
## Make sure to also add the reply message to .github/label-commenter-config.yaml!
## Make sure to also add the reply message to .github/label-commenter-config.yml!
## This currently seems no longer to work due to changes on the actions-cool/issues-helper!
####################################################################
# - name: Remove 'Logfile' label again (issues only)
@@ -68,12 +69,11 @@ jobs:
# with:
# actions: 'remove-labels'
# labels: 'bot-reply Show Trained Digits/Pointers'
####################################################################
## Write the response
####################################################################
- name: Write Response
uses: peaceiris/actions-label-commenter@c2d00660c86f2b9ed0fb35b372c451558eba85b3
with:
github_token: "${{ secrets.GITHUB_TOKEN }}"
config_file: .github/label-commenter-config.yaml
repo-token: "${{ secrets.GITHUB_TOKEN }}"

9
.gitmodules vendored
View File

@@ -4,12 +4,9 @@
[submodule "code/components/esp-nn"]
path = code/components/esp-nn
url = https://github.com/espressif/esp-nn.git
[submodule "code/components/esp-tflite-micro"]
path = code/components/esp-tflite-micro
url = https://github.com/espressif/esp-tflite-micro.git
[submodule "code/components/tflite-micro-esp-examples"]
path = code/components/tflite-micro-esp-examples
url = https://github.com/espressif/tflite-micro-esp-examples.git
[submodule "code/components/stb"]
path = code/components/stb
url = https://github.com/nothings/stb.git
[submodule "code/esp-protocols"]
path = code/esp-protocols
url = https://github.com/espressif/esp-protocols.git

View File

@@ -1,224 +1,7 @@
## [16.0.0-RC6] - 2024-xx-xx
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.7.0...v16.0.0)
#### Known issues
Please check the [issues](https://github.com/jomjol/AI-on-the-edge-device/issues) and
[discussions](https://github.com/jomjol/AI-on-the-edge-device/discussions) before reporting a new issue.
#### Core Changes
Only changes since RC5 are listed:
- [#3436](https://github.com/jomjol/AI-on-the-edge-device/pull/3436) Added basic authentification of the Web Interface and the REST API, see https://jomjol.github.io/AI-on-the-edge-device-docs/Password-Protection
- xxx
**:warning: Please check your Homeassistant instance to make sure it is handled correctly!**
#### Bug Fixes
Only changes since RC5 are listed:
- xxx
## [16.0.0-RC5] - 2024-12-05
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.7.0...v16.0.0)
#### Known issues
Please check the [issues](https://github.com/jomjol/AI-on-the-edge-device/issues) and
[discussions](https://github.com/jomjol/AI-on-the-edge-device/discussions) before reporting a new issue.
#### Core Changes
Only changes since RC4 are listed:
- [#3423](https://github.com/jomjol/AI-on-the-edge-device/pull/3423) Removed `Autostart` parameter and make the flow to be always enabled
- [#3423](https://github.com/jomjol/AI-on-the-edge-device/pull/3423) Enable `Flow start` menu entry in UI
- [#3332](https://github.com/jomjol/AI-on-the-edge-device/pull/3332) Updated the Homeassistant Discovery topics :
- `raw` has now set the `State Class` to `measurement`. Before it was always set to `""`.
- `value` has now only set the `State Class` to `total_increasing` if the parameter `Allow Negative Rates` is **not** set. Else it uses `measurement` since the rate could also be negative. Before it was always set to `total_increasing`.
- The `rate_per_time_unit` topic of an **Energy** meter needs a `Device Class`=`power`. For `gas` and `water` it should be `volume_flow_rate`. Before it was always set to `""`.
- [#3415](https://github.com/jomjol/AI-on-the-edge-device/pull/3415) Added button for `flow start`
- [#3359](https://github.com/jomjol/AI-on-the-edge-device/pull/3359) Added support for Domoticz MQTT integration
- Added Date and time to overview page
- Updated submodules and models
**:warning: Please check your Homeassistant instance to make sure it is handled correctly!**
#### Bug Fixes
Only changes since RC4 are listed:
- [#3418](https://github.com/jomjol/AI-on-the-edge-device/pull/3418) Added fix for ledintensity
- [#3417](https://github.com/jomjol/AI-on-the-edge-device/pull/3417) Added fix for OV2640 brightness contrast saturation
- [#3393](https://github.com/jomjol/AI-on-the-edge-device/pull/3393) Added fix for 'AnalogToDigitTransitionStart' always using 9.2 regardless of the configured value
- [#3342](https://github.com/jomjol/AI-on-the-edge-device/pull/3342) Added fix for HA menu entry
## [16.0.0-RC4] - 2024-10-06
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.7.0...v16.0.0-RC1)
#### Known issues
Please check the [issues](https://github.com/jomjol/AI-on-the-edge-device/issues) and
[discussions](https://github.com/jomjol/AI-on-the-edge-device/discussions) before reporting a new issue.
#### Core Changes
Only changes since RC3 are listed:
- [#3316](https://github.com/jomjol/AI-on-the-edge-device/pull/3316) Update esp32-camera submodule to `v2.0.13`
- [#3317](https://github.com/jomjol/AI-on-the-edge-device/pull/3317) Added contributor list
- [#3315](https://github.com/jomjol/AI-on-the-edge-device/pull/3315) Added files for demo mode
#### Bug Fixes
Only changes since RC2 are listed:
- [#3313](https://github.com/jomjol/AI-on-the-edge-device/pull/3313) Added delay in InitCam to fix `Camera not detected` issues
## [16.0.0-RC3] - 2024-10-05
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.7.0...v16.0.0-RC1)
#### Known issues
Please check the [issues](https://github.com/jomjol/AI-on-the-edge-device/issues) and
[discussions](https://github.com/jomjol/AI-on-the-edge-device/discussions) before reporting a new issue.
#### Core Changes
Only changes since RC2 are listed:
- Renamed MQTT topic from `rate_per_digitalization_round` to `rate_per_digitization_round` (change happened already in RC1)
#### Bug Fixes
Only changes since RC2 are listed:
- [#3269](https://github.com/jomjol/AI-on-the-edge-device/pull/3269) Re-did revertion of TFlite submodule update as certain modules crash with it (change was lost)
## [16.0.0-RC2] - 2024-10-04
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.7.0...v16.0.0-RC1)
#### Known issues
Please check the [issues](https://github.com/jomjol/AI-on-the-edge-device/issues) and
[discussions](https://github.com/jomjol/AI-on-the-edge-device/discussions) before reporting a new issue.
#### Core Changes
Only changes since RC1 are listed:
- Updated parameter documentation pages
- [#3291](https://github.com/jomjol/AI-on-the-edge-device/pull/3291) Rename/remove unused parameters
- [#3288](https://github.com/jomjol/AI-on-the-edge-device/pull/3288) Migrate-cam-parameters
#### Bug Fixes
Only changes since RC1 are listed:
- [#3269](https://github.com/jomjol/AI-on-the-edge-device/pull/3269) Reverted TFlite submodule update as certain modules crash with it
- [#3279](https://github.com/jomjol/AI-on-the-edge-device/pull/3279) Changed the webhook UploadImg to false
- Changed default value from boolean to numeric value in parameter camDenoise documentation
- Updated config page
## [16.0.0-RC1] - 2024-09-24
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.7.0...v16.0.0-RC1)
#### Known issues
Please check the [issues](https://github.com/jomjol/AI-on-the-edge-device/issues) and
[discussions](https://github.com/jomjol/AI-on-the-edge-device/discussions) before reporting a new issue.
#### Core Changes
Those are just the major changes:
- [#3063](https://github.com/jomjol/AI-on-the-edge-device/pull/3063) Add support for OV5640 camera
- New tflite-Models
- [#3088](https://github.com/jomjol/AI-on-the-edge-device/pull/3088) Homeassistant service discovery: derive node_id when using nested topics
- [#3081](https://github.com/jomjol/AI-on-the-edge-device/pull/3081) Added Prometheus/OpenMetrics exporter
- [#3148](https://github.com/jomjol/AI-on-the-edge-device/pull/3148), [#3163](https://github.com/jomjol/AI-on-the-edge-device/pull/3163), [#3174](https://github.com/jomjol/AI-on-the-edge-device/pull/3148), [#3163](https://github.com/jomjol/AI-on-the-edge-device/pull/3163), [#3174](https://github.com/jomjol/AI-on-the-edge-device/pull/3174) Added Webhook
- [#3195](https://github.com/jomjol/AI-on-the-edge-device/pull/3195) Add rate threshold parameter
- [#3068](https://github.com/jomjol/AI-on-the-edge-device/pull/3068) Added a Delay between the WiFi reconnections
- Web UI improvements
- Various minor changes
- Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)
#### Bug Fixes
Those are just the major changes:
- [#3220](https://github.com/jomjol/AI-on-the-edge-device/pull/3220) Handle crash on corrupted model
- [#3175](https://github.com/jomjol/AI-on-the-edge-device/pull/3175) Bugfix for boot loop
- [#3180](https://github.com/jomjol/AI-on-the-edge-device/pull/3180) Bugfix for time stamp
- [#3162](https://github.com/jomjol/AI-on-the-edge-device/pull/3162) Handle empty prevalue.ini gracefully
- [#3213](https://github.com/jomjol/AI-on-the-edge-device/pull/3213) Added note about only TLS 1.2 is supported
## [15.7.0] - 2024-02-17
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.6.0...v15.7.0)
#### Core Changes
- Added new camera settings (See `Settings > Alignment > Reference Image and Camera Settings`). You might need to re-create the reference image and alignment marks. Note worthy:
- You can now crop the image
- Support to configure sharpness, grayscale, negatoive and exposure
- Enhanced various WebUI pages with better explanations and usability
- Add Firmware Version to MQTT
#### Bug Fixes
- Reverted "Implemented late analog / digit transition [#2778](https://github.com/jomjol/AI-on-the-edge-device/pull/2778) (introduced in `v15.5`) as is seems to cause issues for many users.
## [15.6.0] - 2024-02-09
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.5.0...v15.6.0)
#### Fixed
* Fixed issues with the SD-Card initialization
## [15.5.0] - 2024-02-02
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.4.0...v15.5.0)
#### Changed
- Update PlattformIO to v6.5.0, which means esp-idf to v5.1
- Enhance busy notification
- Implemented late analog / digit transition
#### Fixed
* ATA-TRIM: workaround for old SD-cards with no trim function to work with esp-idf v5.x
* InfluxDB: Modified the time conversions to be more stable (UTC vs. local time shifts)
* Fix negatives on extended resolution false
* Show chip infos on info page
* Fix memory leaks in tflite integration
## [15.4.0] - 2023-12-22
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.3.0...v15.4.0)
#### Changed
- Updates submodules (esp-nn, tflite-micro-example, esp-camera)
- Explicitly included needed tflite network layers (instead of all) , resulting in much smaller firmware size
- Added shortcut icon
- Rename in InfluxDB 'Database' to 'Bucket'
- Updated analog tflite files
- dig-class100-0167_s2_q.tflite
- dig-class11_1700_s2.tflite
- ana-cont_1208_s2_q.tflite
- Added config entries for MQTT TLS
#### Fixed
* InfluxDB: consider DST setting for UTC time conversion
* Minor html response bugfix
- Memory leakage (MQTT)
## [15.3.0] - 2023-07-22
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.3.0...v15.2.4)
#### Changed
- Updated PlatformIO to `6.3.2`
- Updated analog tflite files
- ana-cont_1207_s2_q.tflite
- dig-cont_0620_s3_q.tflite
## [15.2.4] - 2023-05-02
### Changes
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.2.1...v15.2.4)
#### Changed
@@ -242,6 +25,8 @@ For a full list of changes see [Full list of changes](https://github.com/jomjol/
## [15.2.0] - 2023-04-23
### Changes
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.1.1...v15.2.0)
#### Added
@@ -271,6 +56,8 @@ For a full list of changes see [Full list of changes](https://github.com/jomjol/
## [15.1.1] - 2023-03-23
### Changes
For a full list of changes see [Full list of changes](https://github.com/jomjol/AI-on-the-edge-device/compare/v15.1.0...v15.1.1)
#### Added
@@ -325,7 +112,7 @@ For a full list of changes see [Full list of changes](https://github.com/jomjol/
:bangbang: **Attention:** Update your configuration!
- Hybrid CNN network to `dig-cont_0611_s3`
- Analog CNN network to `ana-cont-11.0.5` and `ana-clas100-1.5.7`
- Digit CNN network to `dig-class100-1.6.0`
- Digital CNN network to `dig-class100-1.6.0`
- Various Web interface Improvements/Enhancements:
- Restructured Menu (Needs cache clearing to be applied)
- Enhanced `Previous Value` page
@@ -461,7 +248,7 @@ For a full list of changes see [Full list of changes](https://github.com/jomjol/
- Improved OTA Update mechanism (only working after installation for next update)
- Added data logging in `/log/data` - One day per file and each measurement is on one line
- Format: csv - comma separated
- Content: `time`, `name-of-number`, `raw-value`, `return-value`, `pre-value`, `change-rate`, `change-absolute`, `error-text`, `cnn-digit`, `cnn-analog`
- Content: `time`, `name-of-number`, `raw-value`, `return-value`, `pre-value`, `change-rate`, `change-absolute`, `error-text`, `cnn-digital`, `cnn-analog`
- Show graph of values direct in the user interface (thanks to [@rdmueller](https://github.com/rdmueller))
- Using new data logging (see above)
@@ -479,10 +266,10 @@ For a full list of changes see [Full list of changes](https://github.com/jomjol/
- Updated OTA functionality (more robust, but not fully bullet prove yet)
- Updated Espressif library to `espressif32@v5.2.0`
- [#1176](https://github.com/jomjol/AI-on-the-edge-device/discussions/1176) accept minor negative values (-0.2) if extended resolution is enabled
- [#1143](https://github.com/jomjol/AI-on-the-edge-device/issues/1143) added config parameter `AnalogDigTransitionStart`. It can setup very early and very late digit transition starts.
- [#1143](https://github.com/jomjol/AI-on-the-edge-device/issues/1143) added config parameter `AnalogDigitalTransitionStart`. It can setup very early and very late digit transition starts.
- New version of `dig-class100` (v1.4.0): added images of heliowatt powermeter
- NEW v13.0.2: Update Tool "Logfile downloader and combiner" to handle the new csv file format.
- NEW v13.0.2: MQTT: Added MQTT topic `status` (Digitization Status), Timezone to MQTT topic `timestamp`.#
- NEW v13.0.2: MQTT: Added MQTT topic `status` (Digitalization Status), Timezone to MQTT topic `timestamp`.#
- NEW v13.0.2: Logging: Disable heap logs by default, cleanup
- NEW v13.0.7:
- log NTP server name
@@ -607,7 +394,7 @@ Intermediate Digits
- Updated analog neural network file (`ana-cont_11.3.0_s2.tflite` - default, `ana-class100_0120_s1_q.tflite`)
- Updated digit neural network file (`dig-cont_0570_s3.tflite` - default, `dig-class100_0120_s2_q.tflite`)
- Updated digital neural network file (`dig-cont_0570_s3.tflite` - default, `dig-class100_0120_s2_q.tflite`)
- Added automated filtering of tflite-file in the graphical configuration (thanks to @**[caco3](https://github.com/caco3)**)
@@ -619,8 +406,8 @@ Intermediate Digits
Intermediate Digits
- New and improved consistency check (especially with analog and digit counters mixed)
- Bug Fix: digit counter algorithm
- New and improved consistency check (especially with analog and digital counters mixed)
- Bug Fix: digital counter algorithm
## [11.0.1](https://github.com/jomjol/AI-on-the-edge-device/releases/tag/v11.0.1), 2022-08-18
@@ -631,16 +418,16 @@ Intermediate Digits
- Implementation of new CNN types to detect intermediate values of digits with rolling numbers
- By default the old algo (0, 1, ..., 9, "N") is active (due to the limited types of digits trained so far)
- Activation can be done by selecting a tflite file with the new trained model in the 'config.ini'
- Activation can be done by selection a tflite file with the new trained model in the 'config.ini'
- **Details can be found in the [wiki](https://github.com/jomjol/AI-on-the-edge-device/wiki/Neural-Network-Types)** (different types, trained image types, naming convention)
- Updated neural network files (and adaptation to new naming convention)
- Updated neural network files (and adaption to new naming convention)
- Published a tool to download and combine log files - Thanks to [Contributor]
- Published a tool to download and combine log files - **Thanks to **
- Files see ['/tools/logfile-tool'](tbd), How-to see [wiki](https://github.com/jomjol/AI-on-the-edge-device/wiki/Gasmeter-Log-Downloader)
- Bug Fix: InfluxDB enabling in graphic configuration
- Bug Fix: InfluxDB enabling in grahic configuration
## [10.6.2](https://github.com/jomjol/AI-on-the-edge-device/releases/tag/v10.6.2), 2022-07-24
@@ -654,13 +441,13 @@ Stability Increase
- **NEW 10.6.1**: Bug Fix: tflite-filename with ".", HTML spelling error
- InfluxDB: direct injection into InfluxDB - thanks to **[wetneb](https://github.com/wetneb)**
- IndluxDB: direct injection into InfluxDB - thanks to **[wetneb](https://github.com/wetneb)**
- MQTT: implemented "Retain Flag" and extend with absolute Change (in addition to rate)
- `config.ini`: removal of modelsize (readout from tflite)
- Updated analog neural network file (`ana1000s2.tflite`) & digit neural network file (`dig1400s2q.tflite`)
- Updated analog neural network file (`ana1000s2.tflite`) & digital neural network file (`dig1400s2q.tflite`)
- TFMicro/Lite: Update (espressif Version 20220716)
@@ -696,7 +483,7 @@ Stability Increase
- In the future the new files will also be copied to the `firmware` directory of the repository
- Added Wifi RSSI to MQTT information
- Updated analog neural network file (`ana-s3-q-20220105.tflite`)
- Updated digit neural network file (`dig-s1-q-20220102.tflite`)
- Updated digital neural network file (`dig-s1-q-20220102.tflite`)
- Updated build environment to `Espressif 3.5.0`
## [10.3.0] - (2022-01-29)
@@ -762,7 +549,7 @@ Stability Increase
- Update analog neural network (ana-s3-q-20220105.tflite)
- Update digit neural network (dig-s1-q-20220102.tflite)
- Update digital neural network (dig-s1-q-20220102.tflite)
- Increased web-server buffers
@@ -799,7 +586,7 @@ External Illumination
- Direct JSON access: `http://IP-ADRESS/json`
- Error message in log file in case camera error during startup
- Upgrade analog CNN to v9.1.0
- Upgrade digit CNN to v13.3.0 (added new images)
- Upgrade digital CNN to v13.3.0 (added new images)
- html: support of different ports
## [9.1.1] - External Illumination (2021-11-16)
@@ -824,7 +611,7 @@ External Illumination
### Changed
- Upgrade digit CNN to v13.1.0 (added new images)
- Upgrade digital CNN to v13.1.0 (added new images)
- bug fix: wlan password with space, double digit output
## [8.4.0] - Multi Meter Support (2021-09-25)
@@ -854,7 +641,7 @@ External Illumination
### Changed
- Upgrade digit CNN to v12.1.0 (added new images)
- Upgrade digital CNN to v12.1.0 (added new images)
- Dedicated NaN handling, internal refactoring (CNN-Handling)
- HTML: confirmation after config.ini update
- Bug fixing
@@ -876,7 +663,7 @@ External Illumination
- GPIO: using the general mqtt main topic for GPIO
- Upgrade digit CNN to v12.0.0 (added new images)
- Upgrade digital CNN to v12.0.0 (added new images)
- Update tfmicro to new master (2021-08-07)
- Bug fix: remove text in mqtt value, remove connect limit in wlan reconnet
@@ -912,7 +699,7 @@ External Illumination
- Update wlan handling to esp-idf 4.1
- Upgrade digit CNN to v8.7.0 (added new images)
- Upgrade digital CNN to v8.7.0 (added new images)
- Bug fix: MQTT, WLAN, LED-Controll, GPIO usage, fixed IP, calculation flow rate
@@ -923,7 +710,7 @@ External Illumination
- NEW: 7.0.1: bug fix wlan password with "="
- Upgrade digit CNN to v8.5.0 (added new images)
- Upgrade digital CNN to v8.5.0 (added new images)
- New MQTT topics: flow rate (units/minute), time stamp (last correct read readout)
@@ -940,7 +727,7 @@ External Illumination
- NEW 6.7.1: Improved stability of camera (back to v6.6.1) - remove black strips and areas
- Upgrade digit CNN to v8.3.0 (added new type of digits)
- Upgrade digital CNN to v8.3.0 (added new type of digits)
- Internal update: TFlite (v2.5), esp32cam, startup sequence
@@ -961,7 +748,7 @@ External Illumination
### Changed
- Upgrade digit CNN to v8.2.0 (added new type of digits)
- Upgrade digital CNN to v8.2.0 (added new type of digits)
- Supporting alignment structures in ROI definition
@@ -997,7 +784,7 @@ External Illumination
- Determination of fixed illumination settings during startup - speed up of 5s in each run
- Update digit CNN to v8.1.1 (additional digit images trained)
- Update digital CNN to v8.1.1 (additional digital images trained)
- Extended error message in MQTT error message
@@ -1009,7 +796,7 @@ External Illumination
### Changed
- Disabling of analog / digit counters in configuration
- Disabling of analog / digital counters in configuration
- Improved Alignment Algorithm (`AlignmentAlgo` = `Default`, `Accurate` , `Fast`)
@@ -1029,7 +816,7 @@ External Illumination
- MQTT: Last Will Testament (LWT) implemented: "connection lost" in case of connection lost to `TopicError`
- Disabled `CheckDigitIncreaseConsistency` in default configuration - must now be explicit enabled if needed
- Update digit CNN to v7.2.1 (additional digit images trained)
- Update digital CNN to v7.2.1 (additional digital images trained)
- Setting of arbitrary time server in `config.ini`
- Option for fixed IP-, DNS-Settings in `wlan.ini`
- Increased stability (internal image and camera handling)
@@ -1063,7 +850,7 @@ External Illumination
- standardized access to current logfile via `http://IP-ADRESS/logfileact`
- Update digit CNN to v7.2.0, analog CNN to 6.3.0
- Update digital CNN to v7.2.0, analog CNN to 6.3.0
- Bug fixing: truncation error, CheckDigitConsistency & PreValue implementation
@@ -1082,7 +869,7 @@ External Illumination
### Changed
- Update digit CNN to v6.5.0 and HTML (Info to hostname, IP, ssid)
- Update digital CNN to v6.5.0 and HTML (Info to hostname, IP, ssid)
- New implementation of "checkDigitConsistency" also for digits
@@ -1169,7 +956,7 @@ External Illumination
- Bug in configuration of analog ROIs corrected
- minor Bug correction
- minor bug correction
## [1.0.1](2020-09-05)
@@ -1178,7 +965,7 @@ External Illumination
- preValue.ini Bug corrected
- minor Bug correction
- minor bug correction
## [1.0.0](2020-09-04)

View File

@@ -2,54 +2,28 @@
**There are a lot of ideas for further improvements, but only limited capacity on side of the developer.** Therefore I have created this page as a collection of ideas.
1. Whoever has a new idea can put it here, so that it is not forgotten.
1. Who ever has a new idea can put it here, so it that it is not forgotten.
2. Whoever has the time, capacity and passion to support the project can take any of the ideas and implement them. I will provide support and help wherever I can!
2. Who ever has time, capacity and passion to support, can take any of the ideas and implement them.
I will support and help where ever I can!
____
#### #40 Trigger with cron like exact time slot
* https://github.com/jomjol/AI-on-the-edge-device/issues/2470
#### #39 upnp implementation to auto detect the device
* https://github.com/jomjol/AI-on-the-edge-device/issues/2481
#### #38 Energy Saving
* Deep sleep between recognition
* https://github.com/jomjol/AI-on-the-edge-device/issues/2486
#### #37 Auto init SD card
* Fully implement the SD card handling (including formatting) into the firmware
* https://github.com/jomjol/AI-on-the-edge-device/issues/2488Demo
#### #36 Run demo without camera
Demo mode requires a working camera (if not, one receives a 'Cam bad' error). Would be nice to demo or play around on other ESP32 boards (or on ESP32-CAM boards when you broke the camera cable...).
#### #35 Use the same model, but provide the image from a Smartphone Camera
as reading the Electricity or Water meter every few minutes only delivers apparent accuracy (DE: "Scheingenauigkeit") you could just as well take a picture with your Smartphone every so often (e.g. once a week when you are in the Basement anyway), then with some "semi clever" tricks pass this image to the model developed here, and the values than on to whoever needs them e.g. via MQTT.
as reading the Electricity or Water meter every few minutues only delivers apparent accuracy (DE: "Scheingenauigkeit") you could just as well take a picture with your Smartphone evey so often (e.g. once a week when you are in the Basement anyway), then with some "semi clever" tricks pass this image to the model developed here, and the values then on to who ever needs them e.g. via MQTT.
IMO: It is not needed to have that many readings (datapoints) as our behaviour (Use of electricity or water) doesn't vary that much, say, over a weeks time. The interpolation between weekly readings will give sufficient information on the power and/or water usage.
#### #34 implement state and Roi for water leak detection
for example see Roi in the next picture..
for example see Roi on the next picture..
![grafik](https://user-images.githubusercontent.com/38385805/207858812-2a6ba41d-1a8c-4fa1-9b6a-53cdd113c106.png)
in case of position change between the measurements set this state to true, if there is no change set it back to false.
in case of position change between the measurments set this state to true, if there is no change set it back to false.
In a defined time window this movement can lead into an alarm state / water leak..
having this state in the mqtt broker can trigger functions like closing the water pipe valve and so on...
haveing this state in the mqtt broker can trigger functions like closing the ater pipe walve and so on...
@@ -65,7 +39,7 @@ having this state in the mqtt broker can trigger functions like closing the wate
#### #31 Implement InfluxDB v2.x interface
* Currently only InfluxDB v1.x is supported, extend to v2.x
* Currently only InfluxDB v1.x is supportet, extend to v2.x
* Remark: interface has changed
* see [#1160](https://github.com/jomjol/AI-on-the-edge-device/issues/1160)
@@ -77,12 +51,12 @@ having this state in the mqtt broker can trigger functions like closing the wate
#### ~~#29 Add favicon and use the hostname for the website~~- implemented v11.3.1
* ~~https://github.com/jomjol/AI-on-the-edge-device/issues/927~~
~~* https://github.com/jomjol/AI-on-the-edge-device/issues/927~~
#### #28 Improved error handling for ROIs
* In case a ROI is out of the image, there is no error message, but a non sense image is used
* Implement a error message for wrong configuration of ROI
* Implement a error message for wrong configuratioin of ROI
#### #27 Use Homie Spec for Mqtt binding
@@ -115,7 +89,7 @@ having this state in the mqtt broker can trigger functions like closing the wate
#### ~~#22 Direct hint to the different neural network files in the other repositories~~- implemented >v11.3.1
* ~~https://github.com/jomjol/AI-on-the-edge-device/issues/644~~
~~* https://github.com/jomjol/AI-on-the-edge-device/issues/644~~

View File

@@ -1,68 +0,0 @@
# **Dual Use License for AI-on-the-Edge Device**
Version: 1.0 - Draft Version
Date: 2025-01-05 (5th January 2025)
## **Preamble**
This license allows individuals to use, modify, and share AI-on-the-Edge freely for private, non-commercial purposes. Any commercial use requires a separate licensing agreement with the rights holder.
------
## **1. Grant of License**
### 1.1 **Private Use**
The licensor grants the licensee a free, non-exclusive, worldwide license to use, modify, and distribute the software for private, non-commercial purposes.
### 1.2 **Commercial Use**
The use of the software or any derivative works in any commercial context (including, but not limited to, selling, renting, providing as a service, or integrating into commercial products) is prohibited without a separate commercial license.
------
## **2. Obligation to Private Derivatives**
In modified private versions of the software, the unchanged license as well as the reference to the original source and authors must always be stated (https://github.com/jomjol/AI-on-the-edge-device).
Modified versions of the software must be clearly marked as such and must not imply they are provided by the original licensor.
------
## **3. Commercial Licensing**
Companies, organizations, or individuals wishing to use the software for commercial purposes must obtain a separate commercial license. Please contact mueller.josef(@)gmail.com for further details.
------
## **4. Terms of Cooperation**
By contributing to the AI-on-the-Edge software, this license is considered accepted. This applies to, but is not limited to, code, error corrections, extensions, artwork, documentation, and new features. Any contribution, including libraries and sources, must comply with the terms of this license.
The contributor agrees that the added code and functionality may also be used in commercial versions without compensation to the contributor.
------
## **5. Disclaimer of Liability**
### 5.1 **General Disclaimer**
The software is provided "as is", without any express or implied warranties. The licensor is not liable for any damages resulting from the use of the software.
### 5.2 **No Usage in Safety or Security Environments**
The image processing uses neural networks, among other algorithms, whose results can produce incorrect or unexpected outcomes due to their functionality and the underlying training data. Therefore, this system must not be used or offered for safety-relevant systems or systems with high reliability requirements.
------
## **6. General Provisions**
### 6.1 **Severability Clause**
If any provision of this license is deemed invalid, the remaining provisions shall remain in full force and effect.
------
## **Acceptance**
By using this software, the licensee agrees to the terms of this license.

719
README.md
View File

@@ -1,667 +1,102 @@
<h1 align="center">AI on the Edge Device: Digitizing Your non-digital meters with an ESP32-CAM</h1>
<br>
<br>
# Welcome to the AI-on-the-edge-device
<img src="images/icon/watermeter.svg" width="100px">
## Table of Contents
- [Key Features 🚀](#key-features-)
- [Workflow 🔧](#workflow-)
- [Impressions 📷](#impressions-)
- [AI-on-the-edge-device on a Water Meter 💧](#ai-on-the-edge-device-on-a-water-meter-)
- [Web Interface (Water Meter) 💻](#web-interface-water-meter-)
- [AI-on-the-edge-device on an Electrical Power Meter ⚡](#ai-on-the-edge-device-on-an-electrical-power-meter-)
- [Setup 🛠️](#setup-%EF%B8%8F)
- [Download 🔽](#download-)
- [Flashing the ESP32 💾](#flashing-the-esp32-)
- [Flashing the SD Card 💾](#flashing-the-sd-card-)
- [Casing 🛠️](#casing-%EF%B8%8F)
- [Donate ☕](#donate-)
- [Support 💬](#support-)
- [Changes and History 📜](#changes-and-history-)
- [Build It Yourself 🔨](#build-it-yourself-)
- [Tools 🛠️](#tools-%EF%B8%8F)
- [Additional Ideas 💡](#additional-ideas-)
- [Our Contributors ❤️](#our-contributors-%EF%B8%8F)
Artificial intelligence based systems have been established in our every days live. Just think of speech or image recognition. Most of the systems relay on either powerful processors or a direct connection to the cloud for doing the calculations up there. With the increasing power of modern processors the AI systems are coming closer to the end user - which is usually called **edge computing**.
Here this edge computing is brought into a practical oriented example, where a AI network is implemented on a ESP32 device so: **AI on the edge**.
<p align="center">
<a href="#top">
<img src="https://img.shields.io/badge/Back%20to%20Top-000000?style=for-the-badge&logo=github&logoColor=white" alt="Back to Top">
</a>
</p>
This projects allows you to digitalize your **analoge** water, gas, power and other meters using cheap and easily available hardware.
All you need is an [ESP32 board with a supported camera](https://jomjol.github.io/AI-on-the-edge-device-docs/Hardware-Compatibility/) and a bit of a practical hand.
<img src="images/esp32-cam.png" width="200px">
## Key features
- Tensorflow Lite (TFlite) integration - including easy to use wrapper
- Inline Image processing (feature detection, alignment, ROI extraction)
- **Small** and **cheap** device (3x4.5x2 cm³, < 10 EUR)
- camera and illumination integrated
- Web surface to administrate and control
- OTA-Interface to update directly through the web interface
- Full integration into Homeassistant
- Support for Influx DB 1
- MQTT
- REST API
## Workflow
The device takes a photo of your meter at a defined interval. It then extracts the Regions of Interest (ROI's) out of it and runs them through an artificial inteligence. As a result, you get the digitalized value of your meter.
There are several options what to do with that value. Either send it to a MQTT broker, write it to an InfluxDb or simply provide it throug a REST API.
<img src="https://raw.githubusercontent.com/jomjol/AI-on-the-edge-device/master/images/idea.jpg" width="600">
## Impressions
### AI-on-the-edge-device on a Water Meter
<img src="https://raw.githubusercontent.com/jomjol/AI-on-the-edge-device/master/images/watermeter_all.jpg" width="200"><img src="https://raw.githubusercontent.com/jomjol/AI-on-the-edge-device/master/images/main.jpg" width="200"><img src="https://raw.githubusercontent.com/jomjol/AI-on-the-edge-device/master/images/size.png" width="200">
### Web Interface (Water Meter)
<img src="https://raw.githubusercontent.com/jomjol/AI-on-the-edge-device/master/images/watermeter.jpg" width="600">
### AI-on-the-edge-device on a Electrical Power Meter
<img src="https://raw.githubusercontent.com/jomjol/AI-on-the-edge-device/master/images/powermeter.jpg" width="600">
## Setup
There is a growing [documentation](https://jomjol.github.io/AI-on-the-edge-device-docs/) which provides you with a lot of information.
Head there to get a start, set it up and configure it.
There are also a articles in the German Heise magazine "make:" about the setup and the technical background (behind a paywall) : [DIY - Setup](https://www.heise.de/select/make/2021/2/2103513300897420296)
[![made-with-c++](https://img.shields.io/badge/Made%20with-C++-1f425f.svg)](https://github.com/jomjol/AI-on-the-edge-device/tree/main/code)
[![Doc](https://img.shields.io/badge/Doc-MkDocs-526CFE.svg)](https://jomjol.github.io/AI-on-the-edge-device-docs/)
[![Total downloads](https://img.shields.io/github/downloads/jomjol/AI-on-the-edge-device/total.svg)](https://GitHub.com/jomjol/AI-on-the-edge-device/releases/)
[![GitHub release](https://img.shields.io/github/release/jomjol/AI-on-the-edge-device.svg)](https://GitHub.com/jomjol/AI-on-the-edge-device/releases/)
[![GitHub forks](https://img.shields.io/github/forks/jomjol/AI-on-the-edge-device.svg?style=social&label=Fork&maxAge=2592000)](https://GitHub.com/jomjol/AI-on-the-edge-device/network/)
[![GitHub stars](https://img.shields.io/github/stars/jomjol/AI-on-the-edge-device.svg?style=social&label=Star&maxAge=2592000)](https://GitHub.com/jomjol/AI-on-the-edge-device/stargazers/)
For further background information, head to [Neural Networks](https://www.heise.de/select/make/2021/6/2126410443385102621), [Training Neural Networks](https://www.heise.de/select/make/2022/1/2134114065999161585) and [Programming on the ESP32](https://www.heise.de/select/make/2022/2/2204010051597422030)
<p align="center" id="top">
<img src="images/icon/watermeter.svg" width="150px">
</p>
### Download
The latest available version is available on the [Releases page](https://github.com/jomjol/AI-on-the-edge-device/releases).
Artificial intelligence is everywhere, from speech to image recognition. While most AI systems rely on powerful processors or cloud computing, **edge computing** brings AI closer to the end user by utilizing the capabilities of modern processors.
This project demonstrates edge computing using the **ESP32**, a low-cost, AI-capable device, to digitize your analog meters—whether water, gas, or electricity. With affordable hardware and simple instructions, you can turn any standard meter into a smart device.
Let's explore how to make **AI on the Edge** a reality! 🌟
All you need is an [ESP32 board with a supported camera](https://jomjol.github.io/AI-on-the-edge-device-docs/Hardware-Compatibility/) and some practical skills. 🛠️
---
<br>
## Key Features 🚀
- 🔗 **Tensorflow Lite (TFLite) integration** including an easy-to-use wrapper.
- 📸 **Inline image processing** (feature detection, alignment, ROI extraction).
- 💡 **Small** and **affordable** device (3 x 4.5 x 2 cm³, less than 10 EUR).
- 📷 Integrated camera and illumination.
- 🌐 Web interface for administration and control.
- 🔄 OTA interface for updating directly via the web interface.
- 🏠 Full integration with Home Assistant.
- 📊 Support for **Influx DB 1** and **2**.
- 📡 **MQTT protocol** support.
- 📥 **REST API** available for data access.
<br>
## Workflow 🔧
The device captures a photo of your meter at set intervals. It then extracts the Regions of Interest (ROIs) from the image and runs them through artificial intelligence. As a result, you get the digitized value of your meter.
There are several options for what to do with that value:
- 📤 Send it to a **MQTT broker**.
- 📝 Write it to an **InfluxDb**.
- 🔗 Provide access via a **REST API**.
<p align="center">
<img src="images/idea.jpg" width="600">
</p>
---
<br>
## Impressions 📷
+ ### AI-on-the-edge-device on a Water Meter 💧
<p align="center">
<img src="images/watermeter_all.jpg" width="200"><img
src="images/main.jpg" width="200"><img
src="images/size.png" width="200">
</p>
+ ### Web Interface (Water Meter) 💻
<p align="center">
<img src="images/watermeter.jpg" width="600">
</p>
+ ### AI-on-the-edge-device on an Electrical Power Meter ⚡
<p align="center">
<img src="images/powermeter.jpg" width="600">
</p>
---
<br>
## Setup 🛠️
There is growing [documentation](https://jomjol.github.io/AI-on-the-edge-device-docs/) which provides you with a lot of information. Head there to get started, set it up, and configure it.
There are also articles in the German Heise magazine "make:" about the setup and technical background (behind a paywall): [DIY - Setup](https://www.heise.de/select/make/2021/2/2103513300897420296) 📰
A lot of people have created useful YouTube videos that might help you get started:
- 🎥 [youtube.com/watch?v=HKBofb1cnNc](https://www.youtube.com/watch?v=HKBofb1cnNc)
- 🎥 [youtube.com/watch?v=yyf0ORNLCk4](https://www.youtube.com/watch?v=yyf0ORNLCk4)
- 🎥 [youtube.com/watch?v=XxmTubGek6M](https://www.youtube.com/watch?v=XxmTubGek6M)
- 🎥 [youtube.com/watch?v=mDIJEyElkAU](https://www.youtube.com/watch?v=mDIJEyElkAU)
- 🎥 [youtube.com/watch?v=SssiPkyKVVs](https://www.youtube.com/watch?v=SssiPkyKVVs)
- 🎥 [youtube.com/watch?v=MAHE_QyHZFQ](https://www.youtube.com/watch?v=MAHE_QyHZFQ)
- 🎥 [youtube.com/watch?v=Uap_6bwtILQ](https://www.youtube.com/watch?v=Uap_6bwtILQ)
For further background information, head to:
- [Neural Networks](https://www.heise.de/select/make/2021/6/2126410443385102621)
- [Training Neural Networks](https://www.heise.de/select/make/2022/1/2134114065999161585)
- [Programming on the ESP32](https://www.heise.de/select/make/2022/2/2204010051597422030)
---
<br>
## Download 🔽
The latest available version can be found on the [Releases page](https://github.com/jomjol/AI-on-the-edge-device/releases).
---
<br>
## Flashing the ESP32 💾
Initially, you will have to flash the ESP32 via a USB connection. Later updates are possible directly over the air (OTA using Wi-Fi).
### Flashing of the ESP32
Initially you will have to flash the ESP32 through an USB connection. Later an update is possible directly over the Air (OTA).
There are different ways to flash your ESP32:
- The preferred way is the [Web Installer and Console](https://jomjol.github.io/AI-on-the-edge-device/index.html), a browser-based tool to flash the ESP32 and extract the log over USB:
![](images/web-installer.png)
- [Web Installer and Console](https://jomjol.github.io/AI-on-the-edge-device/index.html) (Webbrowser based tool to flash the ESP32 and extract the Log over USB)
- Flash Tool from Espressif
- ESPtool (command-line tool)
- ESPtool (Command Line Tool)
See the [documentation](https://jomjol.github.io/AI-on-the-edge-device-docs/Installation/) for more information.
See the [Docu](https://jomjol.github.io/AI-on-the-edge-device-docs/Installation/) for more information.
---
### Flashing the SD-Card
The SD-Card must be flashed separately, see the [Docu](https://jomjol.github.io/AI-on-the-edge-device-docs/Installation/) for details.
<br>
## Casing
## Flashing the SD Card 💾
The SD card can be set up automatically after the firmware is installed. See the [documentation](https://jomjol.github.io/AI-on-the-edge-device-docs/Installation/#remote-setup-using-the-built-in-access-point) for details. For this to work, the SD card must be FAT formatted (which is the default on a new SD card).
A 3d-printable housing can be found here:
- https://www.thingiverse.com/thing:4573481 (Water Meter)
- https://www.thingiverse.com/thing:5028229 (Power Meter)
- https://www.thingiverse.com/thing:5224101 (Gas Meter)
- https://www.thingiverse.com/thing:4571627 (ESP32-Cam housing only)
Alternatively, the SD card can still be set up manually. See the [documentation](https://jomjol.github.io/AI-on-the-edge-device-docs/Installation/#3-sd-card) for details.
## Build it yourself
See [Build Instructions](code/README.md).
---
## Donate
If you would like to support the developer with a cup of coffee you can do that via [Paypal](https://www.paypal.com/donate?hosted_button_id=8TRSVYNYKDSWL).
<br>
<form action="https://www.paypal.com/donate" method="post" target="_top">
<input type="hidden" name="hosted_button_id" value="8TRSVYNYKDSWL" />
<input type="image" src="https://www.paypalobjects.com/en_US/DK/i/btn/btn_donateCC_LG.gif" border="0" name="submit" title="PayPal - The safer, easier way to pay online!" alt="Donate with PayPal button" />
<img alt="" border="0" src="https://www.paypal.com/en_DE/i/scr/pixel.gif" width="1" height="1" />
</form>
If you have any technical topics, you can create an [Issue](https://github.com/jomjol/AI-on-the-edge-device/issues).
## Casing 🛠️
Various 3D-printable housings can be found here:
- 💧 [Water Meter](https://www.thingiverse.com/thing:4573481)
- ⚡ [Power Meter](https://www.thingiverse.com/thing:5028229)
- 🔥 [Gas Meter](https://www.thingiverse.com/thing:5224101)
- 📷 [ESP32-cam housing only](https://www.thingiverse.com/thing:4571627)
In other cases you can contact the developer via email: <img src="https://raw.githubusercontent.com/jomjol/AI-on-the-edge-device/master/images/mail.jpg" height="25">
---
## Changes and History
See [Changelog](Changelog.md)
<br>
## Tools
## Donate ☕
If you'd like to support the developer with a cup of coffee, you can do so via [PayPal](https://www.paypal.com/donate?hosted_button_id=8TRSVYNYKDSWL).
* Logfile downloader and combiner (Thx to [reserve85](https://github.com/reserve85))
* Files see ['/tools/logfile-tool'](tbd), How-to see [Docu](https://jomjol.github.io/AI-on-the-edge-device-docs/outdated--Gasmeter-Log-Downloader/)
<p align="center">
<a href="https://www.paypal.com/donate?hosted_button_id=8TRSVYNYKDSWL"><img border="0" src="images/paypal.png" width="200px" target="_blank"></a>
</p>
## Additional Ideas
There are some ideas and feature requests which are not followed currently - mainly due to capacity reasons on side of the developer. They are collected here: [FeatureRequest.md](FeatureRequest.md)
---
------
<br>
## Support 💬
If you have any technical problems, please search the [discussions](https://github.com/jomjol/AI-on-the-edge-device/discussions). In case you find a bug or have a feature request, please open an [issue](https://github.com/jomjol/AI-on-the-edge-device/issues).
For any other issues, you can contact the developer via email:
<p align="center">
<img src="images/mail.jpg" height="25">
</p>
---
<br>
## Changes and History 📜
See the [Changelog](Changelog.md) for detailed information.
---
<br>
## Build It Yourself 🔨
See the [Build Instructions](code/README.md) for step-by-step guidance.
---
<br>
## Tools 🛠️
* Logfile downloader and combiner (Thanks to [reserve85](https://github.com/reserve85))
* It can be found at ['/tools/logfile-tool'](https://github.com/jomjol/AI-on-the-edge-device/tree/main/tools/logfile-tool).
---
<br>
## Additional Ideas 💡
There are some ideas and feature requests which are not currently being pursued—mainly due to capacity constraints on the part of the developers. These features are collected in the [issues](https://github.com/jomjol/AI-on-the-edge-device/issues) and in [FeatureRequest.md](FeatureRequest.md).
---
<br>
## Our Contributors ❤️
<!-- Do not manually edit this section! It should get updated using the Github action "Manually update contributors list" -->
<!-- readme: contributors -start -->
<table>
<tbody>
<tr>
<td align="center">
<a href="https://github.com/jomjol">
<img src="https://avatars.githubusercontent.com/u/30766535?v=4" width="100;" alt="jomjol"/>
<br />
<sub><b>jomjol</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/caco3">
<img src="https://avatars.githubusercontent.com/u/1783586?v=4" width="100;" alt="caco3"/>
<br />
<sub><b>CaCO3</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/haverland">
<img src="https://avatars.githubusercontent.com/u/412645?v=4" width="100;" alt="haverland"/>
<br />
<sub><b>Frank Haverland</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Slider0007">
<img src="https://avatars.githubusercontent.com/u/115730895?v=4" width="100;" alt="Slider0007"/>
<br />
<sub><b>Slider0007</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/SybexX">
<img src="https://avatars.githubusercontent.com/u/587201?v=4" width="100;" alt="SybexX"/>
<br />
<sub><b>michael</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/nliaudat">
<img src="https://avatars.githubusercontent.com/u/6782613?v=4" width="100;" alt="nliaudat"/>
<br />
<sub><b>Nicolas Liaudat</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/Zwer2k">
<img src="https://avatars.githubusercontent.com/u/10438794?v=4" width="100;" alt="Zwer2k"/>
<br />
<sub><b>Zwer2k</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/phlupp">
<img src="https://avatars.githubusercontent.com/u/6304863?v=4" width="100;" alt="phlupp"/>
<br />
<sub><b>phlupp</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/jasaw">
<img src="https://avatars.githubusercontent.com/u/721280?v=4" width="100;" alt="jasaw"/>
<br />
<sub><b>jasaw</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/dockSquadron">
<img src="https://avatars.githubusercontent.com/u/11964767?v=4" width="100;" alt="dockSquadron"/>
<br />
<sub><b>dockSquadron</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/rdmueller">
<img src="https://avatars.githubusercontent.com/u/1856308?v=4" width="100;" alt="rdmueller"/>
<br />
<sub><b>Ralf D. Müller</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/cristianmitran">
<img src="https://avatars.githubusercontent.com/u/36613624?v=4" width="100;" alt="cristianmitran"/>
<br />
<sub><b>cristianmitran</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/michaeljoos72">
<img src="https://avatars.githubusercontent.com/u/20517474?v=4" width="100;" alt="michaeljoos72"/>
<br />
<sub><b>michaeljoos72</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/henrythasler">
<img src="https://avatars.githubusercontent.com/u/6277203?v=4" width="100;" alt="henrythasler"/>
<br />
<sub><b>Henry Thasler</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/amantyagiprojects">
<img src="https://avatars.githubusercontent.com/u/174239452?v=4" width="100;" alt="amantyagiprojects"/>
<br />
<sub><b>Naman Tyagi</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/pixeldoc2000">
<img src="https://avatars.githubusercontent.com/u/376715?v=4" width="100;" alt="pixeldoc2000"/>
<br />
<sub><b>pixel::doc</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/mad2xlc">
<img src="https://avatars.githubusercontent.com/u/37449746?v=4" width="100;" alt="mad2xlc"/>
<br />
<sub><b>Stefan</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/jochenchrist">
<img src="https://avatars.githubusercontent.com/u/2930448?v=4" width="100;" alt="jochenchrist"/>
<br />
<sub><b>jochenchrist</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/parhedberg">
<img src="https://avatars.githubusercontent.com/u/13777521?v=4" width="100;" alt="parhedberg"/>
<br />
<sub><b>parhedberg</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/slovdahl">
<img src="https://avatars.githubusercontent.com/u/1417619?v=4" width="100;" alt="slovdahl"/>
<br />
<sub><b>Sebastian Lövdahl</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/RaHehl">
<img src="https://avatars.githubusercontent.com/u/7577984?v=4" width="100;" alt="RaHehl"/>
<br />
<sub><b>Raphael Hehl</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/LordGuilly">
<img src="https://avatars.githubusercontent.com/u/13271835?v=4" width="100;" alt="LordGuilly"/>
<br />
<sub><b>LordGuilly</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/bilalmirza74">
<img src="https://avatars.githubusercontent.com/u/84387676?v=4" width="100;" alt="bilalmirza74"/>
<br />
<sub><b>Bilal Mirza</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/muggenhor">
<img src="https://avatars.githubusercontent.com/u/484066?v=4" width="100;" alt="muggenhor"/>
<br />
<sub><b>Giel van Schijndel</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/ppisljar">
<img src="https://avatars.githubusercontent.com/u/13629809?v=4" width="100;" alt="ppisljar"/>
<br />
<sub><b>Peter Pisljar</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/ralf1307">
<img src="https://avatars.githubusercontent.com/u/46164027?v=4" width="100;" alt="ralf1307"/>
<br />
<sub><b>Ralf Rachinger</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Ranjana761">
<img src="https://avatars.githubusercontent.com/u/129291313?v=4" width="100;" alt="Ranjana761"/>
<br />
<sub><b>Ranjana761</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/SkylightXD">
<img src="https://avatars.githubusercontent.com/u/16561545?v=4" width="100;" alt="SkylightXD"/>
<br />
<sub><b>SkylightXD</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/ottk3">
<img src="https://avatars.githubusercontent.com/u/5236802?v=4" width="100;" alt="ottk3"/>
<br />
<sub><b>Sven Rojek</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Turbo87">
<img src="https://avatars.githubusercontent.com/u/141300?v=4" width="100;" alt="Turbo87"/>
<br />
<sub><b>Tobias Bieniek</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/tkopczuk">
<img src="https://avatars.githubusercontent.com/u/101632?v=4" width="100;" alt="tkopczuk"/>
<br />
<sub><b>Tomek Kopczuk</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/yonz2">
<img src="https://avatars.githubusercontent.com/u/13886257?v=4" width="100;" alt="yonz2"/>
<br />
<sub><b>Yonz</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Yveaux">
<img src="https://avatars.githubusercontent.com/u/7716005?v=4" width="100;" alt="Yveaux"/>
<br />
<sub><b>Yveaux</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/flooxo">
<img src="https://avatars.githubusercontent.com/u/93255373?v=4" width="100;" alt="flooxo"/>
<br />
<sub><b>flox_x</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/gneluka">
<img src="https://avatars.githubusercontent.com/u/32097881?v=4" width="100;" alt="gneluka"/>
<br />
<sub><b>gneluka</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/kalwados">
<img src="https://avatars.githubusercontent.com/u/11840444?v=4" width="100;" alt="kalwados"/>
<br />
<sub><b>kalwados</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/kub3let">
<img src="https://avatars.githubusercontent.com/u/95883234?v=4" width="100;" alt="kub3let"/>
<br />
<sub><b>kub3let</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/pfeifferch">
<img src="https://avatars.githubusercontent.com/u/73090220?v=4" width="100;" alt="pfeifferch"/>
<br />
<sub><b>pfeifferch</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/rstephan">
<img src="https://avatars.githubusercontent.com/u/8532364?v=4" width="100;" alt="rstephan"/>
<br />
<sub><b>rstephan</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/smartboart">
<img src="https://avatars.githubusercontent.com/u/38385805?v=4" width="100;" alt="smartboart"/>
<br />
<sub><b>smartboart</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/AngryApostrophe">
<img src="https://avatars.githubusercontent.com/u/89547888?v=4" width="100;" alt="AngryApostrophe"/>
<br />
<sub><b>AngryApostrophe</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/wetneb">
<img src="https://avatars.githubusercontent.com/u/309908?v=4" width="100;" alt="wetneb"/>
<br />
<sub><b>Antonin Delpeuch</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/adarazs">
<img src="https://avatars.githubusercontent.com/u/6269603?v=4" width="100;" alt="adarazs"/>
<br />
<sub><b>Attila Darazs</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/austindrenski">
<img src="https://avatars.githubusercontent.com/u/21338699?v=4" width="100;" alt="austindrenski"/>
<br />
<sub><b>Austin Drenski</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/PLCHome">
<img src="https://avatars.githubusercontent.com/u/29116097?v=4" width="100;" alt="PLCHome"/>
<br />
<sub><b>PLCHome</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/CFenner">
<img src="https://avatars.githubusercontent.com/u/9592452?v=4" width="100;" alt="CFenner"/>
<br />
<sub><b>Christopher Fenner</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/dkneisz">
<img src="https://avatars.githubusercontent.com/u/43378003?v=4" width="100;" alt="dkneisz"/>
<br />
<sub><b>Dave</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/FarukhS52">
<img src="https://avatars.githubusercontent.com/u/129654632?v=4" width="100;" alt="FarukhS52"/>
<br />
<sub><b>Farookh Zaheer Siddiqui</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/hex7c0">
<img src="https://avatars.githubusercontent.com/u/4419146?v=4" width="100;" alt="hex7c0"/>
<br />
<sub><b>Francesco Carnielli</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/040medien">
<img src="https://avatars.githubusercontent.com/u/115072?v=4" width="100;" alt="040medien"/>
<br />
<sub><b>Frederik Kemner</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/eltociear">
<img src="https://avatars.githubusercontent.com/u/22633385?v=4" width="100;" alt="eltociear"/>
<br />
<sub><b>Ikko Eltociear Ashimine</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/queeek">
<img src="https://avatars.githubusercontent.com/u/9533371?v=4" width="100;" alt="queeek"/>
<br />
<sub><b>Ina</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/joergrosenkranz">
<img src="https://avatars.githubusercontent.com/u/310438?v=4" width="100;" alt="joergrosenkranz"/>
<br />
<sub><b>Joerg Rosenkranz</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Innovatorcloudy">
<img src="https://avatars.githubusercontent.com/u/183274513?v=4" width="100;" alt="Innovatorcloudy"/>
<br />
<sub><b>KrishCode</b></sub>
</a>
</td>
</tr>
<tr>
<td align="center">
<a href="https://github.com/myxor">
<img src="https://avatars.githubusercontent.com/u/1397377?v=4" width="100;" alt="myxor"/>
<br />
<sub><b>Marco H</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/rainman110">
<img src="https://avatars.githubusercontent.com/u/3213107?v=4" width="100;" alt="rainman110"/>
<br />
<sub><b>Martin Siggel</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/mkelley88">
<img src="https://avatars.githubusercontent.com/u/5567324?v=4" width="100;" alt="mkelley88"/>
<br />
<sub><b>Matthew T. Kelley</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/toolsfactory">
<img src="https://avatars.githubusercontent.com/u/7744975?v=4" width="100;" alt="toolsfactory"/>
<br />
<sub><b>Michael Geissler</b></sub>
</a>
</td>
</tr>
<tbody>
</table>
<!-- readme: contributors -end -->
---
<div align="center">
<a href="#top">
<img src="https://img.shields.io/badge/Back%20to%20Top-000000?style=for-the-badge&logo=github&logoColor=white" alt="Back to Top">
</a>
</div>

1
code/.gitignore vendored
View File

@@ -1,5 +1,4 @@
.pio
.idea
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json

View File

@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.16.0)
list(APPEND EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common components/esp-tflite-micro esp-protocols/components/mdns)
list(APPEND EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common components/tflite-micro-esp-examples/components/tflite-lib)
ADD_CUSTOM_COMMAND(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/version.cpp

View File

@@ -8,15 +8,6 @@ git checkout rolling
git submodule update --init
```
## Update Submodules
```
cd /components/submodule-name (e.g. tflite-micro-example)
git checkout VERSION (e.g. HASH of latest tflite-micro-example build)
cd ../../ (auf Ebene von code)
git submodule update --init
```
Evt. muss man vorher noch einige Verzeichnisse in compenents von Hand löschen, da sie beim checkout nicht gelöscht wurden (vor update -- init)
## Build and Flash within terminal
See further down to build it within an IDE.
### Compile
@@ -69,6 +60,3 @@ pio device monitor -p /dev/ttyUSB0
- `pio run --target erase` to erase the flash
- `pio run --target upload` this will upload the `bootloader.bin, partitions.bin,firmware.bin` from the `code/.pio/build/esp32cam/` folder.
- `pio device monitor` to observe the logs via uart
# Update Parameters
If you create or rename a parameter, make sure to update its documentation in `../param-docs/parameter-pages`! Check the `../param-docs/README.md` for more information.

View File

@@ -25,7 +25,6 @@
#include "server_mqtt.h"
#endif //ENABLE_MQTT
#include "basic_auth.h"
static const char *TAG = "GPIO";
QueueHandle_t gpio_queue_handle = NULL;
@@ -459,7 +458,7 @@ void GpioHandler::registerGpioUri()
httpd_uri_t camuri = { };
camuri.method = HTTP_GET;
camuri.uri = "/GPIO";
camuri.handler = APPLY_BASIC_AUTH_FILTER(callHandleHttpRequest);
camuri.handler = callHandleHttpRequest;
camuri.user_ctx = (void*)this;
httpd_register_uri_handler(_httpServer, &camuri);
}

File diff suppressed because it is too large Load Diff

View File

@@ -15,103 +15,49 @@
#include "CImageBasis.h"
#include "../../include/defines.h"
typedef struct
{
uint16_t CamSensor_id;
class CCamera {
protected:
int ActualQuality;
framesize_t ActualResolution;
int brightness, contrast, saturation;
bool isFixedExposure;
int waitbeforepicture_org;
int led_intensity = 4095;
framesize_t ImageFrameSize = FRAMESIZE_VGA; // 0 - 10
gainceiling_t ImageGainceiling; // Image gain (GAINCEILING_x2, x4, x8, x16, x32, x64 or x128)
void ledc_init(void);
bool CameraInitSuccessful = false;
bool demoMode = false;
int ImageQuality; // 0 - 63
int ImageBrightness; // (-2 to 2) - set brightness
int ImageContrast; //-2 - 2
int ImageSaturation; //-2 - 2
int ImageSharpness; //-2 - 2
bool ImageAutoSharpness;
int ImageSpecialEffect; // 0 - 6
int ImageWbMode; // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home)
int ImageAwb; // white balance enable (0 or 1)
int ImageAwbGain; // Auto White Balance enable (0 or 1)
int ImageAec; // auto exposure off (1 or 0)
int ImageAec2; // automatic exposure sensor (0 or 1)
int ImageAeLevel; // auto exposure levels (-2 to 2)
int ImageAecValue; // set exposure manually (0-1200)
int ImageAgc; // auto gain off (1 or 0)
int ImageAgcGain; // set gain manually (0 - 30)
int ImageBpc; // black pixel correction
int ImageWpc; // white pixel correction
int ImageRawGma; // (1 or 0)
int ImageLenc; // lens correction (1 or 0)
int ImageHmirror; // (0 or 1) flip horizontally
int ImageVflip; // Invert image (0 or 1)
int ImageDcw; // downsize enable (1 or 0)
bool loadNextDemoImage(camera_fb_t *fb);
long GetFileSize(std::string filename);
int ImageDenoiseLevel; // The OV2640 does not support it, OV3660 and OV5640 (0 to 8)
public:
int image_height, image_width;
CCamera();
esp_err_t InitCam();
int ImageWidth;
int ImageHeight;
void LightOnOff(bool status);
void LEDOnOff(bool status);
esp_err_t CaptureToHTTP(httpd_req_t *req, int delay = 0);
esp_err_t CaptureToStream(httpd_req_t *req, bool FlashlightOn);
void SetQualitySize(int qual, framesize_t resol);
bool SetBrightnessContrastSaturation(int _brightness, int _contrast, int _saturation);
void GetCameraParameter(httpd_req_t *req, int &qual, framesize_t &resol);
void SetLEDIntensity(float _intrel);
bool testCamera(void);
void EnableAutoExposure(int flash_duration);
bool getCameraInitSuccessful();
void useDemoMode(void);
int ImageLedIntensity;
framesize_t TextToFramesize(const char * text);
bool ImageZoomEnabled;
int ImageZoomOffsetX;
int ImageZoomOffsetY;
int ImageZoomSize;
int WaitBeforePicture;
bool isImageSize;
bool CameraInitSuccessful;
bool changedCameraSettings;
bool DemoMode;
bool SaveAllFiles;
} camera_controll_config_temp_t;
extern camera_controll_config_temp_t CCstatus;
class CCamera
{
protected:
void ledc_init(void);
bool loadNextDemoImage(camera_fb_t *fb);
long GetFileSize(std::string filename);
void SetCamWindow(sensor_t *s, int frameSizeX, int frameSizeY, int xOffset, int yOffset, int xTotal, int yTotal, int xOutput, int yOutput, int imageVflip);
void SetImageWidthHeightFromResolution(framesize_t resol);
void SanitizeZoomParams(int imageSize, int frameSizeX, int frameSizeY, int &imageWidth, int &imageHeight, int &zoomOffsetX, int &zoomOffsetY);
public:
int LedIntensity = 4096;
CCamera(void);
esp_err_t InitCam(void);
void LightOnOff(bool status);
void LEDOnOff(bool status);
esp_err_t setSensorDatenFromCCstatus(void);
esp_err_t getSensorDatenToCCstatus(void);
int SetCamGainceiling(sensor_t *s, gainceiling_t gainceilingLevel);
void SetCamSharpness(bool autoSharpnessEnabled, int sharpnessLevel);
void SetCamSpecialEffect(sensor_t *s, int specialEffect);
void SetCamContrastBrightness(sensor_t *s, int _contrast, int _brightness);
esp_err_t CaptureToHTTP(httpd_req_t *req, int delay = 0);
esp_err_t CaptureToStream(httpd_req_t *req, bool FlashlightOn);
void SetQualityZoomSize(int qual, framesize_t resol, bool zoomEnabled, int zoomOffsetX, int zoomOffsetY, int imageSize, int imageVflip);
void SetZoomSize(bool zoomEnabled, int zoomOffsetX, int zoomOffsetY, int imageSize, int imageVflip);
int SetLEDIntensity(int _intrel);
bool testCamera(void);
bool getCameraInitSuccessful(void);
void useDemoMode(void);
framesize_t TextToFramesize(const char *text);
esp_err_t CaptureToFile(std::string nm, int delay = 0);
esp_err_t CaptureToBasisImage(CImageBasis *_Image, int delay = 0);
esp_err_t CaptureToFile(std::string nm, int delay = 0);
esp_err_t CaptureToBasisImage(CImageBasis *_Image, int delay = 0);
};
extern CCamera Camera;
#endif

View File

@@ -1,88 +0,0 @@
// Workaround - bug in cam library - enable bits are set without using bitwise OR logic -> only latest enable setting is used
// Reference: https://esp32.com/viewtopic.php?f=19&t=14376#p93178
/* The memory structure is as follows for
byte_0 = enable_bits
byte_0->bit0 = enable saturation and hue --> OK
byte_0->bit1 = enable saturation --> OK
byte_0->bit2 = enable brightness and contrast --> OK
byte_0->bit3 = enable green -> blue spitial effect (Antique and blunish and greenish and reddish and b&w) enable
byte_0->bit4 = anable gray -> red spitial effect (Antique and blunish and greenish and reddish and b&w) enable
byte_0->bit5 = remove (UV) in YUV color system
byte_0->bit6 = enable negative
byte_0->bit7 = remove (Y) in YUV color system
byte_1 = saturation1 0-255 --> ?
byte_2 = hue 0-255 --> OK
byte_3 = saturation2 0-255 --> OK
byte_4 = reenter saturation2 in documents --> ?
byte_5 = spital effect green -> blue 0-255 --> ?
byte_6 = spital effect gray -> red 0-255 --> ?
byte_7 = contrast lower byte 0-255 --> OK
byte_8 = contrast higher byte 0-255 --> OK
byte_9 = brightness 0-255 --> OK
byte_10 = if byte_10==4 contrast effective --> ?
*/
#include <stdint.h>
#include "esp_camera.h"
#include "ov2640_contrast_brightness.h"
static const uint8_t brightness_regs[6][5] = {
{0x7C, 0x7D, 0x7C, 0x7D, 0x7D },
{0x00, 0x04, 0x09, 0x00, 0x00 }, /* -2 */
{0x00, 0x04, 0x09, 0x10, 0x00 }, /* -1 */
{0x00, 0x04, 0x09, 0x20, 0x00 }, /* 0 */
{0x00, 0x04, 0x09, 0x30, 0x00 }, /* +1 */
{0x00, 0x04, 0x09, 0x40, 0x00 }, /* +2 */
};
static const uint8_t contrast_regs[6][7] = {
{0x7C, 0x7D, 0x7C, 0x7D, 0x7D, 0x7D, 0x7D },
{0x00, 0x04, 0x07, 0x20, 0x18, 0x34, 0x06 }, /* -2 */
{0x00, 0x04, 0x07, 0x20, 0x1c, 0x2a, 0x06 }, /* -1 */
{0x00, 0x04, 0x07, 0x20, 0x20, 0x20, 0x06 }, /* 0 */
{0x00, 0x04, 0x07, 0x20, 0x24, 0x16, 0x06 }, /* +1 */
{0x00, 0x04, 0x07, 0x20, 0x28, 0x0c, 0x06 }, /* +2 */
};
int ov2640_set_contrast_brightness(sensor_t *sensor, int _contrast, int _brightness)
{
int ret=0;
_contrast += 3;
if (_contrast <= 0) {
_contrast = 3;
}
else if (_contrast > 5)
{
_contrast = 5;
}
sensor->status.contrast = _contrast-3;
_brightness += 3;
if (_brightness <= 0) {
_brightness = 3;
}
else if (_brightness > 5)
{
_brightness = 5;
}
int brightness = brightness_regs[_brightness][3];
sensor->status.brightness = _brightness-3;
// sensor->set_reg(sensor, int reg, int mask, int value)
sensor->set_reg(sensor, 0xFF, 0x01, 0x00); // Select DSP bank
for (int i=0; i<7; i++)
{
if (i == 5)
{
sensor->set_reg(sensor, contrast_regs[0][i], 0xFF, (brightness | contrast_regs[_contrast][i]));
}
else
{
sensor->set_reg(sensor, contrast_regs[0][i], 0xFF, contrast_regs[_contrast][i]);
}
}
return ret;
}

View File

@@ -1,10 +0,0 @@
#pragma once
#ifndef OV2640_CONTRAST_BRIGHTNESS_H
#define OV2640_CONTRAST_BRIGHTNESS_H
#include "esp_camera.h"
int ov2640_set_contrast_brightness(sensor_t *sensor, int _contrast, int _brightness);
#endif

View File

@@ -1,151 +0,0 @@
#include <stdint.h>
#include "esp_camera.h"
#include "ov2640_sharpness.h"
const static uint8_t OV2640_SHARPNESS_AUTO[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0x20, 0x20,
0x00, 0x00, 0x00
};
const static uint8_t OV2640_SHARPNESS_MANUAL[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0x00, 0x20,
0x00, 0x00, 0x00
};
const static uint8_t OV2640_SHARPNESS_LEVEL0[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0xC0, 0x1F,
0x00, 0x00, 0x00
};
const static uint8_t OV2640_SHARPNESS_LEVEL1[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0xC1, 0x1F,
0x00, 0x00, 0x00
};
const static uint8_t OV2640_SHARPNESS_LEVEL2[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0xC2, 0x1F,
0x00, 0x00, 0x00
};
const static uint8_t OV2640_SHARPNESS_LEVEL3[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0xC4, 0x1F,
0x00, 0x00, 0x00
};
const static uint8_t OV2640_SHARPNESS_LEVEL4[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0xC8, 0x1F,
0x00, 0x00, 0x00
};
const static uint8_t OV2640_SHARPNESS_LEVEL5[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0xD0, 0x1F,
0x00, 0x00, 0x00
};
const static uint8_t OV2640_SHARPNESS_LEVEL6[]=
{
//reg, val, mask
0xFF, 0x00, 0xFF,
0x92, 0x01, 0xFF,
0x93, 0xDF, 0x1F,
0x00, 0x00, 0x00
};
const static uint8_t *OV2640_SETTING_SHARPNESS[]=
{
OV2640_SHARPNESS_LEVEL0, // -3 sharpness
OV2640_SHARPNESS_LEVEL1,
OV2640_SHARPNESS_LEVEL2,
OV2640_SHARPNESS_LEVEL3,
OV2640_SHARPNESS_LEVEL4,
OV2640_SHARPNESS_LEVEL5,
OV2640_SHARPNESS_LEVEL6 // +3 sharpness
};
#define OV2640_MAXLEVEL_SHARPNESS 6
static int table_mask_write(sensor_t *sensor, const uint8_t* ptab)
{
uint8_t address;
uint8_t value;
uint8_t orgval;
uint8_t mask;
const uint8_t *pdata = ptab;
if (pdata == NULL)
{
return -1;
}
while (1)
{
address = *pdata++;
value = *pdata++;
mask = *pdata++;
if ((address == 0) && (value == 0) && (mask == 0))
{
break;
}
sensor->set_reg(sensor, address, mask, value);
}
return 0;
}
int ov2640_enable_auto_sharpness(sensor_t *sensor)
{
table_mask_write(sensor, OV2640_SHARPNESS_AUTO);
sensor->status.sharpness = 0;
return 0;
}
int ov2640_set_sharpness(sensor_t *sensor, int sharpness)
{
int sharpness_temp = 0;
if (sharpness < -3)
{
sharpness_temp = -3;
}
if (sharpness > OV2640_MAXLEVEL_SHARPNESS - 3)
{
sharpness_temp = OV2640_MAXLEVEL_SHARPNESS - 3;
}
table_mask_write(sensor, OV2640_SHARPNESS_MANUAL);
table_mask_write(sensor, OV2640_SETTING_SHARPNESS[sharpness_temp + 3]);
sensor->status.sharpness = sharpness;
return 0;
}

View File

@@ -1,11 +0,0 @@
#pragma once
#ifndef OV2640_SHARPNESS_H
#define OV2640_SHARPNESS_H
#include "esp_camera.h"
int ov2640_enable_auto_sharpness(sensor_t *sensor);
int ov2640_set_sharpness(sensor_t *sensor, int sharpness); // -3 to +3, -4 for auto-sharpness
#endif

View File

@@ -1,66 +0,0 @@
// Workaround - bug in cam library - enable bits are set without using bitwise OR logic -> only latest enable setting is used
// Reference: https://esp32.com/viewtopic.php?f=19&t=14376#p93178
/* The memory structure is as follows for
byte_0 = enable_bits
byte_0->bit0 = enable saturation and hue --> OK
byte_0->bit1 = enable saturation --> OK
byte_0->bit2 = enable brightness and contrast --> OK
byte_0->bit3 = enable green -> blue spitial effect (Antique and blunish and greenish and reddish and b&w) enable
byte_0->bit4 = anable gray -> red spitial effect (Antique and blunish and greenish and reddish and b&w) enable
byte_0->bit5 = remove (UV) in YUV color system
byte_0->bit6 = enable negative
byte_0->bit7 = remove (Y) in YUV color system
byte_1 = saturation1 0-255 --> ?
byte_2 = hue 0-255 --> OK
byte_3 = saturation2 0-255 --> OK
byte_4 = reenter saturation2 in documents --> ?
byte_5 = spital effect green -> blue 0-255 --> ?
byte_6 = spital effect gray -> red 0-255 --> ?
byte_7 = contrast lower byte 0-255 --> OK
byte_8 = contrast higher byte 0-255 --> OK
byte_9 = brightness 0-255 --> OK
byte_10 = if byte_10==4 contrast effective --> ?
*/
#include <stdint.h>
#include "esp_camera.h"
#include "ov2640_specialEffect.h"
static const uint8_t special_effects_regs[8][5] = {
{0x7C, 0x7D, 0x7C, 0x7D, 0x7D},
{0x00, 0X00, 0x05, 0X80, 0X80}, /* no effect */
{0x00, 0X40, 0x05, 0X80, 0X80}, /* negative */
{0x00, 0X18, 0x05, 0X80, 0X80}, /* black and white */
{0x00, 0X18, 0x05, 0X40, 0XC0}, /* reddish */
{0x00, 0X18, 0x05, 0X40, 0X40}, /* greenish */
{0x00, 0X18, 0x05, 0XA0, 0X40}, /* blue */
{0x00, 0X18, 0x05, 0X40, 0XA6}, /* retro */
};
int ov2640_set_special_effect(sensor_t *sensor, int effect)
{
int ret = 0;
effect++;
if (effect <= 0 || effect > 7)
{
effect = 1;
}
sensor->status.special_effect = effect - 1;
int registerValue = 0x06; // enable saturation, contrast, brightness
registerValue |= special_effects_regs[effect][1];
// sensor->set_reg(sensor, int reg, int mask, int value)
sensor->set_reg(sensor, 0xFF, 0x01, 0x00); // Select DSP bank
sensor->set_reg(sensor, special_effects_regs[0][0], 0xFF, 0x00);
sensor->set_reg(sensor, special_effects_regs[0][1], 0x5E, registerValue);
for (int i = 2; i < 5; i++)
{
sensor->set_reg(sensor, special_effects_regs[0][i], 0xFF, special_effects_regs[effect][i]);
}
return ret;
}

View File

@@ -1,10 +0,0 @@
#pragma once
#ifndef OV2640_SPECIALEFFECT_H
#define OV2640_SPECIALEFFECT_H
#include "esp_camera.h"
int ov2640_set_special_effect(sensor_t *sensor, int effect);
#endif

View File

@@ -5,200 +5,191 @@
#include "esp_camera.h"
#include "ClassControllCamera.h"
#include "MainFlowControl.h"
#include "ClassLogFile.h"
#include "esp_log.h"
#include "basic_auth.h"
#include "../../include/defines.h"
static const char *TAG = "server_cam";
void PowerResetCamera()
{
#if CAM_PIN_PWDN == GPIO_NUM_NC // Use reset only if pin is available
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "No power down pin availbale to reset camera");
#else
ESP_LOGD(TAG, "Resetting camera by power down line");
gpio_config_t conf;
conf.intr_type = GPIO_INTR_DISABLE;
conf.pin_bit_mask = 1LL << CAM_PIN_PWDN;
conf.mode = GPIO_MODE_OUTPUT;
conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
conf.pull_up_en = GPIO_PULLUP_DISABLE;
gpio_config(&conf);
// carefull, logic is inverted compared to reset pin
gpio_set_level(CAM_PIN_PWDN, 1);
vTaskDelay(1000 / portTICK_PERIOD_MS);
gpio_set_level(CAM_PIN_PWDN, 0);
vTaskDelay(1000 / portTICK_PERIOD_MS);
#endif
void PowerResetCamera(){
ESP_LOGD(TAG, "Resetting camera by power down line");
gpio_config_t conf;
conf.intr_type = GPIO_INTR_DISABLE;
conf.pin_bit_mask = 1LL << GPIO_NUM_32;
conf.mode = GPIO_MODE_OUTPUT;
conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
conf.pull_up_en = GPIO_PULLUP_DISABLE;
gpio_config(&conf);
// carefull, logic is inverted compared to reset pin
gpio_set_level(GPIO_NUM_32, 1);
vTaskDelay(1000 / portTICK_PERIOD_MS);
gpio_set_level(GPIO_NUM_32, 0);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
esp_err_t handler_lightOn(httpd_req_t *req)
{
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_lightOn - Start");
ESP_LOGD(TAG, "handler_lightOn uri: %s", req->uri);
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_lightOn - Start");
ESP_LOGD(TAG, "handler_lightOn uri: %s", req->uri);
#endif
if (Camera.getCameraInitSuccessful())
if (Camera.getCameraInitSuccessful())
{
Camera.LightOnOff(true);
const char *resp_str = (const char *)req->user_ctx;
const char* resp_str = (const char*) req->user_ctx;
httpd_resp_send(req, resp_str, strlen(resp_str));
}
else
else
{
httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Camera not initialized: REST API /lighton not available!");
return ESP_ERR_NOT_FOUND;
}
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_lightOn - Done");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_lightOn - Done");
#endif
return ESP_OK;
}
esp_err_t handler_lightOff(httpd_req_t *req)
{
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_lightOff - Start");
ESP_LOGD(TAG, "handler_lightOff uri: %s", req->uri);
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_lightOff - Start");
ESP_LOGD(TAG, "handler_lightOff uri: %s", req->uri);
#endif
if (Camera.getCameraInitSuccessful())
if (Camera.getCameraInitSuccessful())
{
Camera.LightOnOff(false);
const char *resp_str = (const char *)req->user_ctx;
httpd_resp_send(req, resp_str, strlen(resp_str));
const char* resp_str = (const char*) req->user_ctx;
httpd_resp_send(req, resp_str, strlen(resp_str));
}
else
else
{
httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Camera not initialized: REST API /lightoff not available!");
return ESP_ERR_NOT_FOUND;
}
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_lightOff - Done");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_lightOff - Done");
#endif
return ESP_OK;
}
esp_err_t handler_capture(httpd_req_t *req)
{
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture - Start");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture - Start");
#endif
if (Camera.getCameraInitSuccessful())
if (Camera.getCameraInitSuccessful())
{
// If the camera settings were changed by creating a new reference image, they must be reset
if (CFstatus.changedCameraSettings)
{
Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
Camera.LedIntensity = CCstatus.ImageLedIntensity;
CFstatus.changedCameraSettings = false;
}
int quality;
framesize_t res;
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Size: %d, Quality: %d", CCstatus.ImageFrameSize, CCstatus.ImageQuality);
#endif
Camera.GetCameraParameter(req, quality, res);
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Size: %d, Quality: %d", res, quality);
#endif
Camera.SetQualitySize(quality, res);
esp_err_t result;
result = Camera.CaptureToHTTP(req);
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture - Done");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture - Done");
#endif
return result;
}
else
else
{
httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Camera not initialized: REST API /capture not available!");
return ESP_ERR_NOT_FOUND;
}
}
esp_err_t handler_capture_with_light(httpd_req_t *req)
{
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture_with_light - Start");
#endif
if (Camera.getCameraInitSuccessful())
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture_with_light - Start");
#endif
if (Camera.getCameraInitSuccessful())
{
char _query[100];
char _delay[10];
int quality;
framesize_t res;
int delay = 2500;
if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
{
ESP_LOGD(TAG, "Query: %s", _query);
if (httpd_query_key_value(_query, "delay", _delay, 10) == ESP_OK)
{
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Delay: %s", _delay);
#endif
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Delay: %s", _delay);
#endif
delay = atoi(_delay);
if (delay < 0)
{
delay = 0;
}
}
}
// If the camera settings were changed by creating a new reference image, they must be reset
if (CFstatus.changedCameraSettings)
{
Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
Camera.LedIntensity = CCstatus.ImageLedIntensity;
CFstatus.changedCameraSettings = false;
}
Camera.GetCameraParameter(req, quality, res);
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Size: %d, Quality: %d", CCstatus.ImageFrameSize, CCstatus.ImageQuality);
#endif
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Size: %d, Quality: %d", res, quality);
#endif
Camera.SetQualitySize(quality, res);
Camera.LightOnOff(true);
const TickType_t xDelay = delay / portTICK_PERIOD_MS;
vTaskDelay(xDelay);
vTaskDelay( xDelay );
esp_err_t result;
result = Camera.CaptureToHTTP(req);
result = Camera.CaptureToHTTP(req);
Camera.LightOnOff(false);
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture_with_light - Done");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture_with_light - Done");
#endif
return result;
}
else
else
{
httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Camera not initialized: REST API /capture_with_flashlight not available!");
return ESP_ERR_NOT_FOUND;
}
}
esp_err_t handler_capture_save_to_file(httpd_req_t *req)
{
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture_save_to_file - Start");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture_save_to_file - Start");
#endif
if (Camera.getCameraInitSuccessful())
if (Camera.getCameraInitSuccessful())
{
char _query[100];
char _delay[10];
@@ -206,103 +197,94 @@ esp_err_t handler_capture_save_to_file(httpd_req_t *req)
char filename[100];
std::string fn = "/sdcard/";
int quality;
framesize_t res;
if (httpd_req_get_url_query_str(req, _query, 100) == ESP_OK)
{
ESP_LOGD(TAG, "Query: %s", _query);
if (httpd_query_key_value(_query, "filename", filename, 100) == ESP_OK)
{
fn.append(filename);
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Filename: %s", fn.c_str());
#endif
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Filename: %s", fn.c_str());
#endif
}
else
{
fn.append("noname.jpg");
}
if (httpd_query_key_value(_query, "delay", _delay, 10) == ESP_OK)
{
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Delay: %s", _delay);
#endif
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Delay: %s", _delay);
#endif
delay = atoi(_delay);
if (delay < 0)
{
delay = 0;
}
}
}
else
{
fn.append("noname.jpg");
}
// If the camera settings were changed by creating a new reference image, they must be reset
if (CFstatus.changedCameraSettings)
{
Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
Camera.LedIntensity = CCstatus.ImageLedIntensity;
CFstatus.changedCameraSettings = false;
}
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Size: %d, Quality: %d", CCstatus.ImageFrameSize, CCstatus.ImageQuality);
#endif
Camera.GetCameraParameter(req, quality, res);
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "Size: %d, Quality: %d", res, quality);
#endif
Camera.SetQualitySize(quality, res);
esp_err_t result;
result = Camera.CaptureToFile(fn, delay);
result = Camera.CaptureToFile(fn, delay);
const char *resp_str = (const char *)fn.c_str();
const char* resp_str = (const char*) fn.c_str();
httpd_resp_send(req, resp_str, strlen(resp_str));
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture_save_to_file - Done");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("handler_capture_save_to_file - Done");
#endif
return result;
}
else
else
{
httpd_resp_send_err(req, HTTPD_403_FORBIDDEN, "Camera not initialized: REST API /save not available!");
return ESP_ERR_NOT_FOUND;
}
}
void register_server_camera_uri(httpd_handle_t server)
{
#ifdef DEBUG_DETAIL_ON
#ifdef DEBUG_DETAIL_ON
ESP_LOGI(TAG, "server_part_camera - Registering URI handlers");
#endif
httpd_uri_t camuri = {};
camuri.method = HTTP_GET;
httpd_uri_t camuri = { };
camuri.method = HTTP_GET;
camuri.uri = "/lighton";
camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_lightOn);
camuri.user_ctx = (void *)"Light On";
camuri.uri = "/lighton";
camuri.handler = handler_lightOn;
camuri.user_ctx = (void*) "Light On";
httpd_register_uri_handler(server, &camuri);
camuri.uri = "/lightoff";
camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_lightOff);
camuri.user_ctx = (void *)"Light Off";
httpd_register_uri_handler(server, &camuri);
camuri.uri = "/lightoff";
camuri.handler = handler_lightOff;
camuri.user_ctx = (void*) "Light Off";
httpd_register_uri_handler(server, &camuri);
camuri.uri = "/capture";
camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_capture);
camuri.user_ctx = NULL;
httpd_register_uri_handler(server, &camuri);
camuri.uri = "/capture";
camuri.handler = handler_capture;
camuri.user_ctx = NULL;
httpd_register_uri_handler(server, &camuri);
camuri.uri = "/capture_with_flashlight";
camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_capture_with_light);
camuri.user_ctx = NULL;
httpd_register_uri_handler(server, &camuri);
camuri.uri = "/capture_with_flashlight";
camuri.handler = handler_capture_with_light;
camuri.user_ctx = NULL;
httpd_register_uri_handler(server, &camuri);
camuri.uri = "/save";
camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_capture_save_to_file);
camuri.user_ctx = NULL;
httpd_register_uri_handler(server, &camuri);
camuri.uri = "/save";
camuri.handler = handler_capture_save_to_file;
camuri.user_ctx = NULL;
httpd_register_uri_handler(server, &camuri);
}

View File

@@ -10,6 +10,7 @@
//#include "ClassControllCamera.h"
void register_server_camera_uri(httpd_handle_t server);
void PowerResetCamera();
#endif

View File

@@ -2,6 +2,6 @@ FILE(GLOB_RECURSE app_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.*)
idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "." "../../include" "miniz"
REQUIRES vfs esp_http_server app_update esp_http_client nvs_flash jomjol_tfliteclass jomjol_flowcontroll spiffs jomjol_helper jomjol_controlGPIO)
REQUIRES vfs tflite-lib esp_http_server app_update esp_http_client nvs_flash jomjol_tfliteclass jomjol_flowcontroll spiffs jomjol_helper jomjol_controlGPIO)

View File

@@ -153,7 +153,7 @@
/*#define MINIZ_NO_MALLOC */
#ifdef MINIZ_NO_INFLATE_APIS
//#define MINIZ_NO_ARCHIVE_APIS
#define MINIZ_NO_ARCHIVE_APIS
#endif
#ifdef MINIZ_NO_DEFLATE_APIS

View File

@@ -4,5 +4,5 @@ It should be possible to include the repo directly as a submodule, how ever it c
- https://github.com/richgel999/miniz/issues/145
- https://github.com/espressif/esptool/pull/500#issuecomment-574879468
For simplicity we therefore use the release files as suggested in the readme.
Additionally we added the CMakeLists.txt and this readme.
For sumplicity we therefore use the release files as suggested in the readme.
Additionally we added the CMakeLists.txt and this readme.

View File

@@ -46,7 +46,6 @@ extern "C" {
#include "Helper.h"
#include "miniz.h"
#include "basic_auth.h"
static const char *TAG = "OTA FILE";
@@ -548,7 +547,7 @@ static esp_err_t download_get_handler(httpd_req_t *req)
/* Get value of expected key from query string */
if (httpd_query_key_value(buf, "readonly", param, sizeof(param)) == ESP_OK) {
ESP_LOGI(TAG, "Found URL query parameter => readonly=%s", param);
readonly = (strcmp(param,"true") == 0);
readonly = param && strcmp(param,"true")==0;
}
}
}
@@ -589,9 +588,7 @@ static esp_err_t download_get_handler(httpd_req_t *req)
/* Read file in chunks into the scratch buffer */
chunksize = fread(chunk, 1, SERVER_FILER_SCRATCH_BUFSIZE, fd);
/* Send buffer contents as HTTP chunk. If empty this functions as a
* last-chunk message, signaling end-of-response, to the HTTP client.
* See RFC 2616, section 3.6.1 for details on Chunked Transfer Encoding. */
/* Send the buffer contents as HTTP response chunk */
if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK) {
fclose(fd);
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File sending failed!");
@@ -609,6 +606,8 @@ static esp_err_t download_get_handler(httpd_req_t *req)
fclose(fd);
ESP_LOGD(TAG, "File successfully sent");
/* Respond with an empty chunk to signal HTTP response completion */
httpd_resp_send_chunk(req, NULL, 0);
return ESP_OK;
}
@@ -718,8 +717,7 @@ static esp_err_t upload_post_handler(httpd_req_t *req)
/* Close file upon upload completion */
fclose(fd);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "File saved: " + string(filename));
ESP_LOGI(TAG, "File reception completed");
ESP_LOGI(TAG, "File reception complete");
std::string directory = std::string(filepath);
size_t zw = directory.find("/");
@@ -738,27 +736,21 @@ static esp_err_t upload_post_handler(httpd_req_t *req)
// ESP_LOGD(TAG, "Directory danach 2: %s", directory.c_str());
/* Redirect onto root to see the updated file list */
if (strcmp(filename, "/config/config.ini") == 0 ||
strcmp(filename, "/config/ref0.jpg") == 0 ||
strcmp(filename, "/config/ref0_org.jpg") == 0 ||
strcmp(filename, "/config/ref1.jpg") == 0 ||
strcmp(filename, "/config/ref1_org.jpg") == 0 ||
strcmp(filename, "/config/reference.jpg") == 0 ||
strcmp(filename, "/img_tmp/ref0.jpg") == 0 ||
strcmp(filename, "/img_tmp/ref0_org.jpg") == 0 ||
strcmp(filename, "/img_tmp/ref1.jpg") == 0 ||
strcmp(filename, "/img_tmp/ref1_org.jpg") == 0 ||
strcmp(filename, "/img_tmp/reference.jpg") == 0 )
{
httpd_resp_set_status(req, HTTPD_200); // Avoid reloading of folder content
}
else {
httpd_resp_set_status(req, "303 See Other"); // Reload folder content after upload
}
httpd_resp_set_status(req, "303 See Other");
httpd_resp_set_hdr(req, "Location", directory.c_str());
/* Redirect onto root to see the updated file list */
httpd_resp_set_status(req, "303 See Other");
httpd_resp_set_hdr(req, "Location", directory.c_str());
httpd_resp_sendstr(req, "File uploaded successfully");
/*
if (strcmp(filepath, CONFIG_FILE) == 0) {
ESP_LOGD(TAG, "New config found. Reload handler.");
gpio_handler_deinit();
MQTTdestroy();
}
*/
return ESP_OK;
}
@@ -845,15 +837,16 @@ static esp_err_t delete_post_handler(httpd_req_t *req)
return ESP_FAIL;
}
if (stat(filepath, &file_stat) == -1) { // File does not exist
/* This is ok, we would delete it anyway */
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "File does not exist: " + string(filename));
if (stat(filepath, &file_stat) == -1) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File does not exist: " + string(filename));
/* Respond with 400 Bad Request */
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "File does not exist");
return ESP_FAIL;
}
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Deleting file: " + string(filename));
/* Delete file */
unlink(filepath);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "File deleted: " + string(filename));
ESP_LOGI(TAG, "File deletion completed");
directory = std::string(filepath);
size_t zw = directory.find("/");
@@ -870,30 +863,16 @@ static esp_err_t delete_post_handler(httpd_req_t *req)
directory = directory.substr(start_fn, found - start_fn + 1);
directory = "/fileserver" + directory;
ESP_LOGD(TAG, "Directory danach 4: %s", directory.c_str());
//////////////////////////////////////////////////////////////
/* Redirect onto root to see the updated file list */
if (strcmp(filename, "/config/config.ini") == 0 ||
strcmp(filename, "/config/ref0.jpg") == 0 ||
strcmp(filename, "/config/ref0_org.jpg") == 0 ||
strcmp(filename, "/config/ref1.jpg") == 0 ||
strcmp(filename, "/config/ref1_org.jpg") == 0 ||
strcmp(filename, "/config/reference.jpg") == 0 ||
strcmp(filename, "/img_tmp/ref0.jpg") == 0 ||
strcmp(filename, "/img_tmp/ref0_org.jpg") == 0 ||
strcmp(filename, "/img_tmp/ref1.jpg") == 0 ||
strcmp(filename, "/img_tmp/ref1_org.jpg") == 0 ||
strcmp(filename, "/img_tmp/reference.jpg") == 0 )
{
httpd_resp_set_status(req, HTTPD_200); // Avoid reloading of folder content
}
else {
httpd_resp_set_status(req, "303 See Other"); // Reload folder content after upload
}
}
//////////////////////////////////////////////////////////////
/* Redirect onto root to see the updated file list */
httpd_resp_set_status(req, "303 See Other");
httpd_resp_set_hdr(req, "Location", directory.c_str());
httpd_resp_sendstr(req, "File successfully deleted");
return ESP_OK;
@@ -950,7 +929,7 @@ std::string unzip_new(std::string _in_zip_file, std::string _target_zip, std::st
// Get and print information about each file in the archive.
int numberoffiles = (int)mz_zip_reader_get_num_files(&zip_archive);
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Files to be extracted: " + to_string(numberoffiles));
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Numbers of files to be extracted: " + to_string(numberoffiles));
sort_iter = 0;
{
@@ -1014,7 +993,7 @@ std::string unzip_new(std::string _in_zip_file, std::string _target_zip, std::st
string filename_zw = zw + SUFFIX_ZW;
ESP_LOGI(TAG, "File to extract: %s, Temp. Filename: %s", zw.c_str(), filename_zw.c_str());
ESP_LOGI(TAG, "Filename to extract: %s, Zwischenfilename: %s", zw.c_str(), filename_zw.c_str());
std::string folder = filename_zw.substr(0, filename_zw.find_last_of('/'));
MakeDir(folder);
@@ -1118,7 +1097,7 @@ void unzip(std::string _in_zip_file, std::string _target_directory){
// Save to File.
zw = std::string(archive_filename);
zw = _target_directory + zw;
ESP_LOGD(TAG, "File to extract: %s", zw.c_str());
ESP_LOGD(TAG, "Filename to extract: %s", zw.c_str());
FILE* fpTargetFile = fopen(zw.c_str(), "wb");
fwrite(p, 1, (uint)uncomp_size, fpTargetFile);
fclose(fpTargetFile);
@@ -1175,7 +1154,7 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_download = {
.uri = "/fileserver*", // Match all URIs of type /path/to/file
.method = HTTP_GET,
.handler = APPLY_BASIC_AUTH_FILTER(download_get_handler),
.handler = download_get_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_download);
@@ -1184,7 +1163,7 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_datafileact = {
.uri = "/datafileact", // Match all URIs of type /path/to/file
.method = HTTP_GET,
.handler = APPLY_BASIC_AUTH_FILTER(datafileact_get_full_handler),
.handler = datafileact_get_full_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_datafileact);
@@ -1193,7 +1172,7 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_datafile_last_part_handle = {
.uri = "/data", // Match all URIs of type /path/to/file
.method = HTTP_GET,
.handler = APPLY_BASIC_AUTH_FILTER(datafileact_get_last_part_handler),
.handler = datafileact_get_last_part_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_datafile_last_part_handle);
@@ -1201,7 +1180,7 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_logfileact = {
.uri = "/logfileact", // Match all URIs of type /path/to/file
.method = HTTP_GET,
.handler = APPLY_BASIC_AUTH_FILTER(logfileact_get_full_handler),
.handler = logfileact_get_full_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_logfileact);
@@ -1210,7 +1189,7 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_logfile_last_part_handle = {
.uri = "/log", // Match all URIs of type /path/to/file
.method = HTTP_GET,
.handler = APPLY_BASIC_AUTH_FILTER(logfileact_get_last_part_handler),
.handler = logfileact_get_last_part_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_logfile_last_part_handle);
@@ -1220,7 +1199,7 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_upload = {
.uri = "/upload/*", // Match all URIs of type /upload/path/to/file
.method = HTTP_POST,
.handler = APPLY_BASIC_AUTH_FILTER(upload_post_handler),
.handler = upload_post_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_upload);
@@ -1229,7 +1208,7 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_delete = {
.uri = "/delete/*", // Match all URIs of type /delete/path/to/file
.method = HTTP_POST,
.handler = APPLY_BASIC_AUTH_FILTER(delete_post_handler),
.handler = delete_post_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_delete);

View File

@@ -61,13 +61,7 @@ esp_err_t send_file(httpd_req_t *req, std::string filename)
endsWith(filename, ".jpeg") ||
endsWith(filename, ".ico") ||
endsWith(filename, ".png")) {
if (filename == "/sdcard/html/setup.html") {
httpd_resp_set_hdr(req, "Clear-Site-Data", "\"*\"");
}
else {
httpd_resp_set_hdr(req, "Cache-Control", "max-age=86400");
}
httpd_resp_set_hdr(req, "Cache-Control", "max-age=86400");
}
set_content_type_from_file(req, filename.c_str());

View File

@@ -42,7 +42,6 @@ https://docs.espressif.com/projects/esp-idf/en/latest/esp32/migration-guides/rel
#include "Helper.h"
#include "statusled.h"
#include "basic_auth.h"
#include "../../include/defines.h"
/*an ota data write buffer ready to write to the flash*/
@@ -691,13 +690,13 @@ void register_server_ota_sdcard_uri(httpd_handle_t server)
httpd_uri_t camuri = { };
camuri.method = HTTP_GET;
camuri.uri = "/ota";
camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_ota_update);
camuri.handler = handler_ota_update;
camuri.user_ctx = (void*) "Do OTA";
httpd_register_uri_handler(server, &camuri);
camuri.method = HTTP_GET;
camuri.uri = "/reboot";
camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_reboot);
camuri.handler = handler_reboot;
camuri.user_ctx = (void*) "Reboot";
httpd_register_uri_handler(server, &camuri);

View File

@@ -2,6 +2,6 @@ FILE(GLOB_RECURSE app_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.*)
idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "."
REQUIRES esp_timer esp_wifi jomjol_tfliteclass jomjol_helper jomjol_controlcamera jomjol_mqtt jomjol_influxdb jomjol_webhook jomjol_fileserver_ota jomjol_image_proc jomjol_wlan openmetrics)
REQUIRES esp_timer esp_wifi jomjol_tfliteclass jomjol_helper jomjol_controlcamera jomjol_mqtt jomjol_influxdb jomjol_fileserver_ota jomjol_image_proc jomjol_wlan jomjol_helper)

View File

@@ -67,6 +67,11 @@ string ClassFlow::getHTMLSingleStep(string host){
return "";
}
string ClassFlow::getReadout()
{
return string();
}
std::string ClassFlow::GetParameterName(std::string _input)
{
string _param;

View File

@@ -46,6 +46,7 @@ public:
virtual bool ReadParameter(FILE* pfile, string &aktparamgraph);
virtual bool doFlow(string time);
virtual string getHTMLSingleStep(string host);
virtual string getReadout();
virtual string name(){return "ClassFlow";};
};

View File

@@ -1,374 +1,393 @@
#include "ClassFlowAlignment.h"
#include "ClassFlowTakeImage.h"
#include "ClassFlow.h"
#include "MainFlowControl.h"
#include "CRotateImage.h"
#include "esp_log.h"
#include "ClassLogFile.h"
#include "psram.h"
#include "../../include/defines.h"
static const char *TAG = "ALIGN";
// #define DEBUG_DETAIL_ON
void ClassFlowAlignment::SetInitialParameter(void)
{
initialrotate = 0;
anz_ref = 0;
use_antialiasing = false;
initialflip = false;
SaveAllFiles = false;
namerawimage = "/sdcard/img_tmp/raw.jpg";
FileStoreRefAlignment = "/sdcard/config/align.txt";
ListFlowControll = NULL;
AlignAndCutImage = NULL;
ImageBasis = NULL;
ImageTMP = NULL;
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
AlgROI = (ImageData *)malloc_psram_heap(std::string(TAG) + "->AlgROI", sizeof(ImageData), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
#endif
previousElement = NULL;
disabled = false;
SAD_criteria = 0.05;
}
ClassFlowAlignment::ClassFlowAlignment(std::vector<ClassFlow *> *lfc)
{
SetInitialParameter();
ListFlowControll = lfc;
for (int i = 0; i < ListFlowControll->size(); ++i) {
if (((*ListFlowControll)[i])->name().compare("ClassFlowTakeImage") == 0) {
ImageBasis = ((ClassFlowTakeImage *)(*ListFlowControll)[i])->rawImage;
}
}
// the function take pictures does not exist --> must be created first ONLY FOR TEST PURPOSES
if (!ImageBasis) {
ESP_LOGD(TAG, "CImageBasis had to be created");
ImageBasis = new CImageBasis("ImageBasis", namerawimage);
}
}
bool ClassFlowAlignment::ReadParameter(FILE *pfile, string &aktparamgraph)
{
std::vector<string> splitted;
int suchex = 40;
int suchey = 40;
int alg_algo = 0; // default=0; 1 =HIGHACCURACY; 2= FAST; 3= OFF //add disable aligment algo |01.2023
aktparamgraph = trim(aktparamgraph);
if (aktparamgraph.size() == 0)
{
if (!this->GetNextParagraph(pfile, aktparamgraph)) {
return false;
}
}
if (aktparamgraph.compare("[Alignment]") != 0)
{
// Paragraph does not fit Alignment
return false;
}
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
{
splitted = ZerlegeZeile(aktparamgraph);
if ((toUpper(splitted[0]) == "FLIPIMAGESIZE") && (splitted.size() > 1)) {
initialflip = alphanumericToBoolean(splitted[1]);
}
else if (((toUpper(splitted[0]) == "initialrotate") || (toUpper(splitted[0]) == "INITIALROTATE")) && (splitted.size() > 1)) {
if (isStringNumeric(splitted[1])) {
this->initialrotate = std::stod(splitted[1]);
}
}
else if ((toUpper(splitted[0]) == "SEARCHFIELDX") && (splitted.size() > 1)) {
if (isStringNumeric(splitted[1])) {
suchex = std::stod(splitted[1]);
}
}
else if ((toUpper(splitted[0]) == "SEARCHFIELDY") && (splitted.size() > 1)) {
if (isStringNumeric(splitted[1])) {
suchey = std::stod(splitted[1]);
}
}
else if ((toUpper(splitted[0]) == "ANTIALIASING") && (splitted.size() > 1)) {
use_antialiasing = alphanumericToBoolean(splitted[1]);
}
else if ((splitted.size() == 3) && (anz_ref < 2)) {
if ((isStringNumeric(splitted[1])) && (isStringNumeric(splitted[2])))
{
References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
References[anz_ref].target_x = std::stod(splitted[1]);
References[anz_ref].target_y = std::stod(splitted[2]);
anz_ref++;
}
else
{
References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
References[anz_ref].target_x = 10;
References[anz_ref].target_y = 10;
anz_ref++;
}
}
else if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1)) {
SaveAllFiles = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "ALIGNMENTALGO") && (splitted.size() > 1)) {
#ifdef DEBUG_DETAIL_ON
std::string zw2 = "Alignment mode selected: " + splitted[1];
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
#endif
if (toUpper(splitted[1]) == "HIGHACCURACY") {
alg_algo = 1;
}
if (toUpper(splitted[1]) == "FAST") {
alg_algo = 2;
}
if (toUpper(splitted[1]) == "OFF") {
// no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
alg_algo = 3;
}
}
}
for (int i = 0; i < anz_ref; ++i) {
References[i].search_x = suchex;
References[i].search_y = suchey;
References[i].fastalg_SAD_criteria = SAD_criteria;
References[i].alignment_algo = alg_algo;
#ifdef DEBUG_DETAIL_ON
std::string zw2 = "Alignment mode written: " + std::to_string(alg_algo);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
#endif
}
// no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
if (References[0].alignment_algo != 3) {
return LoadReferenceAlignmentValues();
}
return true;
}
string ClassFlowAlignment::getHTMLSingleStep(string host)
{
string result;
result = "<p>Rotated Image: </p> <p><img src=\"" + host + "/img_tmp/rot.jpg\"></p>\n";
result = result + "<p>Found Alignment: </p> <p><img src=\"" + host + "/img_tmp/rot_roi.jpg\"></p>\n";
result = result + "<p>Aligned Image: </p> <p><img src=\"" + host + "/img_tmp/alg.jpg\"></p>\n";
return result;
}
bool ClassFlowAlignment::doFlow(string time)
{
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
// AlgROI needs to be allocated before ImageTMP to avoid heap fragmentation
if (!AlgROI) {
AlgROI = (ImageData *)heap_caps_realloc(AlgROI, sizeof(ImageData), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
if (!AlgROI) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlgROI");
LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
}
}
if (AlgROI) {
ImageBasis->writeToMemoryAsJPG((ImageData *)AlgROI, 90);
}
#endif
if (!ImageTMP) {
ImageTMP = new CImageBasis("tmpImage", ImageBasis); // Make sure the name does not get change, it is relevant for the PSRAM allocation!
if (!ImageTMP) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate tmpImage -> Exec this round aborted!");
LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
return false;
}
}
delete AlignAndCutImage;
AlignAndCutImage = new CAlignAndCutImage("AlignAndCutImage", ImageBasis, ImageTMP);
if (!AlignAndCutImage) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlignAndCutImage -> Exec this round aborted!");
LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
return false;
}
CRotateImage rt("rawImage", AlignAndCutImage, ImageTMP, initialflip);
if (initialflip) {
int _zw = ImageBasis->height;
ImageBasis->height = ImageBasis->width;
ImageBasis->width = _zw;
_zw = ImageTMP->width;
ImageTMP->width = ImageTMP->height;
ImageTMP->height = _zw;
}
if ((initialrotate != 0) || initialflip) {
if (use_antialiasing) {
rt.RotateAntiAliasing(initialrotate);
}
else {
rt.Rotate(initialrotate);
}
if (SaveAllFiles) {
AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/rot.jpg"));
}
}
// no align algo if set to 3 = off //add disable aligment algo |01.2023
if (References[0].alignment_algo != 3) {
if (!AlignAndCutImage->Align(&References[0], &References[1])) {
SaveReferenceAlignmentValues();
}
} // no align
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
if (AlgROI) {
// no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
if (References[0].alignment_algo != 3) {
DrawRef(ImageTMP);
}
flowctrl.DigitDrawROI(ImageTMP);
flowctrl.AnalogDrawROI(ImageTMP);
ImageTMP->writeToMemoryAsJPG((ImageData *)AlgROI, 90);
}
#endif
if (SaveAllFiles) {
AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/alg.jpg"));
ImageTMP->SaveToFile(FormatFileName("/sdcard/img_tmp/alg_roi.jpg"));
}
// must be deleted to have memory space for loading tflite
delete ImageTMP;
ImageTMP = NULL;
// no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
if (References[0].alignment_algo != 3) {
return LoadReferenceAlignmentValues();
}
return true;
}
void ClassFlowAlignment::SaveReferenceAlignmentValues()
{
FILE *pFile;
std::string zwtime, zwvalue;
pFile = fopen(FileStoreRefAlignment.c_str(), "w");
if (strlen(zwtime.c_str()) == 0) {
time_t rawtime;
struct tm *timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S", timeinfo);
zwtime = std::string(buffer);
}
fputs(zwtime.c_str(), pFile);
fputs("\n", pFile);
zwvalue = std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_y);
zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
zwvalue = zwvalue + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
fputs(zwvalue.c_str(), pFile);
fputs("\n", pFile);
zwvalue = std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_y);
zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
zwvalue = zwvalue + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
fputs(zwvalue.c_str(), pFile);
fputs("\n", pFile);
fclose(pFile);
}
bool ClassFlowAlignment::LoadReferenceAlignmentValues(void)
{
FILE *pFile;
char zw[1024];
string zwvalue;
std::vector<string> splitted;
pFile = fopen(FileStoreRefAlignment.c_str(), "r");
if (pFile == NULL) {
return false;
}
fgets(zw, 1024, pFile);
ESP_LOGD(TAG, "%s", zw);
fgets(zw, 1024, pFile);
splitted = ZerlegeZeile(std::string(zw), " \t");
if (splitted.size() < 6) {
fclose(pFile);
return false;
}
References[0].fastalg_x = stoi(splitted[0]);
References[0].fastalg_y = stoi(splitted[1]);
References[0].fastalg_SAD = stof(splitted[2]);
References[0].fastalg_min = stoi(splitted[3]);
References[0].fastalg_max = stoi(splitted[4]);
References[0].fastalg_avg = stof(splitted[5]);
fgets(zw, 1024, pFile);
splitted = ZerlegeZeile(std::string(zw));
if (splitted.size() < 6) {
fclose(pFile);
return false;
}
References[1].fastalg_x = stoi(splitted[0]);
References[1].fastalg_y = stoi(splitted[1]);
References[1].fastalg_SAD = stof(splitted[2]);
References[1].fastalg_min = stoi(splitted[3]);
References[1].fastalg_max = stoi(splitted[4]);
References[1].fastalg_avg = stof(splitted[5]);
fclose(pFile);
/*#ifdef DEBUG_DETAIL_ON
std::string _zw = "\tLoadReferences[0]\tx,y:\t" + std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_x);
_zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
_zw = _zw + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
_zw = "\tLoadReferences[1]\tx,y:\t" + std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_x);
_zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
_zw = _zw + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
#endif*/
return true;
}
void ClassFlowAlignment::DrawRef(CImageBasis *_zw)
{
if (_zw->ImageOkay()) {
_zw->drawRect(References[0].target_x, References[0].target_y, References[0].width, References[0].height, 255, 0, 0, 2);
_zw->drawRect(References[1].target_x, References[1].target_y, References[1].width, References[1].height, 255, 0, 0, 2);
}
}
#include "ClassFlowAlignment.h"
#include "ClassFlowTakeImage.h"
#include "ClassFlow.h"
#include "MainFlowControl.h"
#include "CRotateImage.h"
#include "esp_log.h"
#include "ClassLogFile.h"
#include "psram.h"
#include "../../include/defines.h"
static const char *TAG = "ALIGN";
// #define DEBUG_DETAIL_ON
void ClassFlowAlignment::SetInitialParameter(void)
{
initalrotate = 0;
anz_ref = 0;
initialmirror = false;
use_antialiasing = false;
initialflip = false;
SaveAllFiles = false;
namerawimage = "/sdcard/img_tmp/raw.jpg";
FileStoreRefAlignment = "/sdcard/config/align.txt";
ListFlowControll = NULL;
AlignAndCutImage = NULL;
ImageBasis = NULL;
ImageTMP = NULL;
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
AlgROI = (ImageData*)malloc_psram_heap(std::string(TAG) + "->AlgROI", sizeof(ImageData), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
#endif
previousElement = NULL;
disabled = false;
SAD_criteria = 0.05;
}
ClassFlowAlignment::ClassFlowAlignment(std::vector<ClassFlow*>* lfc)
{
SetInitialParameter();
ListFlowControll = lfc;
for (int i = 0; i < ListFlowControll->size(); ++i)
{
if (((*ListFlowControll)[i])->name().compare("ClassFlowTakeImage") == 0)
{
ImageBasis = ((ClassFlowTakeImage*) (*ListFlowControll)[i])->rawImage;
}
}
if (!ImageBasis) // the function take pictures does not exist --> must be created first ONLY FOR TEST PURPOSES
{
ESP_LOGD(TAG, "CImageBasis had to be created");
ImageBasis = new CImageBasis("ImageBasis", namerawimage);
}
}
bool ClassFlowAlignment::ReadParameter(FILE* pfile, string& aktparamgraph)
{
std::vector<string> splitted;
int suchex = 40;
int suchey = 40;
int alg_algo = 0; //default=0; 1 =HIGHACCURACY; 2= FAST; 3= OFF //add disable aligment algo |01.2023
aktparamgraph = trim(aktparamgraph);
if (aktparamgraph.size() == 0)
if (!this->GetNextParagraph(pfile, aktparamgraph))
return false;
if (aktparamgraph.compare("[Alignment]") != 0) //Paragraph does not fit Alignment
return false;
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
{
splitted = ZerlegeZeile(aktparamgraph);
if ((toUpper(splitted[0]) == "FLIPIMAGESIZE") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
initialflip = true;
}
if ((toUpper(splitted[0]) == "INITIALMIRROR") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
initialmirror = true;
}
if (((toUpper(splitted[0]) == "INITALROTATE") || (toUpper(splitted[0]) == "INITIALROTATE")) && (splitted.size() > 1))
{
this->initalrotate = std::stod(splitted[1]);
}
if ((toUpper(splitted[0]) == "SEARCHFIELDX") && (splitted.size() > 1))
{
suchex = std::stod(splitted[1]);
}
if ((toUpper(splitted[0]) == "SEARCHFIELDY") && (splitted.size() > 1))
{
suchey = std::stod(splitted[1]);
}
if ((toUpper(splitted[0]) == "ANTIALIASING") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
use_antialiasing = true;
}
if ((splitted.size() == 3) && (anz_ref < 2))
{
References[anz_ref].image_file = FormatFileName("/sdcard" + splitted[0]);
References[anz_ref].target_x = std::stod(splitted[1]);
References[anz_ref].target_y = std::stod(splitted[2]);
anz_ref++;
}
if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
SaveAllFiles = true;
}
if ((toUpper(splitted[0]) == "ALIGNMENTALGO") && (splitted.size() > 1))
{
#ifdef DEBUG_DETAIL_ON
std::string zw2 = "Alignment mode selected: " + splitted[1];
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
#endif
if (toUpper(splitted[1]) == "HIGHACCURACY")
alg_algo = 1;
if (toUpper(splitted[1]) == "FAST")
alg_algo = 2;
if (toUpper(splitted[1]) == "OFF") //no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
alg_algo = 3;
}
}
for (int i = 0; i < anz_ref; ++i)
{
References[i].search_x = suchex;
References[i].search_y = suchey;
References[i].fastalg_SAD_criteria = SAD_criteria;
References[i].alignment_algo = alg_algo;
#ifdef DEBUG_DETAIL_ON
std::string zw2 = "Alignment mode written: " + std::to_string(alg_algo);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw2);
#endif
}
//no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
if(References[0].alignment_algo != 3){
LoadReferenceAlignmentValues();
}
return true;
}
string ClassFlowAlignment::getHTMLSingleStep(string host)
{
string result;
result = "<p>Rotated Image: </p> <p><img src=\"" + host + "/img_tmp/rot.jpg\"></p>\n";
result = result + "<p>Found Alignment: </p> <p><img src=\"" + host + "/img_tmp/rot_roi.jpg\"></p>\n";
result = result + "<p>Aligned Image: </p> <p><img src=\"" + host + "/img_tmp/alg.jpg\"></p>\n";
return result;
}
bool ClassFlowAlignment::doFlow(string time)
{
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
if (!AlgROI) // AlgROI needs to be allocated before ImageTMP to avoid heap fragmentation
{
AlgROI = (ImageData*)heap_caps_realloc(AlgROI, sizeof(ImageData), MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
if (!AlgROI)
{
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlgROI");
LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
}
}
if (AlgROI)
{
ImageBasis->writeToMemoryAsJPG((ImageData*)AlgROI, 90);
}
#endif
if (!ImageTMP)
{
ImageTMP = new CImageBasis("tmpImage", ImageBasis); // Make sure the name does not get change, it is relevant for the PSRAM allocation!
if (!ImageTMP)
{
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate tmpImage -> Exec this round aborted!");
LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
return false;
}
}
delete AlignAndCutImage;
AlignAndCutImage = new CAlignAndCutImage("AlignAndCutImage", ImageBasis, ImageTMP);
if (!AlignAndCutImage)
{
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Can't allocate AlignAndCutImage -> Exec this round aborted!");
LogFile.WriteHeapInfo("ClassFlowAlignment-doFlow");
return false;
}
CRotateImage rt("rawImage", AlignAndCutImage, ImageTMP, initialflip);
if (initialflip)
{
int _zw = ImageBasis->height;
ImageBasis->height = ImageBasis->width;
ImageBasis->width = _zw;
_zw = ImageTMP->width;
ImageTMP->width = ImageTMP->height;
ImageTMP->height = _zw;
}
if (initialmirror)
{
ESP_LOGD(TAG, "do mirror");
rt.Mirror();
if (SaveAllFiles)
AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/mirror.jpg"));
}
if ((initalrotate != 0) || initialflip)
{
if (use_antialiasing)
rt.RotateAntiAliasing(initalrotate);
else
rt.Rotate(initalrotate);
if (SaveAllFiles)
AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/rot.jpg"));
}
//no align algo if set to 3 = off //add disable aligment algo |01.2023
if(References[0].alignment_algo != 3){
if (!AlignAndCutImage->Align(&References[0], &References[1]))
{
SaveReferenceAlignmentValues();
}
}// no align
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
if (AlgROI) {
//no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
if(References[0].alignment_algo != 3){
DrawRef(ImageTMP);
}
flowctrl.DigitalDrawROI(ImageTMP);
flowctrl.AnalogDrawROI(ImageTMP);
ImageTMP->writeToMemoryAsJPG((ImageData*)AlgROI, 90);
}
#endif
if (SaveAllFiles)
{
AlignAndCutImage->SaveToFile(FormatFileName("/sdcard/img_tmp/alg.jpg"));
ImageTMP->SaveToFile(FormatFileName("/sdcard/img_tmp/alg_roi.jpg"));
}
// must be deleted to have memory space for loading tflite
delete ImageTMP;
ImageTMP = NULL;
//no align algo if set to 3 = off => no draw ref //add disable aligment algo |01.2023
if(References[0].alignment_algo != 3){
LoadReferenceAlignmentValues();
}
return true;
}
void ClassFlowAlignment::SaveReferenceAlignmentValues()
{
FILE* pFile;
std::string zwtime, zwvalue;
pFile = fopen(FileStoreRefAlignment.c_str(), "w");
if (strlen(zwtime.c_str()) == 0)
{
time_t rawtime;
struct tm* timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S", timeinfo);
zwtime = std::string(buffer);
}
fputs(zwtime.c_str(), pFile);
fputs("\n", pFile);
zwvalue = std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_y);
zwvalue = zwvalue + "\t" +std::to_string(References[0].fastalg_SAD)+ "\t" +std::to_string(References[0].fastalg_min);
zwvalue = zwvalue + "\t" +std::to_string(References[0].fastalg_max)+ "\t" +std::to_string(References[0].fastalg_avg);
fputs(zwvalue.c_str(), pFile);
fputs("\n", pFile);
zwvalue = std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_y);
zwvalue = zwvalue + "\t" +std::to_string(References[1].fastalg_SAD)+ "\t" +std::to_string(References[1].fastalg_min);
zwvalue = zwvalue + "\t" +std::to_string(References[1].fastalg_max)+ "\t" +std::to_string(References[1].fastalg_avg);
fputs(zwvalue.c_str(), pFile);
fputs("\n", pFile);
fclose(pFile);
}
bool ClassFlowAlignment::LoadReferenceAlignmentValues(void)
{
FILE* pFile;
char zw[1024];
string zwvalue;
std::vector<string> splitted;
pFile = fopen(FileStoreRefAlignment.c_str(), "r");
if (pFile == NULL)
return false;
fgets(zw, 1024, pFile);
ESP_LOGD(TAG, "%s", zw);
fgets(zw, 1024, pFile);
splitted = ZerlegeZeile(std::string(zw), " \t");
if (splitted.size() < 6)
{
fclose(pFile);
return false;
}
References[0].fastalg_x = stoi(splitted[0]);
References[0].fastalg_y = stoi(splitted[1]);
References[0].fastalg_SAD = stof(splitted[2]);
References[0].fastalg_min = stoi(splitted[3]);
References[0].fastalg_max = stoi(splitted[4]);
References[0].fastalg_avg = stof(splitted[5]);
fgets(zw, 1024, pFile);
splitted = ZerlegeZeile(std::string(zw));
if (splitted.size() < 6)
{
fclose(pFile);
return false;
}
References[1].fastalg_x = stoi(splitted[0]);
References[1].fastalg_y = stoi(splitted[1]);
References[1].fastalg_SAD = stof(splitted[2]);
References[1].fastalg_min = stoi(splitted[3]);
References[1].fastalg_max = stoi(splitted[4]);
References[1].fastalg_avg = stof(splitted[5]);
fclose(pFile);
/*#ifdef DEBUG_DETAIL_ON
std::string _zw = "\tLoadReferences[0]\tx,y:\t" + std::to_string(References[0].fastalg_x) + "\t" + std::to_string(References[0].fastalg_x);
_zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[0].fastalg_SAD) + "\t" + std::to_string(References[0].fastalg_min);
_zw = _zw + "\t" + std::to_string(References[0].fastalg_max) + "\t" + std::to_string(References[0].fastalg_avg);
LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
_zw = "\tLoadReferences[1]\tx,y:\t" + std::to_string(References[1].fastalg_x) + "\t" + std::to_string(References[1].fastalg_x);
_zw = _zw + "\tSAD, min, max, avg:\t" + std::to_string(References[1].fastalg_SAD) + "\t" + std::to_string(References[1].fastalg_min);
_zw = _zw + "\t" + std::to_string(References[1].fastalg_max) + "\t" + std::to_string(References[1].fastalg_avg);
LogFile.WriteToDedicatedFile("/sdcard/alignment.txt", _zw);
#endif*/
return true;
}
void ClassFlowAlignment::DrawRef(CImageBasis *_zw)
{
if (_zw->ImageOkay())
{
_zw->drawRect(References[0].target_x, References[0].target_y, References[0].width, References[0].height, 255, 0, 0, 2);
_zw->drawRect(References[1].target_x, References[1].target_y, References[1].width, References[1].height, 255, 0, 0, 2);
}
}

View File

@@ -1,51 +1,54 @@
#pragma once
#ifndef CLASSFLOWALIGNMENT_H
#define CLASSFLOWALIGNMENT_H
#include "ClassFlow.h"
#include "Helper.h"
#include "CAlignAndCutImage.h"
#include "CFindTemplate.h"
#include <string>
using namespace std;
class ClassFlowAlignment : public ClassFlow
{
protected:
float initialrotate;
bool initialflip;
bool use_antialiasing;
RefInfo References[2];
int anz_ref;
string namerawimage;
bool SaveAllFiles;
CAlignAndCutImage *AlignAndCutImage;
std::string FileStoreRefAlignment;
float SAD_criteria;
void SetInitialParameter(void);
bool LoadReferenceAlignmentValues(void);
void SaveReferenceAlignmentValues();
public:
CImageBasis *ImageBasis, *ImageTMP;
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
ImageData *AlgROI;
#endif
ClassFlowAlignment(std::vector<ClassFlow *> *lfc);
CAlignAndCutImage *GetAlignAndCutImage() { return AlignAndCutImage; };
void DrawRef(CImageBasis *_zw);
bool ReadParameter(FILE *pfile, string &aktparamgraph);
bool doFlow(string time);
string getHTMLSingleStep(string host);
string name() { return "ClassFlowAlignment"; };
};
#endif // CLASSFLOWALIGNMENT_H
#pragma once
#ifndef CLASSFLOWALIGNMENT_H
#define CLASSFLOWALIGNMENT_H
#include "ClassFlow.h"
#include "Helper.h"
#include "CAlignAndCutImage.h"
#include "CFindTemplate.h"
#include <string>
using namespace std;
class ClassFlowAlignment :
public ClassFlow
{
protected:
float initalrotate;
bool initialmirror;
bool initialflip;
bool use_antialiasing;
RefInfo References[2];
int anz_ref;
string namerawimage;
bool SaveAllFiles;
CAlignAndCutImage *AlignAndCutImage;
std::string FileStoreRefAlignment;
float SAD_criteria;
void SetInitialParameter(void);
bool LoadReferenceAlignmentValues(void);
void SaveReferenceAlignmentValues();
public:
CImageBasis *ImageBasis, *ImageTMP;
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
ImageData *AlgROI;
#endif
ClassFlowAlignment(std::vector<ClassFlow*>* lfc);
CAlignAndCutImage* GetAlignAndCutImage(){return AlignAndCutImage;};
void DrawRef(CImageBasis *_zw);
bool ReadParameter(FILE* pfile, string& aktparamgraph);
bool doFlow(string time);
string getHTMLSingleStep(string host);
string name(){return "ClassFlowAlignment";};
};
#endif //CLASSFLOWALIGNMENT_H

File diff suppressed because it is too large Load Diff

View File

@@ -11,10 +11,10 @@ enum t_CNNType {
AutoDetect,
Analogue,
Analogue100,
Digit,
DigitHyprid10,
Digital,
DigitalHyprid10,
DoubleHyprid10,
Digit100,
Digital100,
None
};
@@ -25,6 +25,16 @@ protected:
t_CNNType CNNType;
std::vector<general*> GENERAL;
float CNNGoodThreshold;
std::string cnn_name = "ClassFlowCNNGeneral";
//moved to define.h
//float Analog_error = 3.0;
//float AnalogToDigtalFehler = 0.8;
//float Digital_Uncertainty = 0.2;
//int DigitalBand = 3;
//float Digital_Transition_Range_Predecessor = 2;
//float Digital_Transition_Area_Predecessor = 0.7; // 9.3 - 0.7
//float Digital_Transition_Area_Forward = 9.7; // Pre-run zero crossing only happens from approx. 9.7 onwards
string cnnmodelfile;
int modelxsize, modelysize, modelchannel;
@@ -35,8 +45,8 @@ protected:
bool SaveAllFiles;
int PointerEvalAnalogNew(float zahl, int numeral_preceder);
int PointerEvalAnalogToDigitNew(float zahl, float numeral_preceder, int eval_predecessors, float AnalogToDigitTransitionStart);
int PointerEvalHybridNew(float zahl, float number_of_predecessors, int eval_predecessors, bool Analog_Predecessors = false, float AnalogToDigitTransitionStart=9.2);
int PointerEvalAnalogToDigitNew(float zahl, float numeral_preceder, int eval_predecessors, float analogDigitalTransitionStart);
int PointerEvalHybridNew(float zahl, float number_of_predecessors, int eval_predecessors, bool Analog_Predecessors = false, float analogDigitalTransitionStart=9.2);
@@ -47,12 +57,13 @@ protected:
public:
ClassFlowCNNGeneral(ClassFlowAlignment *_flowalign, t_CNNType _cnntype = AutoDetect);
ClassFlowCNNGeneral(ClassFlowAlignment *_flowalign, std::string _cnn_name);
bool ReadParameter(FILE* pfile, string& aktparamgraph);
bool doFlow(string time);
string getHTMLSingleStep(string host);
string getReadout(int _analog, bool _extendedResolution = false, int prev = -1, float _before_narrow_Analog = -1, float AnalogToDigitTransitionStart=9.2);
string getReadout(int _analog, bool _extendedResolution = false, int prev = -1, float _before_narrow_Analog = -1, float analogDigitalTransitionStart=9.2);
string getReadoutRawString(int _analog);
@@ -72,7 +83,7 @@ public:
t_CNNType getCNNType(){return CNNType;};
string name(){return "ClassFlowCNNGeneral";};
string name(){return "ClassFlowCNNGeneral " + cnn_name;};
};
#endif

View File

@@ -24,15 +24,16 @@ extern "C" {
#include "server_mqtt.h"
#endif //ENABLE_MQTT
#include "websocket.h"
#include "server_help.h"
#include "MainFlowControl.h"
#include "basic_auth.h"
#include "../../include/defines.h"
static const char* TAG = "FLOWCTRL";
//#define DEBUG_DETAIL_ON
std::string ClassFlowControll::doSingleStep(std::string _stepname, std::string _host){
std::string _classname = "";
std::string result = "";
@@ -65,19 +66,11 @@ std::string ClassFlowControll::doSingleStep(std::string _stepname, std::string _
_classname = "ClassFlowInfluxDBv2";
}
#endif //ENABLE_INFLUXDB
#ifdef ENABLE_WEBHOOK
if ((_stepname.compare("[Webhook]") == 0) || (_stepname.compare(";[Webhook]") == 0)){
_classname = "ClassFlowWebhook";
}
#endif //ENABLE_WEBHOOK
for (int i = 0; i < FlowControll.size(); ++i)
if (FlowControll[i]->name().compare(_classname) == 0){
if (!(FlowControll[i]->name().compare("ClassFlowTakeImage") == 0)) {
// if it is a TakeImage, the image does not need to be included, this happens automatically with the html query.
if (!(FlowControll[i]->name().compare("ClassFlowTakeImage") == 0)) // if it is a TakeImage, the image does not need to be included, this happens automatically with the html query.
FlowControll[i]->doFlow("");
}
result = FlowControll[i]->getHTMLSingleStep(_host);
}
@@ -86,51 +79,39 @@ std::string ClassFlowControll::doSingleStep(std::string _stepname, std::string _
return result;
}
std::string ClassFlowControll::TranslateAktstatus(std::string _input)
{
if (_input.compare("ClassFlowTakeImage") == 0) {
if (_input.compare("ClassFlowTakeImage") == 0)
return ("Take Image");
}
if (_input.compare("ClassFlowAlignment") == 0) {
if (_input.compare("ClassFlowAlignment") == 0)
return ("Aligning");
}
if (_input.compare("ClassFlowCNNGeneral") == 0) {
return ("Digitization of ROIs");
}
if (_input.compare("ClassFlowCNNGeneral Digital") == 0)
return ("Digitalization of Digital ROIs");
if (_input.compare("ClassFlowCNNGeneral Analog") == 0)
return ("Digitalization of Analog ROIs");
#ifdef ENABLE_MQTT
if (_input.compare("ClassFlowMQTT") == 0) {
if (_input.compare("ClassFlowMQTT") == 0)
return ("Sending MQTT");
}
#endif //ENABLE_MQTT
#ifdef ENABLE_INFLUXDB
if (_input.compare("ClassFlowInfluxDB") == 0) {
if (_input.compare("ClassFlowInfluxDB") == 0)
return ("Sending InfluxDB");
}
if (_input.compare("ClassFlowInfluxDBv2") == 0) {
if (_input.compare("ClassFlowInfluxDBv2") == 0)
return ("Sending InfluxDBv2");
}
#endif //ENABLE_INFLUXDB
#ifdef ENABLE_WEBHOOK
if (_input.compare("ClassFlowWebhook") == 0) {
return ("Sending Webhook");
}
#endif //ENABLE_WEBHOOK
if (_input.compare("ClassFlowPostProcessing") == 0) {
if (_input.compare("ClassFlowPostProcessing") == 0)
return ("Post-Processing");
}
return "Unkown Status";
return "Unkown Status: " + _input +"";
}
std::vector<HTMLInfo*> ClassFlowControll::GetAllDigit()
std::vector<HTMLInfo*> ClassFlowControll::GetAllDigital()
{
if (flowdigit) {
ESP_LOGD(TAG, "ClassFlowControll::GetAllDigit - flowdigit != NULL");
if (flowdigit)
{
ESP_LOGD(TAG, "ClassFlowControll::GetAllDigital - flowdigit != NULL");
return flowdigit->GetHTMLInfo();
}
@@ -138,66 +119,68 @@ std::vector<HTMLInfo*> ClassFlowControll::GetAllDigit()
return empty;
}
std::vector<HTMLInfo*> ClassFlowControll::GetAllAnalog()
{
if (flowanalog) {
if (flowanalog)
return flowanalog->GetHTMLInfo();
}
std::vector<HTMLInfo*> empty;
return empty;
}
t_CNNType ClassFlowControll::GetTypeDigit()
t_CNNType ClassFlowControll::GetTypeDigital()
{
if (flowdigit) {
if (flowdigit)
return flowdigit->getCNNType();
}
return t_CNNType::None;
}
t_CNNType ClassFlowControll::GetTypeAnalog()
{
if (flowanalog) {
if (flowanalog)
return flowanalog->getCNNType();
}
return t_CNNType::None;
}
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
void ClassFlowControll::DigitDrawROI(CImageBasis *_zw)
void ClassFlowControll::DigitalDrawROI(CImageBasis *_zw)
{
if (flowdigit) {
if (flowdigit)
flowdigit->DrawROI(_zw);
}
}
void ClassFlowControll::AnalogDrawROI(CImageBasis *_zw)
{
if (flowanalog) {
if (flowanalog)
flowanalog->DrawROI(_zw);
}
}
#endif
#ifdef ENABLE_MQTT
bool ClassFlowControll::StartMQTTService()
{
/* Start the MQTT service */
for (int i = 0; i < FlowControll.size(); ++i) {
if (FlowControll[i]->name().compare("ClassFlowMQTT") == 0) {
return ((ClassFlowMQTT*) (FlowControll[i]))->Start(AutoInterval);
}
}
for (int i = 0; i < FlowControll.size(); ++i) {
if (FlowControll[i]->name().compare("ClassFlowMQTT") == 0) {
return ((ClassFlowMQTT*) (FlowControll[i]))->Start(AutoInterval);
}
}
return false;
}
#endif //ENABLE_MQTT
void ClassFlowControll::SetInitialParameter(void)
{
AutoStart = true;
AutoStart = false;
SetupModeActive = false;
AutoInterval = 10; // Minutes
flowdigit = NULL;
@@ -207,12 +190,14 @@ void ClassFlowControll::SetInitialParameter(void)
aktRunNr = 0;
aktstatus = "Flow task not yet created";
aktstatusWithTime = aktstatus;
schedule_websocket_message("{\"state\": \"" + aktstatus + "\"}");
}
bool ClassFlowControll::getIsAutoStart(void)
{
//return AutoStart;
return true; // Flow must always be enabled, else the manual trigger (REST, MQTT) will not work!
return AutoStart;
}
@@ -221,86 +206,76 @@ void ClassFlowControll::setAutoStartInterval(long &_interval)
_interval = AutoInterval * 60 * 1000; // AutoInterval: minutes -> ms
}
ClassFlow* ClassFlowControll::CreateClassFlow(std::string _type)
{
ClassFlow* cfc = NULL;
_type = trim(_type);
if (toUpper(_type).compare("[TAKEIMAGE]") == 0) {
if (toUpper(_type).compare("[TAKEIMAGE]") == 0)
{
cfc = new ClassFlowTakeImage(&FlowControll);
flowtakeimage = (ClassFlowTakeImage*) cfc;
}
if (toUpper(_type).compare("[ALIGNMENT]") == 0) {
if (toUpper(_type).compare("[ALIGNMENT]") == 0)
{
cfc = new ClassFlowAlignment(&FlowControll);
flowalignment = (ClassFlowAlignment*) cfc;
}
if (toUpper(_type).compare("[ANALOG]") == 0) {
cfc = new ClassFlowCNNGeneral(flowalignment);
if (toUpper(_type).compare("[ANALOG]") == 0)
{
cfc = new ClassFlowCNNGeneral(flowalignment, std::string("Analog"));
flowanalog = (ClassFlowCNNGeneral*) cfc;
}
if (toUpper(_type).compare(0, 7, "[DIGITS") == 0) {
cfc = new ClassFlowCNNGeneral(flowalignment);
if (toUpper(_type).compare(0, 7, "[DIGITS") == 0)
{
cfc = new ClassFlowCNNGeneral(flowalignment, std::string("Digit"));
flowdigit = (ClassFlowCNNGeneral*) cfc;
}
#ifdef ENABLE_MQTT
if (toUpper(_type).compare("[MQTT]") == 0) {
if (toUpper(_type).compare("[MQTT]") == 0)
cfc = new ClassFlowMQTT(&FlowControll);
}
#endif //ENABLE_MQTT
#ifdef ENABLE_INFLUXDB
if (toUpper(_type).compare("[INFLUXDB]") == 0) {
if (toUpper(_type).compare("[INFLUXDB]") == 0)
cfc = new ClassFlowInfluxDB(&FlowControll);
}
if (toUpper(_type).compare("[INFLUXDBV2]") == 0) {
if (toUpper(_type).compare("[INFLUXDBV2]") == 0)
cfc = new ClassFlowInfluxDBv2(&FlowControll);
}
#endif //ENABLE_INFLUXDB
#ifdef ENABLE_WEBHOOK
if (toUpper(_type).compare("[WEBHOOK]") == 0)
cfc = new ClassFlowWebhook(&FlowControll);
#endif //ENABLE_WEBHOOK
if (toUpper(_type).compare("[POSTPROCESSING]") == 0) {
if (toUpper(_type).compare("[POSTPROCESSING]") == 0)
{
cfc = new ClassFlowPostProcessing(&FlowControll, flowanalog, flowdigit);
flowpostprocessing = (ClassFlowPostProcessing*) cfc;
}
if (cfc) {
// Attached only if it is not [AutoTimer], because this is for FlowControll
if (cfc) // Attached only if it is not [AutoTimer], because this is for FlowControll
FlowControll.push_back(cfc);
}
if (toUpper(_type).compare("[AUTOTIMER]") == 0) {
cfc = this;
}
if (toUpper(_type).compare("[AUTOTIMER]") == 0)
cfc = this;
if (toUpper(_type).compare("[DATALOGGING]") == 0) {
cfc = this;
}
if (toUpper(_type).compare("[DATALOGGING]") == 0)
cfc = this;
if (toUpper(_type).compare("[DEBUG]") == 0) {
cfc = this;
}
if (toUpper(_type).compare("[DEBUG]") == 0)
cfc = this;
if (toUpper(_type).compare("[SYSTEM]") == 0) {
cfc = this;
}
if (toUpper(_type).compare("[SYSTEM]") == 0)
cfc = this;
return cfc;
}
void ClassFlowControll::InitFlow(std::string config)
{
aktstatus = "Initialization";
aktstatusWithTime = aktstatus;
schedule_websocket_message("{\"state\": \"" + aktstatus + "\"}");
//#ifdef ENABLE_MQTT
//MQTTPublish(mqttServer_getMainTopic() + "/" + "status", "Initialization", 1, false); // Right now, not possible -> MQTT Service is going to be started later
//#endif //ENABLE_MQTT
@@ -316,55 +291,64 @@ void ClassFlowControll::InitFlow(std::string config)
line = "";
char zw[1024];
if (pFile != NULL) {
if (pFile != NULL)
{
fgets(zw, 1024, pFile);
ESP_LOGD(TAG, "%s", zw);
line = std::string(zw);
}
while ((line.size() > 0) && !(feof(pFile))) {
while ((line.size() > 0) && !(feof(pFile)))
{
cfc = CreateClassFlow(line);
// printf("Name: %s\n", cfc->name().c_str());
if (cfc) {
ESP_LOGE(TAG, "Start ReadParameter (%s)", line.c_str());
// printf("Name: %s\n", cfc->name().c_str());
if (cfc)
{
ESP_LOGD(TAG, "Start ReadParameter (%s)", line.c_str());
cfc->ReadParameter(pFile, line);
}
else {
else
{
line = "";
if (fgets(zw, 1024, pFile) && !feof(pFile)) {
ESP_LOGD(TAG, "Read: %s", zw);
line = std::string(zw);
}
if (fgets(zw, 1024, pFile) && !feof(pFile))
{
ESP_LOGD(TAG, "Read: %s", zw);
line = std::string(zw);
}
}
}
fclose(pFile);
}
std::string* ClassFlowControll::getActStatusWithTime()
{
return &aktstatusWithTime;
}
std::string* ClassFlowControll::getActStatus()
{
return &aktstatus;
}
void ClassFlowControll::setActStatus(std::string _aktstatus)
{
aktstatus = _aktstatus;
aktstatusWithTime = aktstatus;
schedule_websocket_message("{\"state\": \"" + aktstatus + "\"}");
}
void ClassFlowControll::doFlowTakeImageOnly(string time)
{
std::string zw_time;
for (int i = 0; i < FlowControll.size(); ++i) {
for (int i = 0; i < FlowControll.size(); ++i)
{
if (FlowControll[i]->name() == "ClassFlowTakeImage") {
zw_time = getCurrentTimeString("%H:%M:%S");
aktstatus = TranslateAktstatus(FlowControll[i]->name());
@@ -372,12 +356,15 @@ void ClassFlowControll::doFlowTakeImageOnly(string time)
#ifdef ENABLE_MQTT
MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, 1, false);
#endif //ENABLE_MQTT
schedule_websocket_message("{\"state\": \"" + aktstatus + "\"}");
FlowControll[i]->doFlow(time);
}
}
}
bool ClassFlowControll::doFlow(string time)
{
bool result = true;
@@ -397,11 +384,13 @@ bool ClassFlowControll::doFlow(string time)
//checkNtpStatus(0);
for (int i = 0; i < FlowControll.size(); ++i) {
for (int i = 0; i < FlowControll.size(); ++i)
{
zw_time = getCurrentTimeString("%H:%M:%S");
aktstatus = TranslateAktstatus(FlowControll[i]->name());
aktstatusWithTime = aktstatus + " (" + zw_time + ")";
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Status: " + aktstatusWithTime);
schedule_websocket_message("{\"state\": \"" + aktstatus + "\"}");
#ifdef ENABLE_MQTT
MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, qos, false);
#endif //ENABLE_MQTT
@@ -414,7 +403,7 @@ bool ClassFlowControll::doFlow(string time)
if (!FlowControll[i]->doFlow(time)){
repeat++;
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Fehler im vorheriger Schritt - wird zum " + to_string(repeat) + ". Mal wiederholt");
if (i) { i -= 1; } // vPrevious step must be repeated (probably take pictures)
if (i) i -= 1; // vPrevious step must be repeated (probably take pictures)
result = false;
if (repeat > 5) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Wiederholung 5x nicht erfolgreich --> reboot");
@@ -422,7 +411,8 @@ bool ClassFlowControll::doFlow(string time)
//Step was repeated 5x --> reboot
}
}
else {
else
{
result = true;
}
@@ -435,6 +425,7 @@ bool ClassFlowControll::doFlow(string time)
aktstatus = "Flow finished";
aktstatusWithTime = aktstatus + " (" + zw_time + ")";
//LogFile.WriteToFile(ESP_LOG_INFO, TAG, aktstatusWithTime);
schedule_websocket_message("{\"state\": \"" + aktstatus + "\"}");
#ifdef ENABLE_MQTT
MQTTPublish(mqttServer_getMainTopic() + "/" + "status", aktstatus, qos, false);
#endif //ENABLE_MQTT
@@ -446,29 +437,27 @@ bool ClassFlowControll::doFlow(string time)
string ClassFlowControll::getReadoutAll(int _type)
{
std::string out = "";
if (flowpostprocessing) {
if (flowpostprocessing)
{
std::vector<NumberPost*> *numbers = flowpostprocessing->GetNumbers();
for (int i = 0; i < (*numbers).size(); ++i) {
for (int i = 0; i < (*numbers).size(); ++i)
{
out = out + (*numbers)[i]->name + "\t";
switch (_type) {
case READOUT_TYPE_VALUE:
out = out + (*numbers)[i]->ReturnValue;
break;
case READOUT_TYPE_PREVALUE:
if (flowpostprocessing->PreValueUse) {
if ((*numbers)[i]->PreValueOkay) {
if (flowpostprocessing->PreValueUse)
{
if ((*numbers)[i]->PreValueOkay)
out = out + (*numbers)[i]->ReturnPreValue;
}
else {
out = out + "PreValue too old";
}
else
out = out + "PreValue too old";
}
else {
else
out = out + "PreValue deactivated";
}
break;
case READOUT_TYPE_RAWVALUE:
out = out + (*numbers)[i]->ReturnRawValue;
@@ -477,10 +466,8 @@ string ClassFlowControll::getReadoutAll(int _type)
out = out + (*numbers)[i]->ErrorMessageText;
break;
}
if (i < (*numbers).size()-1) {
if (i < (*numbers).size()-1)
out = out + "\r\n";
}
}
// ESP_LOGD(TAG, "OUT: %s", out.c_str());
}
@@ -488,24 +475,43 @@ string ClassFlowControll::getReadoutAll(int _type)
return out;
}
string ClassFlowControll::getReadout(bool _rawvalue = false, bool _noerror = false, int _number = 0)
{
if (flowpostprocessing) {
if (flowpostprocessing)
return flowpostprocessing->getReadoutParam(_rawvalue, _noerror, _number);
string zw = "";
string result = "";
for (int i = 0; i < FlowControll.size(); ++i)
{
zw = FlowControll[i]->getReadout();
if (zw.length() > 0)
{
if (result.length() == 0)
result = zw;
else
result = result + "\t" + zw;
}
}
return std::string("");
return result;
}
string ClassFlowControll::GetPrevalue(std::string _number)
{
if (flowpostprocessing) {
if (flowpostprocessing)
{
return flowpostprocessing->GetPreValue(_number);
}
return std::string("");
}
bool ClassFlowControll::UpdatePrevalue(std::string _newvalue, std::string _numbers, bool _extern)
{
double newvalueAsDouble;
@@ -526,12 +532,10 @@ bool ClassFlowControll::UpdatePrevalue(std::string _newvalue, std::string _numbe
}
if (flowpostprocessing) {
if (flowpostprocessing->SetPreValue(newvalueAsDouble, _numbers, _extern)) {
if (flowpostprocessing->SetPreValue(newvalueAsDouble, _numbers, _extern))
return true;
}
else {
else
return false;
}
}
else {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "UpdatePrevalue: ERROR - Class Post-Processing not initialized");
@@ -539,81 +543,93 @@ bool ClassFlowControll::UpdatePrevalue(std::string _newvalue, std::string _numbe
}
}
bool ClassFlowControll::ReadParameter(FILE* pfile, string& aktparamgraph)
{
std::vector<string> splitted;
aktparamgraph = trim(aktparamgraph);
if (aktparamgraph.size() == 0) {
if (!this->GetNextParagraph(pfile, aktparamgraph)) {
if (aktparamgraph.size() == 0)
if (!this->GetNextParagraph(pfile, aktparamgraph))
return false;
}
}
if ((toUpper(aktparamgraph).compare("[AUTOTIMER]") != 0) && (toUpper(aktparamgraph).compare("[DEBUG]") != 0) &&
(toUpper(aktparamgraph).compare("[SYSTEM]") != 0 && (toUpper(aktparamgraph).compare("[DATALOGGING]") != 0))) {
// Paragraph passt nicht zu Debug oder DataLogging
(toUpper(aktparamgraph).compare("[SYSTEM]") != 0 && (toUpper(aktparamgraph).compare("[DATALOGGING]") != 0))) // Paragraph passt nicht zu Debug oder DataLogging
return false;
}
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph)) {
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
{
splitted = ZerlegeZeile(aktparamgraph, " =");
if ((toUpper(splitted[0]) == "INTERVAL") && (splitted.size() > 1)) {
if (isStringNumeric(splitted[1]))
if ((toUpper(splitted[0]) == "AUTOSTART") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
{
AutoInterval = std::stof(splitted[1]);
AutoStart = true;
}
}
if ((toUpper(splitted[0]) == "DATALOGACTIVE") && (splitted.size() > 1)) {
LogFile.SetDataLogToSD(alphanumericToBoolean(splitted[1]));
if ((toUpper(splitted[0]) == "INTERVAL") && (splitted.size() > 1))
{
AutoInterval = std::stof(splitted[1]);
}
if ((toUpper(splitted[0]) == "DATAFILESRETENTION") && (splitted.size() > 1)) {
if (isStringNumeric(splitted[1]))
if ((toUpper(splitted[0]) == "DATALOGACTIVE") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
{
LogFile.SetDataLogRetention(std::stoi(splitted[1]));
LogFile.SetDataLogToSD(true);
}
else {
LogFile.SetDataLogToSD(false);
}
}
if ((toUpper(splitted[0]) == "LOGLEVEL") && (splitted.size() > 1)) {
if ((toUpper(splitted[0]) == "DATAFILESRETENTION") && (splitted.size() > 1))
{
LogFile.SetDataLogRetention(std::stoi(splitted[1]));
}
if ((toUpper(splitted[0]) == "LOGLEVEL") && (splitted.size() > 1))
{
/* matches esp_log_level_t */
if ((toUpper(splitted[1]) == "TRUE") || (toUpper(splitted[1]) == "2")) {
if ((toUpper(splitted[1]) == "TRUE") || (toUpper(splitted[1]) == "2"))
{
LogFile.setLogLevel(ESP_LOG_WARN);
}
else if ((toUpper(splitted[1]) == "FALSE") || (toUpper(splitted[1]) == "0") || (toUpper(splitted[1]) == "1")) {
else if ((toUpper(splitted[1]) == "FALSE") || (toUpper(splitted[1]) == "0") || (toUpper(splitted[1]) == "1"))
{
LogFile.setLogLevel(ESP_LOG_ERROR);
}
else if (toUpper(splitted[1]) == "3") {
else if (toUpper(splitted[1]) == "3")
{
LogFile.setLogLevel(ESP_LOG_INFO);
}
else if (toUpper(splitted[1]) == "4") {
else if (toUpper(splitted[1]) == "4")
{
LogFile.setLogLevel(ESP_LOG_DEBUG);
}
/* If system reboot was not triggered by user and reboot was caused by execption -> keep log level to DEBUG */
if (!getIsPlannedReboot() && (esp_reset_reason() == ESP_RST_PANIC)) {
if (!getIsPlannedReboot() && (esp_reset_reason() == ESP_RST_PANIC))
LogFile.setLogLevel(ESP_LOG_DEBUG);
}
}
if ((toUpper(splitted[0]) == "LOGFILESRETENTION") && (splitted.size() > 1)) {
if (isStringNumeric(splitted[1]))
{
LogFile.SetLogFileRetention(std::stoi(splitted[1]));
}
if ((toUpper(splitted[0]) == "LOGFILESRETENTION") && (splitted.size() > 1))
{
LogFile.SetLogFileRetention(std::stoi(splitted[1]));
}
/* TimeServer and TimeZone got already read from the config, see setupTime () */
#if (defined WLAN_USE_ROAMING_BY_SCANNING || (defined WLAN_USE_MESH_ROAMING && defined WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES))
if ((toUpper(splitted[0]) == "RSSITHRESHOLD") && (splitted.size() > 1)) {
if ((toUpper(splitted[0]) == "RSSITHRESHOLD") && (splitted.size() > 1))
{
int RSSIThresholdTMP = atoi(splitted[1].c_str());
RSSIThresholdTMP = min(0, max(-100, RSSIThresholdTMP)); // Verify input limits (-100 - 0)
if (ChangeRSSIThreshold(WLAN_CONFIG_FILE, RSSIThresholdTMP)) {
if (ChangeRSSIThreshold(WLAN_CONFIG_FILE, RSSIThresholdTMP))
{
// reboot necessary so that the new wlan.ini is also used !!!
fclose(pfile);
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Rebooting to activate new RSSITHRESHOLD ...");
@@ -622,8 +638,10 @@ bool ClassFlowControll::ReadParameter(FILE* pfile, string& aktparamgraph)
}
#endif
if ((toUpper(splitted[0]) == "HOSTNAME") && (splitted.size() > 1)) {
if (ChangeHostName(WLAN_CONFIG_FILE, splitted[1])) {
if ((toUpper(splitted[0]) == "HOSTNAME") && (splitted.size() > 1))
{
if (ChangeHostName(WLAN_CONFIG_FILE, splitted[1]))
{
// reboot necessary so that the new wlan.ini is also used !!!
fclose(pfile);
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Rebooting to activate new HOSTNAME...");
@@ -631,19 +649,23 @@ bool ClassFlowControll::ReadParameter(FILE* pfile, string& aktparamgraph)
}
}
if ((toUpper(splitted[0]) == "SETUPMODE") && (splitted.size() > 1)) {
SetupModeActive = alphanumericToBoolean(splitted[1]);
if ((toUpper(splitted[0]) == "SETUPMODE") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
{
SetupModeActive = true;
}
}
}
return true;
}
int ClassFlowControll::CleanTempFolder() {
const char* folderPath = "/sdcard/img_tmp";
ESP_LOGD(TAG, "Clean up temporary folder to avoid damage of sdcard sectors: %s", folderPath);
DIR *dir = opendir(folderPath);
if (!dir) {
ESP_LOGE(TAG, "Failed to stat dir: %s", folderPath);
return -1;
@@ -651,33 +673,31 @@ int ClassFlowControll::CleanTempFolder() {
struct dirent *entry;
int deleted = 0;
while ((entry = readdir(dir)) != NULL) {
std::string path = string(folderPath) + "/" + entry->d_name;
if (entry->d_type == DT_REG) {
if (unlink(path.c_str()) == 0) {
deleted ++;
}
else {
ESP_LOGE(TAG, "can't delete file: %s", path.c_str());
}
}
else if (entry->d_type == DT_DIR) {
deleted += removeFolder(path.c_str(), TAG);
}
if (entry->d_type == DT_REG) {
if (unlink(path.c_str()) == 0) {
deleted ++;
} else {
ESP_LOGE(TAG, "can't delete file: %s", path.c_str());
}
} else if (entry->d_type == DT_DIR) {
deleted += removeFolder(path.c_str(), TAG);
}
}
closedir(dir);
ESP_LOGD(TAG, "%d files deleted", deleted);
return 0;
}
esp_err_t ClassFlowControll::SendRawJPG(httpd_req_t *req)
{
return flowtakeimage != NULL ? flowtakeimage->SendRawJPG(req) : ESP_FAIL;
}
esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
{
ESP_LOGD(TAG, "ClassFlowControll::GetJPGStream %s", _fn.c_str());
@@ -839,8 +859,8 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
else {
std::vector<HTMLInfo*> htmlinfo;
htmlinfo = GetAllDigit();
ESP_LOGD(TAG, "After getClassFlowControll::GetAllDigit");
htmlinfo = GetAllDigital();
ESP_LOGD(TAG, "After getClassFlowControll::GetAllDigital");
for (int i = 0; i < htmlinfo.size(); ++i)
{
@@ -909,20 +929,14 @@ esp_err_t ClassFlowControll::GetJPGStream(std::string _fn, httpd_req_t *req)
return result;
}
string ClassFlowControll::getNumbersName()
{
return flowpostprocessing->getNumbersName();
}
string ClassFlowControll::getJSON()
{
return flowpostprocessing->GetJSON();
}
/**
* @returns a vector of all current sequences
**/
const std::vector<NumberPost*> &ClassFlowControll::getNumbers()
{
return *flowpostprocessing->GetNumbers();
}

View File

@@ -17,9 +17,6 @@
#include "ClassFlowInfluxDB.h"
#include "ClassFlowInfluxDBv2.h"
#endif //ENABLE_INFLUXDB
#ifdef ENABLE_WEBHOOK
#include "ClassFlowWebhook.h"
#endif //ENABLE_WEBHOOK
#include "ClassFlowCNNGeneral.h"
class ClassFlowControll :
@@ -37,14 +34,13 @@ protected:
bool AutoStart;
float AutoInterval;
bool SetupModeActive;
void SetInitialParameter(void);
std::string aktstatusWithTime;
std::string aktstatus;
int aktRunNr;
public:
bool SetupModeActive;
void InitFlow(std::string config);
bool doFlow(string time);
void doFlowTakeImageOnly(string time);
@@ -55,13 +51,12 @@ public:
string GetPrevalue(std::string _number = "");
bool ReadParameter(FILE* pfile, string& aktparamgraph);
string getJSON();
const std::vector<NumberPost*> &getNumbers();
string getNumbersName();
string TranslateAktstatus(std::string _input);
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
void DigitDrawROI(CImageBasis *_zw);
void DigitalDrawROI(CImageBasis *_zw);
void AnalogDrawROI(CImageBasis *_zw);
#endif
@@ -77,10 +72,10 @@ public:
std::string* getActStatus();
void setActStatus(std::string _aktstatus);
std::vector<HTMLInfo*> GetAllDigit();
std::vector<HTMLInfo*> GetAllDigital();
std::vector<HTMLInfo*> GetAllAnalog();
t_CNNType GetTypeDigit();
t_CNNType GetTypeDigital();
t_CNNType GetTypeAnalog();
#ifdef ENABLE_MQTT

View File

@@ -5,10 +5,6 @@
#include "ClassFlowImage.h"
/**
* Properties of one ROI
* FIXME: naming of members could use some refactoring to comply with common C++ coding style guidelines
*/
struct roi {
int posx, posy, deltax, deltay;
float result_float;
@@ -18,68 +14,55 @@ struct roi {
CImageBasis *image, *image_org;
};
/**
* FIXME: Why is this additional layer needed?
*/
struct general {
string name;
std::vector<roi*> ROI;
};
enum t_RateType {
AbsoluteChange, // ignores the time difference; only the value difference is used comparison with NumberPost.maxRate
RateChange // time difference is considered and a normalized rate is used for comparison with NumberPost.maxRate
AbsoluteChange,
RateChange
};
/**
* Holds all properties and settings of a sequence. A sequence is a set of digit and/or analog ROIs that are combined to
* provide one meter reading (value).
* FIXME: can be renamed to `Sequence`
*/
struct NumberPost {
float MaxRateValue; // maxRate; upper bound for the difference between two consecutive readings; affected by maxRateType;
bool useMaxRateValue; // consistencyChecksEnabled; enables consistency checks; uses maxRate and maxRateType
t_RateType MaxRateType; // maxRateType; affects how the value of maxRate is used for comparing the current and previous value
bool ErrorMessage; // FIXME: not used; can be removed
int ChangeRateThreshold; // threshold parameter for negative rate detection
bool PreValueOkay; // previousValueValid; indicates that the reading of the previous round has no errors
bool AllowNegativeRates; // allowNegativeRate; defines if the consistency checks allow negative rates between consecutive meter readings.
bool checkDigitIncreaseConsistency; // extendedConsistencyCheck; performs an additional consistency check to avoid wrong readings
time_t timeStampLastValue; // Timestamp for the last read value; is used for the log
time_t timeStampLastPreValue; // Timestamp for the last PreValue set; is used for useMaxRateValue
time_t timeStampTimeUTC; // FIXME: not used; can be removed.
string timeStamp; // localTimeStr; timestamp of last valid reading formatted as local time
double FlowRateAct; // currentRate; ΔValue/min; since usage is not limited to water meters, the physical unit is not known.
double PreValue; // lastValidValue; most recent value that could be read w/o any errors
double Value; // value; most recent readout; may include corrections
string ReturnRateValue; // currentRateStr; current normalized rate; ΔValue/min
string ReturnChangeAbsolute; // currentChangeStr; absolute difference between current and previous measurement
string ReturnRawValue; // rawValueStr; Raw value (with N & leading 0)
string ReturnValue; // valueStr; corrected return value, if necessary with error message
string ReturnPreValue; // lastValidValueStr; corrected return value without error message
string ErrorMessageText; // errorMessage; Error message for consistency checks
int AnzahlAnalog; // numAnalogRoi; number of analog ROIs used in this sequence
int AnzahlDigit; // numDigitRoi; number of digit ROIs used in this sequence
int DecimalShift; // decimalShift; each increment shifts the decimal separator by one digit; value=value*10^decimalShift; pos. value shifts to the right
int DecimalShiftInitial; // decimalShiftInitial; same as decimalShift but is a const to reset decimalShift after calculations
float AnalogToDigitTransitionStart; // AnalogToDigitTransitionStartValue; FIXME: need a better description; When is the digit > x.1, i.e. when does it start to tilt?
int Nachkomma; // decimalPlaces; usually defined by the number of analog ROIs; affected by DecimalShift
float MaxRateValue;
bool useMaxRateValue;
t_RateType RateType;
bool ErrorMessage;
bool PreValueOkay;
bool AllowNegativeRates;
bool checkDigitIncreaseConsistency;
time_t lastvalue;
string timeStamp;
double FlowRateAct; // m3 / min
double PreValue; // last value that was read out well
double Value; // last value read out, incl. corrections
string ReturnRateValue; // return value rate
string ReturnChangeAbsolute; // return value rate
string ReturnRawValue; // Raw value (with N & leading 0)
string ReturnValue; // corrected return value, if necessary with error message
string ReturnPreValue; // corrected return value without error message
string ErrorMessageText; // Error message for consistency check
int AnzahlAnalog;
int AnzahlDigital;
int DecimalShift;
int DecimalShiftInitial;
float AnalogDigitalTransitionStart; // When is the digit > x.1, i.e. when does it start to tilt?
int Nachkomma;
string DomoticzIdx; // Domoticz counter Idx
string FieldV1; // influxdbFieldName_v1; Name of the Field in InfluxDBv1
string MeasurementV1; // influxdbMeasurementName_v1; Name of the Measurement in InfluxDBv1
string FieldV1; // Fieldname in InfluxDBv1
string MeasurementV1; // Measurement in InfluxDBv1
string FieldV2; // influxdbFieldName_v2; Name of the Field in InfluxDBv2
string MeasurementV2; // influxdbMeasurementName_v2; Name of the Measurement in InfluxDBv2
string FieldV2; // Fieldname in InfluxDBv2
string MeasurementV2; // Measurement in InfluxDBv2
bool isExtendedResolution; // extendResolution; Adds the decimal place of the least significant analog ROI to the value
bool isExtendedResolution;
general *digit_roi; // digitRoi; set of digit ROIs for the sequence
general *analog_roi; // analogRoi; set of analog ROIs for the sequence
general *digit_roi;
general *analog_roi;
string name; // name; Designation for the sequence
string name;
};
#endif

View File

@@ -137,7 +137,6 @@ bool ClassFlowInfluxDB::doFlow(string zwtime)
std::string resultraw = "";
std::string resultrate = "";
std::string resulttimestamp = "";
long int timeutc;
string zw = "";
string namenumber = "";
@@ -153,7 +152,6 @@ bool ClassFlowInfluxDB::doFlow(string zwtime)
resulterror = (*NUMBERS)[i]->ErrorMessageText;
resultrate = (*NUMBERS)[i]->ReturnRateValue;
resulttimestamp = (*NUMBERS)[i]->timeStamp;
timeutc = (*NUMBERS)[i]->timeStampTimeUTC;
if ((*NUMBERS)[i]->FieldV1.length() > 0)
{
@@ -169,7 +167,7 @@ bool ClassFlowInfluxDB::doFlow(string zwtime)
}
if (result.length() > 0)
InfluxDBPublish(measurement, namenumber, result, timeutc);
InfluxDBPublish(measurement, namenumber, result, resulttimestamp);
}
}

View File

@@ -20,7 +20,7 @@ static const char* TAG = "INFLUXDBV2";
void ClassFlowInfluxDBv2::SetInitialParameter(void)
{
uri = "";
bucket = "";
database = "";
dborg = "";
dbtoken = "";
// dbfield = "";
@@ -109,9 +109,9 @@ bool ClassFlowInfluxDBv2::ReadParameter(FILE* pfile, string& aktparamgraph)
{
handleMeasurement(splitted[0], splitted[1]);
}
if (((toUpper(splitted[0]) == "BUCKET")) && (splitted.size() > 1))
if (((toUpper(splitted[0]) == "DATABASE")) && (splitted.size() > 1))
{
this->bucket = splitted[1];
this->database = splitted[1];
}
}
@@ -119,11 +119,11 @@ bool ClassFlowInfluxDBv2::ReadParameter(FILE* pfile, string& aktparamgraph)
printf("org: %s\n", dborg.c_str());
printf("token: %s\n", dbtoken.c_str());
if ((uri.length() > 0) && (bucket.length() > 0) && (dbtoken.length() > 0) && (dborg.length() > 0))
if ((uri.length() > 0) && (database.length() > 0) && (dbtoken.length() > 0) && (dborg.length() > 0))
{
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init InfluxDB with uri: " + uri + ", org: " + dborg + ", token: *****");
// printf("vor V2 Init\n");
InfluxDB_V2_Init(uri, bucket, dborg, dbtoken);
InfluxDB_V2_Init(uri, database, dborg, dbtoken);
// printf("nach V2 Init\n");
InfluxDBenable = true;
} else {
@@ -196,7 +196,6 @@ bool ClassFlowInfluxDBv2::doFlow(string zwtime)
std::string resultraw = "";
std::string resultrate = "";
std::string resulttimestamp = "";
long int resulttimeutc = 0;
string zw = "";
string namenumber = "";
@@ -213,8 +212,6 @@ bool ClassFlowInfluxDBv2::doFlow(string zwtime)
resulterror = (*NUMBERS)[i]->ErrorMessageText;
resultrate = (*NUMBERS)[i]->ReturnRateValue;
resulttimestamp = (*NUMBERS)[i]->timeStamp;
resulttimeutc = (*NUMBERS)[i]->timeStampTimeUTC;
if ((*NUMBERS)[i]->FieldV2.length() > 0)
{
@@ -232,7 +229,8 @@ bool ClassFlowInfluxDBv2::doFlow(string zwtime)
printf("vor sende Influx_DB_V2 - namenumber. %s, result: %s, timestampt: %s", namenumber.c_str(), result.c_str(), resulttimestamp.c_str());
if (result.length() > 0)
InfluxDB_V2_Publish(measurement, namenumber, result, resulttimeutc);
InfluxDB_V2_Publish(measurement, namenumber, result, resulttimestamp);
// InfluxDB_V2_Publish(namenumber, result, resulttimestamp);
}
}

View File

@@ -15,7 +15,7 @@ class ClassFlowInfluxDBv2 :
public ClassFlow
{
protected:
std::string uri, bucket;
std::string uri, database;
std::string dborg, dbtoken, dbfield;
std::string OldValue;
ClassFlowPostProcessing* flowpostprocessing;

View File

@@ -9,6 +9,7 @@
#include "ClassLogFile.h"
#include "time_sntp.h"
#include "websocket.h"
#include "interface_mqtt.h"
#include "ClassFlowPostProcessing.h"
#include "ClassFlowControll.h"
@@ -37,9 +38,6 @@ void ClassFlowMQTT::SetInitialParameter(void)
topicUptime = "";
topicFreeMem = "";
caCertFilename = "";
clientCertFilename = "";
clientKeyFilename = "";
clientname = wlan_config.hostname;
OldValue = "";
@@ -51,7 +49,6 @@ void ClassFlowMQTT::SetInitialParameter(void)
ListFlowControll = NULL;
disabled = false;
keepAlive = 25*60;
domoticzintopic = "";
}
ClassFlowMQTT::ClassFlowMQTT()
@@ -106,44 +103,31 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
{
splitted = ZerlegeZeile(aktparamgraph);
std::string _param = GetParameterName(splitted[0]);
if ((toUpper(_param) == "CACERT") && (splitted.size() > 1))
{
this->caCertFilename = splitted[1];
}
if ((toUpper(_param) == "CLIENTCERT") && (splitted.size() > 1))
{
this->clientCertFilename = splitted[1];
}
if ((toUpper(_param) == "CLIENTKEY") && (splitted.size() > 1))
{
this->clientKeyFilename = splitted[1];
}
if ((toUpper(_param) == "USER") && (splitted.size() > 1))
if ((toUpper(splitted[0]) == "USER") && (splitted.size() > 1))
{
this->user = splitted[1];
}
if ((toUpper(_param) == "PASSWORD") && (splitted.size() > 1))
if ((toUpper(splitted[0]) == "PASSWORD") && (splitted.size() > 1))
{
this->password = splitted[1];
}
if ((toUpper(_param) == "URI") && (splitted.size() > 1))
if ((toUpper(splitted[0]) == "URI") && (splitted.size() > 1))
{
this->uri = splitted[1];
}
if ((toUpper(_param) == "RETAINMESSAGES") && (splitted.size() > 1))
if ((toUpper(splitted[0]) == "RETAINMESSAGES") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE") {
SetRetainFlag = true;
setMqtt_Server_Retain(SetRetainFlag);
}
}
if ((toUpper(_param) == "HOMEASSISTANTDISCOVERY") && (splitted.size() > 1))
if ((toUpper(splitted[0]) == "HOMEASSISTANTDISCOVERY") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
SetHomeassistantDiscoveryEnabled(true);
}
if ((toUpper(_param) == "METERTYPE") && (splitted.size() > 1)) {
if ((toUpper(splitted[0]) == "METERTYPE") && (splitted.size() > 1)) {
/* Use meter type for the device class
Make sure it is a listed one on https://developers.home-assistant.io/docs/core/entity/sensor/#available-device-classes */
if (toUpper(splitted[1]) == "WATER_M3") {
@@ -153,7 +137,7 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
mqttServer_setMeterType("water", "L", "h", "L/h");
}
else if (toUpper(splitted[1]) == "WATER_FT3") {
mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // m = Minutes
mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // Minutes
}
else if (toUpper(splitted[1]) == "WATER_GAL") {
mqttServer_setMeterType("water", "gal", "h", "gal/h");
@@ -162,7 +146,7 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
mqttServer_setMeterType("gas", "", "h", "m³/h");
}
else if (toUpper(splitted[1]) == "GAS_FT3") {
mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // m = Minutes
mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // Minutes
}
else if (toUpper(splitted[1]) == "ENERGY_WH") {
mqttServer_setMeterType("energy", "Wh", "h", "W");
@@ -178,26 +162,15 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
}
}
if ((toUpper(_param) == "CLIENTID") && (splitted.size() > 1))
if ((toUpper(splitted[0]) == "CLIENTID") && (splitted.size() > 1))
{
this->clientname = splitted[1];
}
if (((toUpper(_param) == "TOPIC") || (toUpper(splitted[0]) == "MAINTOPIC")) && (splitted.size() > 1))
if (((toUpper(splitted[0]) == "TOPIC") || (toUpper(splitted[0]) == "MAINTOPIC")) && (splitted.size() > 1))
{
maintopic = splitted[1];
}
if (((toUpper(_param) == "DOMOTICZTOPICIN")) && (splitted.size() > 1))
{
this->domoticzintopic = splitted[1];
}
if (((toUpper(_param) == "DOMOTICZIDX")) && (splitted.size() > 1))
{
handleIdx(splitted[0], splitted[1]);
}
}
/* Note:
@@ -206,7 +179,6 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
* To work around this, we delay the start and trigger it from ClassFlowControll::ReadParameter() */
mqttServer_setMainTopic(maintopic);
mqttServer_setDmoticzInTopic(domoticzintopic);
return true;
}
@@ -224,9 +196,8 @@ bool ClassFlowMQTT::Start(float AutoInterval)
mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, domoticzintopic, LWT_TOPIC, LWT_CONNECTED,
LWT_DISCONNECTED, caCertFilename, clientCertFilename, clientKeyFilename,
keepAlive, SetRetainFlag, (void *)&GotConnected);
bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, LWT_TOPIC, LWT_CONNECTED,
LWT_DISCONNECTED, keepAlive, SetRetainFlag, (void *)&GotConnected);
if (!MQTTConfigCheck) {
return false;
@@ -249,8 +220,6 @@ bool ClassFlowMQTT::doFlow(string zwtime)
std::string resultchangabs = "";
string zw = "";
string namenumber = "";
string domoticzpayload = "";
string DomoticzIdx = "";
int qos = 1;
/* Send the the Homeassistant Discovery and the Static Topics in case they where scheduled */
@@ -274,22 +243,22 @@ bool ClassFlowMQTT::doFlow(string zwtime)
resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
resulttimestamp = (*NUMBERS)[i]->timeStamp;
DomoticzIdx = (*NUMBERS)[i]->DomoticzIdx;
domoticzpayload = "{\"command\":\"udevice\",\"idx\":" + DomoticzIdx + ",\"svalue\":\""+ result + "\"}";
namenumber = (*NUMBERS)[i]->name;
if (namenumber == "default")
namenumber = maintopic + "/";
else
namenumber = maintopic + "/" + namenumber + "/";
if ((domoticzintopic.length() > 0) && (result.length() > 0))
success |= MQTTPublish(domoticzintopic, domoticzpayload, qos, SetRetainFlag);
if (result.length() > 0)
if (result.length() > 0) {
success |= MQTTPublish(namenumber + "value", result, qos, SetRetainFlag);
if (resulterror.length() > 0)
schedule_websocket_message("{\"value\": \"" + result + "\", \"number\": \"" + (*NUMBERS)[i]->name + "\"}");
}
if (resulterror.length() > 0) {
success |= MQTTPublish(namenumber + "error", resulterror, qos, SetRetainFlag);
schedule_websocket_message("{\"error\": \"" + resulterror + "\", \"number\": \"" + (*NUMBERS)[i]->name + "\"}");
}
if (resultrate.length() > 0) {
success |= MQTTPublish(namenumber + "rate", resultrate, qos, SetRetainFlag);
@@ -306,11 +275,13 @@ bool ClassFlowMQTT::doFlow(string zwtime)
if (resultchangabs.length() > 0) {
success |= MQTTPublish(namenumber + "changeabsolut", resultchangabs, qos, SetRetainFlag); // Legacy API
success |= MQTTPublish(namenumber + "rate_per_digitization_round", resultchangabs, qos, SetRetainFlag);
success |= MQTTPublish(namenumber + "rate_per_digitalization_round", resultchangabs, qos, SetRetainFlag);
}
if (resultraw.length() > 0)
if (resultraw.length() > 0) {
success |= MQTTPublish(namenumber + "raw", resultraw, qos, SetRetainFlag);
schedule_websocket_message("{\"raw\": \"" + resultraw + "\", \"number\": \"" + (*NUMBERS)[i]->name + "\"}");
}
if (resulttimestamp.length() > 0)
success |= MQTTPublish(namenumber + "timestamp", resulttimestamp, qos, SetRetainFlag);
@@ -345,26 +316,6 @@ bool ClassFlowMQTT::doFlow(string zwtime)
return true;
}
void ClassFlowMQTT::handleIdx(string _decsep, string _value)
{
string _digit, _decpos;
int _pospunkt = _decsep.find_first_of(".");
// ESP_LOGD(TAG, "Name: %s, Pospunkt: %d", _decsep.c_str(), _pospunkt);
if (_pospunkt > -1)
_digit = _decsep.substr(0, _pospunkt);
else
_digit = "default";
for (int j = 0; j < flowpostprocessing->NUMBERS.size(); ++j)
{
if (_digit == "default") // Set to default first (if nothing else is set)
{
flowpostprocessing->NUMBERS[j]->DomoticzIdx = _value;
}
if (flowpostprocessing->NUMBERS[j]->name == _digit)
{
flowpostprocessing->NUMBERS[j]->DomoticzIdx = _value;
}
}
}
#endif //ENABLE_MQTT

View File

@@ -19,13 +19,12 @@ protected:
std::string OldValue;
ClassFlowPostProcessing* flowpostprocessing;
std::string user, password;
std::string caCertFilename, clientCertFilename, clientKeyFilename;
bool SetRetainFlag;
int keepAlive; // Seconds
float roundInterval; // Minutes
std::string maintopic, domoticzintopic;
std::string maintopic;
void SetInitialParameter(void);
void handleIdx(string _decsep, string _value);
public:
ClassFlowMQTT();

View File

@@ -21,9 +21,11 @@ protected:
bool ErrorMessage;
bool IgnoreLeadingNaN; // SPECIAL CASE for User Gustl ???
ClassFlowCNNGeneral* flowAnalog;
ClassFlowCNNGeneral* flowDigit;
string FilePreValue;
ClassFlowTakeImage *flowTakeImage;
@@ -39,18 +41,21 @@ protected:
void handleMaxRateValue(string _decsep, string _value);
void handleDecimalExtendedResolution(string _decsep, string _value);
void handleMaxRateType(string _decsep, string _value);
void handleAnalogToDigitTransitionStart(string _decsep, string _value);
void handleAnalogDigitalTransitionStart(string _decsep, string _value);
void handleAllowNegativeRate(string _decsep, string _value);
void handleChangeRateThreshold(string _decsep, string _value);
std::string GetStringReadouts(general);
void WriteDataLog(int _index);
public:
bool PreValueUse;
std::vector<NumberPost*> NUMBERS;
ClassFlowPostProcessing(std::vector<ClassFlow*>* lfc, ClassFlowCNNGeneral *_analog, ClassFlowCNNGeneral *_digit);
virtual ~ClassFlowPostProcessing(){};
bool ReadParameter(FILE* pfile, string& aktparamgraph);

View File

@@ -1,15 +1,9 @@
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include "ClassFlowTakeImage.h"
#include "Helper.h"
#include "ClassLogFile.h"
#include "CImageBasis.h"
#include "ClassControllCamera.h"
#include "MainFlowControl.h"
#include "esp_wifi.h"
#include "esp_log.h"
@@ -18,14 +12,14 @@
#include <time.h>
// #define DEBUG_DETAIL_ON
// #define DEBUG_DETAIL_ON
// #define WIFITURNOFF
static const char *TAG = "TAKEIMAGE";
static const char* TAG = "TAKEIMAGE";
esp_err_t ClassFlowTakeImage::camera_capture(void)
{
string nm = namerawimage;
esp_err_t ClassFlowTakeImage::camera_capture(){
string nm = namerawimage;
Camera.CaptureToFile(nm);
time(&TimeImageTaken);
localtime(&TimeImageTaken);
@@ -36,500 +30,150 @@ esp_err_t ClassFlowTakeImage::camera_capture(void)
void ClassFlowTakeImage::takePictureWithFlash(int flash_duration)
{
// in case the image is flipped, it must be reset here //
rawImage->width = CCstatus.ImageWidth;
rawImage->height = CCstatus.ImageHeight;
rawImage->width = image_width;
rawImage->height = image_height;
/////////////////////////////////////////////////////////////////////////////////////
ESP_LOGD(TAG, "flash_duration: %d", flash_duration);
Camera.CaptureToBasisImage(rawImage, flash_duration);
time(&TimeImageTaken);
localtime(&TimeImageTaken);
if (CCstatus.SaveAllFiles)
{
rawImage->SaveToFile(namerawimage);
}
if (SaveAllFiles) rawImage->SaveToFile(namerawimage);
}
void ClassFlowTakeImage::SetInitialParameter(void)
{
waitbeforepicture = 5;
isImageSize = false;
ImageQuality = -1;
TimeImageTaken = 0;
ImageQuality = 5;
rawImage = NULL;
ImageSize = FRAMESIZE_VGA;
SaveAllFiles = false;
disabled = false;
FixedExposure = false;
namerawimage = "/sdcard/img_tmp/raw.jpg";
}
}
// auslesen der Kameraeinstellungen aus der config.ini
// wird beim Start aufgerufen
bool ClassFlowTakeImage::ReadParameter(FILE *pfile, string &aktparamgraph)
{
Camera.getSensorDatenToCCstatus(); // Kamera >>> CCstatus
std::vector<string> splitted;
aktparamgraph = trim(aktparamgraph);
if (aktparamgraph.size() == 0)
{
if (!this->GetNextParagraph(pfile, aktparamgraph))
{
return false;
}
}
if (aktparamgraph.compare("[TakeImage]") != 0)
{
// Paragraph does not fit TakeImage
return false;
}
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
{
splitted = ZerlegeZeile(aktparamgraph);
if ((toUpper(splitted[0]) == "RAWIMAGESLOCATION") && (splitted.size() > 1))
{
imagesLocation = "/sdcard" + splitted[1];
isLogImage = true;
}
else if ((toUpper(splitted[0]) == "RAWIMAGESRETENTION") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
this->imagesRetention = std::stod(splitted[1]);
}
}
else if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1))
{
CCstatus.SaveAllFiles = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "WAITBEFORETAKINGPICTURE") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _WaitBeforePicture = std::stoi(splitted[1]);
if (_WaitBeforePicture != 0)
{
CCstatus.WaitBeforePicture = _WaitBeforePicture;
}
else
{
CCstatus.WaitBeforePicture = 2;
}
}
}
else if ((toUpper(splitted[0]) == "CAMGAINCEILING") && (splitted.size() > 1))
{
std::string _ImageGainceiling = toUpper(splitted[1]);
if (isStringNumeric(_ImageGainceiling))
{
int _ImageGainceiling_ = std::stoi(_ImageGainceiling);
switch (_ImageGainceiling_)
{
case 1:
CFstatus.ImageGainceiling = GAINCEILING_4X;
break;
case 2:
CFstatus.ImageGainceiling = GAINCEILING_8X;
break;
case 3:
CFstatus.ImageGainceiling = GAINCEILING_16X;
break;
case 4:
CFstatus.ImageGainceiling = GAINCEILING_32X;
break;
case 5:
CFstatus.ImageGainceiling = GAINCEILING_64X;
break;
case 6:
CFstatus.ImageGainceiling = GAINCEILING_128X;
break;
default:
CFstatus.ImageGainceiling = GAINCEILING_2X;
}
}
else
{
if (_ImageGainceiling == "X4")
{
CCstatus.ImageGainceiling = GAINCEILING_4X;
}
else if (_ImageGainceiling == "X8")
{
CCstatus.ImageGainceiling = GAINCEILING_8X;
}
else if (_ImageGainceiling == "X16")
{
CCstatus.ImageGainceiling = GAINCEILING_16X;
}
else if (_ImageGainceiling == "X32")
{
CCstatus.ImageGainceiling = GAINCEILING_32X;
}
else if (_ImageGainceiling == "X64")
{
CCstatus.ImageGainceiling = GAINCEILING_64X;
}
else if (_ImageGainceiling == "X128")
{
CCstatus.ImageGainceiling = GAINCEILING_128X;
}
else
{
CCstatus.ImageGainceiling = GAINCEILING_2X;
}
}
}
else if ((toUpper(splitted[0]) == "CAMQUALITY") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageQuality = std::stoi(splitted[1]);
CCstatus.ImageQuality = clipInt(_ImageQuality, 63, 6);
}
}
else if ((toUpper(splitted[0]) == "CAMBRIGHTNESS") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageBrightness = std::stoi(splitted[1]);
CCstatus.ImageBrightness = clipInt(_ImageBrightness, 2, -2);
}
}
else if ((toUpper(splitted[0]) == "CAMCONTRAST") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageContrast = std::stoi(splitted[1]);
CCstatus.ImageContrast = clipInt(_ImageContrast, 2, -2);
}
}
else if ((toUpper(splitted[0]) == "CAMSATURATION") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageSaturation = std::stoi(splitted[1]);
CCstatus.ImageSaturation = clipInt(_ImageSaturation, 2, -2);
}
}
else if ((toUpper(splitted[0]) == "CAMSHARPNESS") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageSharpness = std::stoi(splitted[1]);
if (CCstatus.CamSensor_id == OV2640_PID)
{
CCstatus.ImageSharpness = clipInt(_ImageSharpness, 2, -2);
}
else
{
CCstatus.ImageSharpness = clipInt(_ImageSharpness, 3, -3);
}
}
}
else if ((toUpper(splitted[0]) == "CAMAUTOSHARPNESS") && (splitted.size() > 1))
{
CCstatus.ImageAutoSharpness = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMSPECIALEFFECT") && (splitted.size() > 1))
{
std::string _ImageSpecialEffect = toUpper(splitted[1]);
if (isStringNumeric(_ImageSpecialEffect))
{
int _ImageSpecialEffect_ = std::stoi(_ImageSpecialEffect);
CFstatus.ImageSpecialEffect = clipInt(_ImageSpecialEffect_, 6, 0);
}
else
{
if (_ImageSpecialEffect == "NEGATIVE")
{
CCstatus.ImageSpecialEffect = 1;
}
else if (_ImageSpecialEffect == "GRAYSCALE")
{
CCstatus.ImageSpecialEffect = 2;
}
else if (_ImageSpecialEffect == "RED")
{
CCstatus.ImageSpecialEffect = 3;
}
else if (_ImageSpecialEffect == "GREEN")
{
CCstatus.ImageSpecialEffect = 4;
}
else if (_ImageSpecialEffect == "BLUE")
{
CCstatus.ImageSpecialEffect = 5;
}
else if (_ImageSpecialEffect == "RETRO")
{
CCstatus.ImageSpecialEffect = 6;
}
else
{
CCstatus.ImageSpecialEffect = 0;
}
}
}
else if ((toUpper(splitted[0]) == "CAMWBMODE") && (splitted.size() > 1))
{
std::string _ImageWbMode = toUpper(splitted[1]);
if (isStringNumeric(_ImageWbMode))
{
int _ImageWbMode_ = std::stoi(_ImageWbMode);
CFstatus.ImageWbMode = clipInt(_ImageWbMode_, 4, 0);
}
else
{
if (_ImageWbMode == "SUNNY")
{
CCstatus.ImageWbMode = 1;
}
else if (_ImageWbMode == "CLOUDY")
{
CCstatus.ImageWbMode = 2;
}
else if (_ImageWbMode == "OFFICE")
{
CCstatus.ImageWbMode = 3;
}
else if (_ImageWbMode == "HOME")
{
CCstatus.ImageWbMode = 4;
}
else
{
CCstatus.ImageWbMode = 0;
}
}
}
else if ((toUpper(splitted[0]) == "CAMAWB") && (splitted.size() > 1))
{
CCstatus.ImageAwb = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMAWBGAIN") && (splitted.size() > 1))
{
CCstatus.ImageAwbGain = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMAEC") && (splitted.size() > 1))
{
CCstatus.ImageAec = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMAEC2") && (splitted.size() > 1))
{
CCstatus.ImageAec2 = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMAELEVEL") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageAeLevel = std::stoi(splitted[1]);
if (CCstatus.CamSensor_id == OV2640_PID)
{
CCstatus.ImageAeLevel = clipInt(_ImageAeLevel, 2, -2);
}
else
{
CCstatus.ImageAeLevel = clipInt(_ImageAeLevel, 5, -5);
}
}
}
else if ((toUpper(splitted[0]) == "CAMAECVALUE") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageAecValue = std::stoi(splitted[1]);
CCstatus.ImageAecValue = clipInt(_ImageAecValue, 1200, 0);
}
}
else if ((toUpper(splitted[0]) == "CAMAGC") && (splitted.size() > 1))
{
CCstatus.ImageAgc = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMAGCGAIN") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageAgcGain = std::stoi(splitted[1]);
CCstatus.ImageAgcGain = clipInt(_ImageAgcGain, 30, 0);
}
}
else if ((toUpper(splitted[0]) == "CAMBPC") && (splitted.size() > 1))
{
CCstatus.ImageBpc = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMWPC") && (splitted.size() > 1))
{
CCstatus.ImageWpc = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMRAWGMA") && (splitted.size() > 1))
{
CCstatus.ImageRawGma = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMLENC") && (splitted.size() > 1))
{
CCstatus.ImageLenc = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMHMIRROR") && (splitted.size() > 1))
{
CCstatus.ImageHmirror = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMVFLIP") && (splitted.size() > 1))
{
CCstatus.ImageVflip = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMDCW") && (splitted.size() > 1))
{
CCstatus.ImageDcw = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMDENOISE") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageDenoiseLevel = std::stoi(splitted[1]);
if (CCstatus.CamSensor_id == OV2640_PID)
{
CCstatus.ImageDenoiseLevel = 0;
}
else
{
CCstatus.ImageDenoiseLevel = clipInt(_ImageDenoiseLevel, 8, 0);
}
}
}
else if ((toUpper(splitted[0]) == "CAMZOOM") && (splitted.size() > 1))
{
CCstatus.ImageZoomEnabled = alphanumericToBoolean(splitted[1]);
}
else if ((toUpper(splitted[0]) == "CAMZOOMOFFSETX") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageZoomOffsetX = std::stoi(splitted[1]);
if (CCstatus.CamSensor_id == OV2640_PID)
{
CCstatus.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 480, -480);
}
else if (CCstatus.CamSensor_id == OV3660_PID)
{
CCstatus.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 704, -704);
}
else if (CCstatus.CamSensor_id == OV5640_PID)
{
CCstatus.ImageZoomOffsetX = clipInt(_ImageZoomOffsetX, 960, -960);
}
}
}
else if ((toUpper(splitted[0]) == "CAMZOOMOFFSETY") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageZoomOffsetY = std::stoi(splitted[1]);
if (CCstatus.CamSensor_id == OV2640_PID)
{
CCstatus.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 360, -360);
}
else if (CCstatus.CamSensor_id == OV3660_PID)
{
CCstatus.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 528, -528);
}
else if (CCstatus.CamSensor_id == OV5640_PID)
{
CCstatus.ImageZoomOffsetY = clipInt(_ImageZoomOffsetY, 720, -720);
}
}
}
else if ((toUpper(splitted[0]) == "CAMZOOMSIZE") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int _ImageZoomSize = std::stoi(splitted[1]);
if (CCstatus.CamSensor_id == OV2640_PID)
{
CCstatus.ImageZoomSize = clipInt(_ImageZoomSize, 29, 0);
}
else if (CCstatus.CamSensor_id == OV3660_PID)
{
CCstatus.ImageZoomSize = clipInt(_ImageZoomSize, 43, 0);
}
else if (CCstatus.CamSensor_id == OV5640_PID)
{
CCstatus.ImageZoomSize = clipInt(_ImageZoomSize, 59, 0);
}
}
}
else if ((toUpper(splitted[0]) == "LEDINTENSITY") && (splitted.size() > 1))
{
if (isStringNumeric(splitted[1]))
{
int ledintensity = std::stoi(splitted[1]);
CCstatus.ImageLedIntensity = Camera.SetLEDIntensity(ledintensity);
}
}
else if ((toUpper(splitted[0]) == "DEMO") && (splitted.size() > 1))
{
CCstatus.DemoMode = alphanumericToBoolean(splitted[1]);
if (CCstatus.DemoMode == true)
{
Camera.useDemoMode();
}
}
}
Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
rawImage = new CImageBasis("rawImage");
rawImage->CreateEmptyImage(CCstatus.ImageWidth, CCstatus.ImageHeight, 3);
return true;
}
ClassFlowTakeImage::ClassFlowTakeImage(std::vector<ClassFlow *> *lfc) : ClassFlowImage(lfc, TAG)
ClassFlowTakeImage::ClassFlowTakeImage(std::vector<ClassFlow*>* lfc) : ClassFlowImage(lfc, TAG)
{
imagesLocation = "/log/source";
imagesRetention = 5;
SetInitialParameter();
}
bool ClassFlowTakeImage::ReadParameter(FILE* pfile, string& aktparamgraph)
{
std::vector<string> splitted;
aktparamgraph = trim(aktparamgraph);
int _brightness = -100;
int _contrast = -100;
int _saturation = -100;
if (aktparamgraph.size() == 0)
if (!this->GetNextParagraph(pfile, aktparamgraph))
return false;
if (aktparamgraph.compare("[TakeImage]") != 0) // Paragraph does not fit TakeImage
return false;
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
{
splitted = ZerlegeZeile(aktparamgraph);
if ((toUpper(splitted[0]) == "RAWIMAGESLOCATION") && (splitted.size() > 1))
{
imagesLocation = "/sdcard" + splitted[1];
isLogImage = true;
}
if ((toUpper(splitted[0]) == "IMAGEQUALITY") && (splitted.size() > 1))
ImageQuality = std::stod(splitted[1]);
if ((toUpper(splitted[0]) == "IMAGESIZE") && (splitted.size() > 1))
{
ImageSize = Camera.TextToFramesize(splitted[1].c_str());
isImageSize = true;
}
if ((toUpper(splitted[0]) == "SAVEALLFILES") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
SaveAllFiles = true;
}
if ((toUpper(splitted[0]) == "WAITBEFORETAKINGPICTURE") && (splitted.size() > 1))
{
waitbeforepicture = stoi(splitted[1]);
}
if ((toUpper(splitted[0]) == "RAWIMAGESRETENTION") && (splitted.size() > 1))
{
this->imagesRetention = std::stoi(splitted[1]);
}
if ((toUpper(splitted[0]) == "BRIGHTNESS") && (splitted.size() > 1))
{
_brightness = stoi(splitted[1]);
}
if ((toUpper(splitted[0]) == "CONTRAST") && (splitted.size() > 1))
{
_contrast = stoi(splitted[1]);
}
if ((toUpper(splitted[0]) == "SATURATION") && (splitted.size() > 1))
{
_saturation = stoi(splitted[1]);
}
if ((toUpper(splitted[0]) == "FIXEDEXPOSURE") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
FixedExposure = true;
}
if ((toUpper(splitted[0]) == "LEDINTENSITY") && (splitted.size() > 1))
{
float ledintensity = stof(splitted[1]);
ledintensity = min((float) 100, ledintensity);
ledintensity = max((float) 0, ledintensity);
Camera.SetLEDIntensity(ledintensity);
}
if ((toUpper(splitted[0]) == "DEMO") && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "TRUE")
Camera.useDemoMode();
}
}
Camera.SetBrightnessContrastSaturation(_brightness, _contrast, _saturation);
Camera.SetQualitySize(ImageQuality, ImageSize);
image_width = Camera.image_width;
image_height = Camera.image_height;
rawImage = new CImageBasis("rawImage");
rawImage->CreateEmptyImage(image_width, image_height, 3);
waitbeforepicture_store = waitbeforepicture;
if (FixedExposure && (waitbeforepicture > 0))
{
// ESP_LOGD(TAG, "Fixed Exposure enabled!");
int flash_duration = (int) (waitbeforepicture * 1000);
Camera.EnableAutoExposure(flash_duration);
waitbeforepicture = 0.2;
// flash_duration = (int) (waitbeforepicture * 1000);
// takePictureWithFlash(flash_duration);
// rawImage->SaveToFile("/sdcard/init2.jpg");
}
return true;
}
string ClassFlowTakeImage::getHTMLSingleStep(string host)
{
string result;
@@ -537,79 +181,74 @@ string ClassFlowTakeImage::getHTMLSingleStep(string host)
return result;
}
// wird bei jeder Auswertrunde aufgerufen
bool ClassFlowTakeImage::doFlow(string zwtime)
{
psram_init_shared_memory_for_take_image_step();
string logPath = CreateLogFolder(zwtime);
int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
int flash_duration = (int) (waitbeforepicture * 1000);
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - Before takePictureWithFlash");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - Before takePictureWithFlash");
#endif
#ifdef WIFITURNOFF
esp_wifi_stop(); // to save power usage and
#endif
// wenn die Kameraeinstellungen durch Erstellen eines neuen Referenzbildes verändert wurden, müssen sie neu gesetzt werden
if (CFstatus.changedCameraSettings)
{
Camera.setSensorDatenFromCCstatus(); // CCstatus >>> Kamera
Camera.SetQualityZoomSize(CCstatus.ImageQuality, CCstatus.ImageFrameSize, CCstatus.ImageZoomEnabled, CCstatus.ImageZoomOffsetX, CCstatus.ImageZoomOffsetY, CCstatus.ImageZoomSize, CCstatus.ImageVflip);
Camera.LedIntensity = CCstatus.ImageLedIntensity;
CFstatus.changedCameraSettings = false;
}
#ifdef WIFITURNOFF
esp_wifi_stop(); // to save power usage and
#endif
takePictureWithFlash(flash_duration);
#ifdef WIFITURNOFF
esp_wifi_start();
#endif
#ifdef WIFITURNOFF
esp_wifi_start();
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After takePictureWithFlash");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After takePictureWithFlash");
#endif
LogImage(logPath, "raw", NULL, NULL, zwtime, rawImage);
RemoveOldLogs();
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After RemoveOldLogs");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After RemoveOldLogs");
#endif
psram_deinit_shared_memory_for_take_image_step();
return true;
}
esp_err_t ClassFlowTakeImage::SendRawJPG(httpd_req_t *req)
{
int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
int flash_duration = (int) (waitbeforepicture * 1000);
time(&TimeImageTaken);
localtime(&TimeImageTaken);
return Camera.CaptureToHTTP(req, flash_duration);
}
ImageData *ClassFlowTakeImage::SendRawImage(void)
ImageData* ClassFlowTakeImage::SendRawImage()
{
CImageBasis *zw = new CImageBasis("SendRawImage", rawImage);
ImageData *id;
int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
int flash_duration = (int) (waitbeforepicture * 1000);
Camera.CaptureToBasisImage(zw, flash_duration);
time(&TimeImageTaken);
localtime(&TimeImageTaken);
id = zw->writeToMemoryAsJPG();
id = zw->writeToMemoryAsJPG();
delete zw;
return id;
return id;
}
time_t ClassFlowTakeImage::getTimeImageTaken(void)
time_t ClassFlowTakeImage::getTimeImageTaken()
{
return TimeImageTaken;
}
@@ -618,3 +257,4 @@ ClassFlowTakeImage::~ClassFlowTakeImage(void)
{
delete rawImage;
}

View File

@@ -9,32 +9,47 @@
#include <string>
class ClassFlowTakeImage : public ClassFlowImage
class ClassFlowTakeImage :
public ClassFlowImage
{
protected:
float waitbeforepicture;
float waitbeforepicture_store;
framesize_t ImageSize;
bool isImageSize;
int ImageQuality;
time_t TimeImageTaken;
string namerawimage;
int image_height, image_width;
bool SaveAllFiles;
bool FixedExposure;
esp_err_t camera_capture(void);
void CopyFile(string input, string output);
esp_err_t camera_capture();
void takePictureWithFlash(int flash_duration);
void SetInitialParameter(void);
void SetInitialParameter(void);
public:
CImageBasis *rawImage;
ClassFlowTakeImage(std::vector<ClassFlow *> *lfc);
ClassFlowTakeImage(std::vector<ClassFlow*>* lfc);
bool ReadParameter(FILE *pfile, string &aktparamgraph);
bool ReadParameter(FILE* pfile, string& aktparamgraph);
bool doFlow(string time);
string getHTMLSingleStep(string host);
time_t getTimeImageTaken(void);
string name() { return "ClassFlowTakeImage"; };
time_t getTimeImageTaken();
string name(){return "ClassFlowTakeImage";};
ImageData *SendRawImage(void);
ImageData* SendRawImage();
esp_err_t SendRawJPG(httpd_req_t *req);
~ClassFlowTakeImage(void);
};
#endif // CLASSFFLOWTAKEIMAGE_H
#endif //CLASSFFLOWTAKEIMAGE_H

View File

@@ -1,171 +0,0 @@
#ifdef ENABLE_WEBHOOK
#include <sstream>
#include "ClassFlowWebhook.h"
#include "Helper.h"
#include "connect_wlan.h"
#include "time_sntp.h"
#include "interface_webhook.h"
#include "ClassFlowPostProcessing.h"
#include "ClassFlowAlignment.h"
#include "esp_log.h"
#include "../../include/defines.h"
#include "ClassLogFile.h"
#include <time.h>
static const char* TAG = "WEBHOOK";
void ClassFlowWebhook::SetInitialParameter(void)
{
uri = "";
flowpostprocessing = NULL;
flowAlignment = NULL;
previousElement = NULL;
ListFlowControll = NULL;
disabled = false;
WebhookEnable = false;
WebhookUploadImg = 0;
}
ClassFlowWebhook::ClassFlowWebhook()
{
SetInitialParameter();
}
ClassFlowWebhook::ClassFlowWebhook(std::vector<ClassFlow*>* lfc)
{
SetInitialParameter();
ListFlowControll = lfc;
for (int i = 0; i < ListFlowControll->size(); ++i)
{
if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
{
flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
}
if (((*ListFlowControll)[i])->name().compare("ClassFlowAlignment") == 0)
{
flowAlignment = (ClassFlowAlignment*) (*ListFlowControll)[i];
}
}
}
ClassFlowWebhook::ClassFlowWebhook(std::vector<ClassFlow*>* lfc, ClassFlow *_prev)
{
SetInitialParameter();
previousElement = _prev;
ListFlowControll = lfc;
for (int i = 0; i < ListFlowControll->size(); ++i)
{
if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
{
flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
}
if (((*ListFlowControll)[i])->name().compare("ClassFlowAlignment") == 0)
{
flowAlignment = (ClassFlowAlignment*) (*ListFlowControll)[i];
}
}
}
bool ClassFlowWebhook::ReadParameter(FILE* pfile, string& aktparamgraph)
{
std::vector<string> splitted;
aktparamgraph = trim(aktparamgraph);
printf("akt param: %s\n", aktparamgraph.c_str());
if (aktparamgraph.size() == 0)
if (!this->GetNextParagraph(pfile, aktparamgraph))
return false;
if (toUpper(aktparamgraph).compare("[WEBHOOK]") != 0)
return false;
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
{
ESP_LOGD(TAG, "while loop reading line: %s", aktparamgraph.c_str());
splitted = ZerlegeZeile(aktparamgraph);
std::string _param = GetParameterName(splitted[0]);
if ((toUpper(_param) == "URI") && (splitted.size() > 1))
{
this->uri = splitted[1];
}
if (((toUpper(_param) == "APIKEY")) && (splitted.size() > 1))
{
this->apikey = splitted[1];
}
if (((toUpper(_param) == "UPLOADIMG")) && (splitted.size() > 1))
{
if (toUpper(splitted[1]) == "1")
{
this->WebhookUploadImg = 1;
} else if (toUpper(splitted[1]) == "2")
{
this->WebhookUploadImg = 2;
}
}
}
WebhookInit(uri,apikey);
WebhookEnable = true;
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Webhook Enabled for Uri " + uri);
printf("uri: %s\n", uri.c_str());
return true;
}
void ClassFlowWebhook::handleMeasurement(string _decsep, string _value)
{
string _digit, _decpos;
int _pospunkt = _decsep.find_first_of(".");
// ESP_LOGD(TAG, "Name: %s, Pospunkt: %d", _decsep.c_str(), _pospunkt);
if (_pospunkt > -1)
_digit = _decsep.substr(0, _pospunkt);
else
_digit = "default";
for (int j = 0; j < flowpostprocessing->NUMBERS.size(); ++j)
{
if (_digit == "default") // Set to default first (if nothing else is set)
{
flowpostprocessing->NUMBERS[j]->MeasurementV2 = _value;
}
if (flowpostprocessing->NUMBERS[j]->name == _digit)
{
flowpostprocessing->NUMBERS[j]->MeasurementV2 = _value;
}
}
}
bool ClassFlowWebhook::doFlow(string zwtime)
{
if (!WebhookEnable)
return true;
if (flowpostprocessing)
{
printf("vor sende WebHook");
bool numbersWithError = WebhookPublish(flowpostprocessing->GetNumbers());
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
if ((WebhookUploadImg == 1 || (WebhookUploadImg != 0 && numbersWithError)) && flowAlignment && flowAlignment->AlgROI) {
WebhookUploadPic(flowAlignment->AlgROI);
}
#endif
}
return true;
}
#endif //ENABLE_WEBHOOK

View File

@@ -1,43 +0,0 @@
#ifdef ENABLE_WEBHOOK
#pragma once
#ifndef CLASSFWEBHOOK_H
#define CLASSFWEBHOOK_H
#include "ClassFlow.h"
#include "ClassFlowPostProcessing.h"
#include "ClassFlowAlignment.h"
#include <string>
class ClassFlowWebhook :
public ClassFlow
{
protected:
std::string uri, apikey;
ClassFlowPostProcessing* flowpostprocessing;
ClassFlowAlignment* flowAlignment;
bool WebhookEnable;
int WebhookUploadImg;
void SetInitialParameter(void);
void handleFieldname(string _decsep, string _value);
void handleMeasurement(string _decsep, string _value);
public:
ClassFlowWebhook();
ClassFlowWebhook(std::vector<ClassFlow*>* lfc);
ClassFlowWebhook(std::vector<ClassFlow*>* lfc, ClassFlow *_prev);
bool ReadParameter(FILE* pfile, string& aktparamgraph);
bool doFlow(string time);
string name(){return "ClassFlowWebhook";};
};
#endif //CLASSFWEBHOOK_H
#endif //ENABLE_WEBHOOK

File diff suppressed because it is too large Load Diff

View File

@@ -9,83 +9,26 @@
#include <esp_http_server.h>
#include "CImageBasis.h"
#include "ClassFlowControll.h"
#include "openmetrics.h"
typedef struct
{
uint16_t CamSensor_id;
framesize_t ImageFrameSize = FRAMESIZE_VGA; // 0 - 10
gainceiling_t ImageGainceiling; // Image gain (GAINCEILING_x2, x4, x8, x16, x32, x64 or x128)
int ImageQuality; // 0 - 63
int ImageBrightness; // (-2 to 2) - set brightness
int ImageContrast; //-2 - 2
int ImageSaturation; //-2 - 2
int ImageSharpness; //-2 - 2
bool ImageAutoSharpness;
int ImageSpecialEffect; // 0 - 6
int ImageWbMode; // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home)
int ImageAwb; // white balance enable (0 or 1)
int ImageAwbGain; // Auto White Balance enable (0 or 1)
int ImageAec; // auto exposure off (1 or 0)
int ImageAec2; // automatic exposure sensor (0 or 1)
int ImageAeLevel; // auto exposure levels (-2 to 2)
int ImageAecValue; // set exposure manually (0-1200)
int ImageAgc; // auto gain off (1 or 0)
int ImageAgcGain; // set gain manually (0 - 30)
int ImageBpc; // black pixel correction
int ImageWpc; // white pixel correction
int ImageRawGma; // (1 or 0)
int ImageLenc; // lens correction (1 or 0)
int ImageHmirror; // (0 or 1) flip horizontally
int ImageVflip; // Invert image (0 or 1)
int ImageDcw; // downsize enable (1 or 0)
int ImageDenoiseLevel; // The OV2640 does not support it, OV3660 and OV5640 (0 to 8)
int ImageWidth;
int ImageHeight;
int ImageLedIntensity;
bool ImageZoomEnabled;
int ImageZoomOffsetX;
int ImageZoomOffsetY;
int ImageZoomSize;
int WaitBeforePicture;
bool isImageSize;
bool CameraInitSuccessful;
bool changedCameraSettings;
bool DemoMode;
bool SaveAllFiles;
} camera_flow_config_temp_t;
extern camera_flow_config_temp_t CFstatus;
extern ClassFlowControll flowctrl;
esp_err_t setCCstatusToCFstatus(void); // CCstatus >>> CFstatus
esp_err_t setCFstatusToCCstatus(void); // CFstatus >>> CCstatus
esp_err_t setCFstatusToCam(void); // CFstatus >>> Kamera
void register_server_main_flow_task_uri(httpd_handle_t server);
void CheckIsPlannedReboot(void);
bool getIsPlannedReboot(void);
void CheckIsPlannedReboot();
bool getIsPlannedReboot();
void InitializeFlowTask(void);
void DeleteMainFlowTask(void);
bool isSetupModusActive(void);
void InitializeFlowTask();
void DeleteMainFlowTask();
bool isSetupModusActive();
int getCountFlowRounds(void);
int getCountFlowRounds();
#ifdef ENABLE_MQTT
esp_err_t MQTTCtrlFlowStart(std::string _topic);
#endif // ENABLE_MQTT
#endif //ENABLE_MQTT
esp_err_t GetRawJPG(httpd_req_t *req);
esp_err_t GetJPG(std::string _filename, httpd_req_t *req);
#endif // MAINFLOWCONTROL_H
#endif //MAINFLOWCONTROL_H

View File

@@ -2,6 +2,6 @@ FILE(GLOB_RECURSE app_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.*)
idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "."
REQUIRES esp_timer esp-tflite-micro jomjol_logfile fatfs sdmmc vfs)
REQUIRES esp_timer tflite-lib jomjol_logfile fatfs sdmmc esp_http_server)

File diff suppressed because it is too large Load Diff

View File

@@ -6,7 +6,6 @@
#include <string>
#include <fstream>
#include <vector>
#include "sdmmc_cmd.h"
using namespace std;
@@ -21,6 +20,7 @@ bool RenameFile(string from, string to);
bool MakeDir(std::string _what);
bool FileExists(string filename);
string RundeOutput(double _in, int _anzNachkomma);
size_t findDelimiterPos(string input, string delimiter);
@@ -32,6 +32,7 @@ string getFileType(string filename);
string getFileFullFileName(string filename);
string getDirectory(string filename);
int mkdir_r(const char *dir, const mode_t mode);
int removeFolder(const char* folderPath, const char* logTag);
@@ -40,7 +41,6 @@ string toUpper(string in);
float temperatureRead();
std::string intToHexString(int _valueInt);
time_t addDays(time_t startTime, int days);
void memCopyGen(uint8_t* _source, uint8_t* _target, int _size);
@@ -67,6 +67,7 @@ string getSDCardSectorSize();
string getMac(void);
/* Error bit fields
One bit per error
Make sure it matches https://jomjol.github.io/AI-on-the-edge-device-docs/Error-Codes */
@@ -96,18 +97,8 @@ const char* get404(void);
std::string UrlDecode(const std::string& value);
void replaceAll(std::string& s, const std::string& toReplace, const std::string& replaceWith);
bool replaceString(std::string& s, std::string const& toReplace, std::string const& replaceWith);
bool replaceString(std::string& s, std::string const& toReplace, std::string const& replaceWith, bool logIt);
bool isInString(std::string& s, std::string const& toFind);
bool isStringNumeric(std::string &input);
bool isStringAlphabetic(std::string &input);
bool isStringAlphanumeric(std::string &input);
bool alphanumericToBoolean(std::string &input);
int clipInt(int input, int high, int low);
bool numericStrToBool(std::string input);
bool stringToBoolean(std::string input);
#endif //HELPER_H

View File

@@ -120,15 +120,15 @@ void psram_free_shared_temp_image_memory(void) {
/*******************************************************************
* Memory used in Digitization Steps
* Memory used in Digitalization Steps
* During this step we only use the shared part of the PSRAM for the
* Tensor Arena and one of the Models.
* The shared memory is large enough for the largest model and the
* Tensor Arena. Therefore we do not need to monitor the usage.
*******************************************************************/
void *psram_get_shared_tensor_arena_memory(void) {
if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitization_Model")) {
sharedMemoryInUseFor = "Digitization_Tensor";
if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitalization_Model")) {
sharedMemoryInUseFor = "Digitalization_Tensor";
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Tensor Arena (" + std::to_string(TENSOR_ARENA_SIZE) + " bytes, use shared memory in PSRAM)...");
return shared_region; // Use 1th part of the shared memory for Tensor
}
@@ -140,8 +140,8 @@ void *psram_get_shared_tensor_arena_memory(void) {
void *psram_get_shared_model_memory(void) {
if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitization_Tensor")) {
sharedMemoryInUseFor = "Digitization_Model";
if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitalization_Tensor")) {
sharedMemoryInUseFor = "Digitalization_Model";
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Model memory (" + std::to_string(MAX_MODEL_SIZE) + " bytes, use shared memory in PSRAM)...");
return (uint8_t *)shared_region + TENSOR_ARENA_SIZE; // Use 2nd part of the shared memory (after Tensor Arena) for the model
}

View File

@@ -20,7 +20,7 @@ void psram_free_shared_stbi_memory(void *p);
void *psram_reserve_shared_tmp_image_memory(void);
void psram_free_shared_temp_image_memory(void);
/* Memory used in Digitization Steps */
/* Memory used in Digitalization Steps */
void *psram_get_shared_tensor_arena_memory(void);
void *psram_get_shared_model_memory(void);
void psram_free_shared_tensor_arena_and_model_memory(void);

View File

@@ -3,7 +3,6 @@
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/stat.h>

View File

@@ -1,646 +0,0 @@
/*
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdlib.h>
#include <string.h>
#include "sdcard_init.h"
#include "esp_log.h"
#include "ffconf.h"
#include "esp_compiler.h"
#include "esp_vfs.h"
#include "vfs_fat_internal.h"
#include "diskio_impl.h"
#include "diskio_sdmmc.h"
#include "soc/soc_caps.h"
#include "driver/sdmmc_defs.h"
#if SOC_SDMMC_HOST_SUPPORTED
#include "driver/sdmmc_host.h"
#endif
static sdmmc_card_t* s_cards[FF_VOLUMES] = { NULL };
static bool s_disk_status_check_en[FF_VOLUMES] = { };
static const char* TAG = "sdcard_init";
#define CHECK_EXECUTE_RESULT(err, str) do { \
if ((err) !=ESP_OK) { \
ESP_LOGE(TAG, str" (0x%x).", err); \
goto cleanup; \
} \
} while(0)
typedef struct mh_vfs_fat_sd_ctx_t {
BYTE pdrv; //Drive number that is mounted
esp_vfs_fat_mount_config_t mount_config; //Mount configuration
FATFS *fs; //FAT structure pointer that is registered
sdmmc_card_t *card; //Card info
char *base_path; //Path where partition is registered
} mh_vfs_fat_sd_ctx_t;
static mh_vfs_fat_sd_ctx_t *s_ctx[FF_VOLUMES] = {};
/**
* This `s_saved_ctx_id` is only used by `esp_vfs_fat_sdmmc_unmount`, which is deprecated.
* This variable together with `esp_vfs_fat_sdmmc_unmount` should be removed in next major version
*/
static uint32_t s_saved_ctx_id = FF_VOLUMES;
static void call_host_deinit_mh(const sdmmc_host_t *host_config);
static esp_err_t partition_card_mh(const esp_vfs_fat_mount_config_t *mount_config, const char *drv, sdmmc_card_t *card, BYTE pdrv);
//Check if SD/MMC card is present
static DSTATUS ff_sdmmc_card_available_mh(BYTE pdrv)
{
sdmmc_card_t* card = s_cards[pdrv];
assert(card);
esp_err_t err = sdmmc_get_status(card);
if (unlikely(err != ESP_OK)) {
ESP_LOGE(TAG, "Check status failed (0x%x)", err);
return STA_NOINIT;
}
return 0;
}
/**
* ff_sdmmc_status() and ff_sdmmc_initialize() return STA_NOINIT when sdmmc_get_status()
* fails. This error value is checked throughout the FATFS code.
* Both functions return 0 on success.
*/
DSTATUS ff_sdmmc_initialize_mh (BYTE pdrv)
{
return ff_sdmmc_card_available_mh(pdrv);
}
DSTATUS ff_sdmmc_status_mh(BYTE pdrv)
{
if (s_disk_status_check_en[pdrv]) {
return ff_sdmmc_card_available_mh(pdrv);
}
return 0;
}
DRESULT ff_sdmmc_read_mh (BYTE pdrv, BYTE* buff, DWORD sector, UINT count)
{
sdmmc_card_t* card = s_cards[pdrv];
assert(card);
esp_err_t err = sdmmc_read_sectors(card, buff, sector, count);
if (unlikely(err != ESP_OK)) {
ESP_LOGE(TAG, "sdmmc_read_blocks failed (%d)", err);
return RES_ERROR;
}
return RES_OK;
}
DRESULT ff_sdmmc_write_mh (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count)
{
sdmmc_card_t* card = s_cards[pdrv];
assert(card);
esp_err_t err = sdmmc_write_sectors(card, buff, sector, count);
if (unlikely(err != ESP_OK)) {
ESP_LOGE(TAG, "sdmmc_write_blocks failed (%d)", err);
return RES_ERROR;
}
return RES_OK;
}
#if FF_USE_TRIM
DRESULT ff_sdmmc_trim_mh (BYTE pdrv, DWORD start_sector, DWORD sector_count)
{
sdmmc_card_t* card = s_cards[pdrv];
assert(card);
sdmmc_erase_arg_t arg;
arg = sdmmc_can_discard(card) == ESP_OK ? SDMMC_DISCARD_ARG : SDMMC_ERASE_ARG;
esp_err_t err = sdmmc_erase_sectors(card, start_sector, sector_count, arg);
if (unlikely(err != ESP_OK)) {
ESP_LOGE(TAG, "sdmmc_erase_sectors failed (%d)", err);
return RES_ERROR;
}
return RES_OK;
}
#endif //FF_USE_TRIM
DRESULT ff_sdmmc_ioctl_mh (BYTE pdrv, BYTE cmd, void* buff)
{
sdmmc_card_t* card = s_cards[pdrv];
assert(card);
switch(cmd) {
case CTRL_SYNC:
return RES_OK;
case GET_SECTOR_COUNT:
*((DWORD*) buff) = card->csd.capacity;
return RES_OK;
case GET_SECTOR_SIZE:
*((WORD*) buff) = card->csd.sector_size;
return RES_OK;
case GET_BLOCK_SIZE:
return RES_ERROR;
#if FF_USE_TRIM
case CTRL_TRIM:
if (sdmmc_can_trim(card) != ESP_OK) {
return RES_PARERR;
}
return ff_sdmmc_trim_mh (pdrv, *((DWORD*)buff), //start_sector
(*((DWORD*)buff + 1) - *((DWORD*)buff) + 1)); //sector_count
#endif //FF_USE_TRIM
}
return RES_ERROR;
}
void ff_sdmmc_set_disk_status_check_mh(BYTE pdrv, bool enable)
{
s_disk_status_check_en[pdrv] = enable;
}
void ff_diskio_register_sdmmc_mh(BYTE pdrv, sdmmc_card_t* card)
{
static const ff_diskio_impl_t sdmmc_impl = {
.init = &ff_sdmmc_initialize_mh,
.status = &ff_sdmmc_status_mh,
.read = &ff_sdmmc_read_mh,
.write = &ff_sdmmc_write_mh,
.ioctl = &ff_sdmmc_ioctl_mh
};
s_cards[pdrv] = card;
s_disk_status_check_en[pdrv] = false;
ff_diskio_register(pdrv, &sdmmc_impl);
}
BYTE ff_diskio_get_pdrv_card_mh(const sdmmc_card_t* card)
{
for (int i = 0; i < FF_VOLUMES; i++) {
if (card == s_cards[i]) {
return i;
}
}
return 0xff;
}
static bool s_get_context_id_by_card_mh(const sdmmc_card_t *card, uint32_t *out_id)
{
mh_vfs_fat_sd_ctx_t *p_ctx = NULL;
for (int i = 0; i < FF_VOLUMES; i++) {
p_ctx = s_ctx[i];
if (p_ctx) {
if (p_ctx->card == card) {
*out_id = i;
return true;
}
}
}
return false;
}
static uint32_t s_get_unused_context_id_mh(void)
{
for (uint32_t i = 0; i < FF_VOLUMES; i++) {
if (!s_ctx[i]) {
return i;
}
}
return FF_VOLUMES;
}
static esp_err_t mount_prepare_mem_mh(const char *base_path, BYTE *out_pdrv, char **out_dup_path, sdmmc_card_t** out_card)
{
esp_err_t err = ESP_OK;
char* dup_path = NULL;
sdmmc_card_t* card = NULL;
// connect SDMMC driver to FATFS
BYTE pdrv = FF_DRV_NOT_USED;
if (ff_diskio_get_drive(&pdrv) != ESP_OK || pdrv == FF_DRV_NOT_USED) {
ESP_LOGD(TAG, "the maximum count of volumes is already mounted");
return ESP_ERR_NO_MEM;
}
// not using ff_memalloc here, as allocation in internal RAM is preferred
card = (sdmmc_card_t*)malloc(sizeof(sdmmc_card_t));
if (card == NULL) {
ESP_LOGD(TAG, "could not locate new sdmmc_card_t");
err = ESP_ERR_NO_MEM;
goto cleanup;
}
dup_path = strdup(base_path);
if(!dup_path){
ESP_LOGD(TAG, "could not copy base_path");
err = ESP_ERR_NO_MEM;
goto cleanup;
}
*out_card = card;
*out_pdrv = pdrv;
*out_dup_path = dup_path;
return ESP_OK;
cleanup:
free(card);
free(dup_path);
return err;
}
static esp_err_t s_f_mount_mh(sdmmc_card_t *card, FATFS *fs, const char *drv, uint8_t pdrv, const esp_vfs_fat_mount_config_t *mount_config)
{
esp_err_t err = ESP_OK;
FRESULT res = f_mount(fs, drv, 1);
if (res != FR_OK) {
err = ESP_FAIL;
ESP_LOGW(TAG, "failed to mount card (%d)", res);
bool need_mount_again = (res == FR_NO_FILESYSTEM || res == FR_INT_ERR) && mount_config->format_if_mount_failed;
if (!need_mount_again) {
return ESP_FAIL;
}
err = partition_card_mh(mount_config, drv, card, pdrv);
if (err != ESP_OK) {
return err;
}
ESP_LOGW(TAG, "mounting again");
res = f_mount(fs, drv, 0);
if (res != FR_OK) {
err = ESP_FAIL;
ESP_LOGD(TAG, "f_mount failed after formatting (%d)", res);
return err;
}
}
return ESP_OK;
}
static esp_err_t mount_to_vfs_fat_mh(const esp_vfs_fat_mount_config_t *mount_config, sdmmc_card_t *card, uint8_t pdrv, const char *base_path, FATFS **out_fs)
{
FATFS *fs = NULL;
esp_err_t err;
ff_diskio_register_sdmmc_mh(pdrv, card);
ff_sdmmc_set_disk_status_check_mh(pdrv, mount_config->disk_status_check_enable);
ESP_LOGD(TAG, "using pdrv=%i", pdrv);
char drv[3] = {(char)('0' + pdrv), ':', 0};
// connect FATFS to VFS
err = esp_vfs_fat_register(base_path, drv, mount_config->max_files, &fs);
*out_fs = fs;
if (err == ESP_ERR_INVALID_STATE) {
// it's okay, already registered with VFS
} else if (err != ESP_OK) {
ESP_LOGD(TAG, "esp_vfs_fat_register failed 0x(%x)", err);
goto fail;
}
// Try to mount partition
err = s_f_mount_mh(card, fs, drv, pdrv, mount_config);
if (err != ESP_OK) {
goto fail;
}
return ESP_OK;
fail:
if (fs) {
f_mount(NULL, drv, 0);
}
esp_vfs_fat_unregister_path(base_path);
ff_diskio_unregister(pdrv);
return err;
}
static esp_err_t partition_card_mh(const esp_vfs_fat_mount_config_t *mount_config, const char *drv, sdmmc_card_t *card, BYTE pdrv)
{
FRESULT res = FR_OK;
esp_err_t err;
const size_t workbuf_size = 4096;
void* workbuf = NULL;
ESP_LOGW(TAG, "partitioning card");
workbuf = ff_memalloc(workbuf_size);
if (workbuf == NULL) {
return ESP_ERR_NO_MEM;
}
LBA_t plist[] = {100, 0, 0, 0};
res = f_fdisk(pdrv, plist, workbuf);
if (res != FR_OK) {
err = ESP_FAIL;
ESP_LOGD(TAG, "f_fdisk failed (%d)", res);
goto fail;
}
size_t alloc_unit_size = esp_vfs_fat_get_allocation_unit_size(card->csd.sector_size, mount_config->allocation_unit_size);
ESP_LOGW(TAG, "formatting card, allocation unit size=%d", alloc_unit_size);
const MKFS_PARM opt = {(BYTE)FM_ANY, 0, 0, 0, alloc_unit_size};
res = f_mkfs(drv, &opt, workbuf, workbuf_size);
if (res != FR_OK) {
err = ESP_FAIL;
ESP_LOGD(TAG, "f_mkfs failed (%d)", res);
goto fail;
}
free(workbuf);
return ESP_OK;
fail:
free(workbuf);
return err;
}
#if SOC_SDMMC_HOST_SUPPORTED
static esp_err_t init_sdmmc_host_mh(int slot, const void *slot_config, int *out_slot)
{
*out_slot = slot;
return sdmmc_host_init_slot(slot, (const sdmmc_slot_config_t*) slot_config);
}
esp_err_t esp_vfs_fat_sdmmc_mount_mh(const char* base_path, const sdmmc_host_t* host_config, const void* slot_config, const esp_vfs_fat_mount_config_t* mount_config, sdmmc_card_t** out_card)
{
esp_err_t err;
mh_vfs_fat_sd_ctx_t *ctx = NULL;
uint32_t ctx_id = FF_VOLUMES;
FATFS *fs = NULL;
int card_handle = -1; //uninitialized
sdmmc_card_t* card = NULL;
BYTE pdrv = FF_DRV_NOT_USED;
char* dup_path = NULL;
bool host_inited = false;
err = mount_prepare_mem_mh(base_path, &pdrv, &dup_path, &card);
if (err != ESP_OK) {
ESP_LOGE(TAG, "mount_prepare failed");
return err;
}
err = (*host_config->init)();
CHECK_EXECUTE_RESULT(err, "host init failed");
//deinit() needs to be called to revert the init
host_inited = true;
//If this failed (indicated by card_handle != -1), slot deinit needs to called()
//leave card_handle as is to indicate that (though slot deinit not implemented yet.
err = init_sdmmc_host_mh(host_config->slot, slot_config, &card_handle);
CHECK_EXECUTE_RESULT(err, "slot init failed");
// probe and initialize card
err = sdmmc_card_init(host_config, card);
CHECK_EXECUTE_RESULT(err, "sdmmc_card_init failed");
err = mount_to_vfs_fat_mh(mount_config, card, pdrv, dup_path, &fs);
CHECK_EXECUTE_RESULT(err, "mount_to_vfs failed");
if (out_card != NULL) {
*out_card = card;
}
//For deprecation backward compatibility
if (s_saved_ctx_id == FF_VOLUMES) {
s_saved_ctx_id = 0;
}
ctx = calloc(sizeof(mh_vfs_fat_sd_ctx_t), 1);
if (!ctx) {
CHECK_EXECUTE_RESULT(ESP_ERR_NO_MEM, "no mem");
}
ctx->pdrv = pdrv;
memcpy(&ctx->mount_config, mount_config, sizeof(esp_vfs_fat_mount_config_t));
ctx->card = card;
ctx->base_path = dup_path;
ctx->fs = fs;
ctx_id = s_get_unused_context_id_mh();
assert(ctx_id != FF_VOLUMES);
s_ctx[ctx_id] = ctx;
return ESP_OK;
cleanup:
if (host_inited) {
call_host_deinit_mh(host_config);
}
free(card);
free(dup_path);
return err;
}
#endif
static esp_err_t init_sdspi_host_mh(int slot, const void *slot_config, int *out_slot)
{
esp_err_t err = sdspi_host_init_device((const sdspi_device_config_t*)slot_config, out_slot);
if (err != ESP_OK) {
ESP_LOGE(TAG,
"Failed to attach sdspi device onto an SPI bus (rc=0x%x), please initialize the \
bus first and check the device parameters."
, err);
}
return err;
}
esp_err_t esp_vfs_fat_sdspi_mount_mh(const char* base_path, const sdmmc_host_t* host_config_input, const sdspi_device_config_t* slot_config, const esp_vfs_fat_mount_config_t* mount_config, sdmmc_card_t** out_card)
{
const sdmmc_host_t* host_config = host_config_input;
esp_err_t err;
mh_vfs_fat_sd_ctx_t *ctx = NULL;
uint32_t ctx_id = FF_VOLUMES;
FATFS *fs = NULL;
int card_handle = -1; //uninitialized
bool host_inited = false;
BYTE pdrv = FF_DRV_NOT_USED;
sdmmc_card_t* card = NULL;
char* dup_path = NULL;
err = mount_prepare_mem_mh(base_path, &pdrv, &dup_path, &card);
if (err != ESP_OK) {
ESP_LOGE(TAG, "mount_prepare failed");
return err;
}
//the init() function is usually empty, doesn't require any deinit to revert it
err = (*host_config->init)();
CHECK_EXECUTE_RESULT(err, "host init failed");
err = init_sdspi_host_mh(host_config->slot, slot_config, &card_handle);
CHECK_EXECUTE_RESULT(err, "slot init failed");
//Set `host_inited` to true to indicate that host_config->deinit() needs
//to be called to revert `init_sdspi_host`
host_inited = true;
//The `slot` argument inside host_config should be replaced by the SD SPI handled returned
//above. But the input pointer is const, so create a new variable.
sdmmc_host_t new_config;
if (card_handle != host_config->slot) {
new_config = *host_config_input;
host_config = &new_config;
new_config.slot = card_handle;
}
// probe and initialize card
err = sdmmc_card_init(host_config, card);
CHECK_EXECUTE_RESULT(err, "sdmmc_card_init failed");
err = mount_to_vfs_fat_mh(mount_config, card, pdrv, dup_path, &fs);
CHECK_EXECUTE_RESULT(err, "mount_to_vfs failed");
if (out_card != NULL) {
*out_card = card;
}
//For deprecation backward compatibility
if (s_saved_ctx_id == FF_VOLUMES) {
s_saved_ctx_id = 0;
}
ctx = calloc(sizeof(mh_vfs_fat_sd_ctx_t), 1);
if (!ctx) {
CHECK_EXECUTE_RESULT(ESP_ERR_NO_MEM, "no mem");
}
ctx->pdrv = pdrv;
memcpy(&ctx->mount_config, mount_config, sizeof(esp_vfs_fat_mount_config_t));
ctx->card = card;
ctx->base_path = dup_path;
ctx->fs = fs;
ctx_id = s_get_unused_context_id_mh();
assert(ctx_id != FF_VOLUMES);
s_ctx[ctx_id] = ctx;
return ESP_OK;
cleanup:
if (host_inited) {
call_host_deinit_mh(host_config);
}
free(card);
free(dup_path);
return err;
}
static void call_host_deinit_mh(const sdmmc_host_t *host_config)
{
if (host_config->flags & SDMMC_HOST_FLAG_DEINIT_ARG) {
host_config->deinit_p(host_config->slot);
} else {
host_config->deinit();
}
}
static esp_err_t unmount_card_core_mh(const char *base_path, sdmmc_card_t *card)
{
BYTE pdrv = ff_diskio_get_pdrv_card_mh(card);
if (pdrv == 0xff) {
return ESP_ERR_INVALID_ARG;
}
// unmount
char drv[3] = {(char)('0' + pdrv), ':', 0};
f_mount(0, drv, 0);
// release SD driver
ff_diskio_unregister(pdrv);
call_host_deinit_mh(&card->host);
free(card);
esp_err_t err = esp_vfs_fat_unregister_path(base_path);
return err;
}
esp_err_t esp_vfs_fat_sdmmc_unmount_mh(void)
{
esp_err_t err = unmount_card_core_mh(s_ctx[s_saved_ctx_id]->base_path, s_ctx[s_saved_ctx_id]->card);
free(s_ctx[s_saved_ctx_id]);
s_ctx[s_saved_ctx_id] = NULL;
s_saved_ctx_id = FF_VOLUMES;
return err;
}
esp_err_t esp_vfs_fat_sdcard_unmount_mh(const char *base_path, sdmmc_card_t *card)
{
uint32_t id = FF_VOLUMES;
bool found = s_get_context_id_by_card_mh(card, &id);
if (!found) {
return ESP_ERR_INVALID_ARG;
}
free(s_ctx[id]);
s_ctx[id] = NULL;
esp_err_t err = unmount_card_core_mh(base_path, card);
return err;
}
esp_err_t esp_vfs_fat_sdcard_format_mh(const char *base_path, sdmmc_card_t *card)
{
esp_err_t ret = ESP_OK;
if (!card) {
ESP_LOGE(TAG, "card not initialized");
return ESP_ERR_INVALID_STATE;
}
BYTE pdrv = ff_diskio_get_pdrv_card_mh(card);
if (pdrv == 0xff) {
ESP_LOGE(TAG, "card driver not registered");
return ESP_ERR_INVALID_STATE;
}
const size_t workbuf_size = 4096;
void *workbuf = ff_memalloc(workbuf_size);
if (workbuf == NULL) {
return ESP_ERR_NO_MEM;
}
//unmount
char drv[3] = {(char)('0' + pdrv), ':', 0};
f_mount(0, drv, 0);
//format
uint32_t id = FF_VOLUMES;
bool found = s_get_context_id_by_card_mh(card, &id);
assert(found);
size_t alloc_unit_size = esp_vfs_fat_get_allocation_unit_size(card->csd.sector_size, s_ctx[id]->mount_config.allocation_unit_size);
ESP_LOGI(TAG, "Formatting card, allocation unit size=%d", alloc_unit_size);
const MKFS_PARM opt = {(BYTE)FM_ANY, 0, 0, 0, alloc_unit_size};
FRESULT res = f_mkfs(drv, &opt, workbuf, workbuf_size);
free(workbuf);
if (res != FR_OK) {
ret = ESP_FAIL;
ESP_LOGD(TAG, "f_mkfs failed (%d)", res);
}
//mount back
esp_err_t err = s_f_mount_mh(card, s_ctx[id]->fs, drv, pdrv, &s_ctx[id]->mount_config);
if (err != ESP_OK) {
unmount_card_core_mh(base_path, card);
ESP_LOGE(TAG, "failed to format, resources recycled, please mount again");
}
return ret;
}

View File

@@ -1,111 +0,0 @@
/*
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stddef.h>
#include "esp_err.h"
#include "driver/gpio.h"
#include "sdmmc_cmd.h"
#include "driver/sdmmc_types.h"
#include "driver/sdspi_host.h"
#include "ff.h"
#include "esp_vfs_fat.h"
#include "wear_levelling.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Convenience function to get FAT filesystem on SD card registered in VFS
*
* This is an all-in-one function which does the following:
* - initializes SDMMC driver or SPI driver with configuration in host_config
* - initializes SD card with configuration in slot_config
* - mounts FAT partition on SD card using FATFS library, with configuration in mount_config
* - registers FATFS library with VFS, with prefix given by base_prefix variable
*
* This function is intended to make example code more compact.
* For real world applications, developers should implement the logic of
* probing SD card, locating and mounting partition, and registering FATFS in VFS,
* with proper error checking and handling of exceptional conditions.
*
* @note Use this API to mount a card through SDSPI is deprecated. Please call
* `esp_vfs_fat_sdspi_mount()` instead for that case.
*
* @param base_path path where partition should be registered (e.g. "/sdcard")
* @param host_config Pointer to structure describing SDMMC host. When using
* SDMMC peripheral, this structure can be initialized using
* SDMMC_HOST_DEFAULT() macro. When using SPI peripheral,
* this structure can be initialized using SDSPI_HOST_DEFAULT()
* macro.
* @param slot_config Pointer to structure with slot configuration.
* For SDMMC peripheral, pass a pointer to sdmmc_slot_config_t
* structure initialized using SDMMC_SLOT_CONFIG_DEFAULT.
* @param mount_config pointer to structure with extra parameters for mounting FATFS
* @param[out] out_card if not NULL, pointer to the card information structure will be returned via this argument
* @return
* - ESP_OK on success
* - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called
* - ESP_ERR_NO_MEM if memory can not be allocated
* - ESP_FAIL if partition can not be mounted
* - other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers
*/
esp_err_t esp_vfs_fat_sdmmc_mount_mh(const char* base_path, const sdmmc_host_t* host_config, const void* slot_config, const esp_vfs_fat_mount_config_t* mount_config, sdmmc_card_t** out_card);
/**
* @brief Convenience function to get FAT filesystem on SD card registered in VFS
*
* This is an all-in-one function which does the following:
* - initializes an SPI Master device based on the SPI Master driver with configuration in
* slot_config, and attach it to an initialized SPI bus.
* - initializes SD card with configuration in host_config_input
* - mounts FAT partition on SD card using FATFS library, with configuration in mount_config
* - registers FATFS library with VFS, with prefix given by base_prefix variable
*
* This function is intended to make example code more compact.
* For real world applications, developers should implement the logic of
* probing SD card, locating and mounting partition, and registering FATFS in VFS,
* with proper error checking and handling of exceptional conditions.
*
* @note This function try to attach the new SD SPI device to the bus specified in host_config.
* Make sure the SPI bus specified in `host_config->slot` have been initialized by
* `spi_bus_initialize()` before.
*
* @param base_path path where partition should be registered (e.g. "/sdcard")
* @param host_config_input Pointer to structure describing SDMMC host. This structure can be
* initialized using SDSPI_HOST_DEFAULT() macro.
* @param slot_config Pointer to structure with slot configuration.
* For SPI peripheral, pass a pointer to sdspi_device_config_t
* structure initialized using SDSPI_DEVICE_CONFIG_DEFAULT().
* @param mount_config pointer to structure with extra parameters for mounting FATFS
* @param[out] out_card If not NULL, pointer to the card information structure will be returned via
* this argument. It is suggested to hold this handle and use it to unmount the card later if
* needed. Otherwise it's not suggested to use more than one card at the same time and unmount one
* of them in your application.
* @return
* - ESP_OK on success
* - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called
* - ESP_ERR_NO_MEM if memory can not be allocated
* - ESP_FAIL if partition can not be mounted
* - other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers
*/
esp_err_t esp_vfs_fat_sdspi_mount_mh(const char* base_path, const sdmmc_host_t* host_config_input, const sdspi_device_config_t* slot_config, const esp_vfs_fat_mount_config_t* mount_config, sdmmc_card_t** out_card);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,129 @@
#include "esp_log.h"
#include <esp_http_server.h>
#include "../../include/defines.h"
#include "ClassLogFile.h"
#include "freertos/ringbuf.h"
#include "psram.h"
#include "websocket.h"
#define MAX_MESSAGE_LENGTH 100
static const char *TAG = "WEBSOCKET";
static httpd_handle_t server = NULL;
static httpd_handle_t websocket_handle = NULL;
/*
* Structure holding server handle and message
* in order to use out of request send */
struct async_resp_arg {
httpd_handle_t hd;
char message[MAX_MESSAGE_LENGTH];
};
/*
* async send function, which we put into the httpd work queue
*/
static void websocket_send_pending_message(void *arg) {
esp_err_t ret;
struct async_resp_arg *resp_arg = (struct async_resp_arg *)arg;
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Sending Websocket message: '" + std::string(resp_arg->message) + "'");
httpd_ws_frame_t ws_pkt;
memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t));
ws_pkt.payload = (uint8_t *)resp_arg->message;
ws_pkt.len = strlen(resp_arg->message);
ws_pkt.type = HTTPD_WS_TYPE_TEXT;
static size_t max_clients = CONFIG_LWIP_MAX_LISTENING_TCP;
size_t fds = max_clients;
int client_fds[max_clients];
ret = httpd_get_client_list(server, &fds, client_fds);
if (ret != ESP_OK) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to get Websocket client ist: " + std::to_string(ret) + "!");
free_psram_heap("websocket msg", resp_arg);
return;
}
/* Send it to all websocket clients */
for (int i = 0; i < fds; i++) {
int client_info = httpd_ws_get_fd_info(server, client_fds[i]);
if (client_info == HTTPD_WS_CLIENT_WEBSOCKET) {
httpd_ws_send_frame_async(websocket_handle, client_fds[i], &ws_pkt);
}
}
free_psram_heap("websocket msg", resp_arg);
}
esp_err_t schedule_websocket_message(std::string message) {
// return 0;
esp_err_t ret;
if (websocket_handle == NULL) { // No websocket connecten open
return ESP_OK;
}
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Scheduled websocket message: '" + message + "'");
struct async_resp_arg *resp_arg = (struct async_resp_arg *)malloc_psram_heap("websocket msg",
sizeof(struct async_resp_arg), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (resp_arg == NULL) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to malloc memory for scheduled websocket message!");
return ESP_ERR_NO_MEM;
}
strncpy(resp_arg->message, message.c_str(), MAX_MESSAGE_LENGTH);
ret = httpd_queue_work(websocket_handle, websocket_send_pending_message, resp_arg);
if (ret != ESP_OK) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Websocket Scheduling failed: " + std::to_string(ret) + "!");
free_psram_heap("websocket msg", resp_arg);
}
return ret;
}
static esp_err_t ws_handler(httpd_req_t *req) {
if (req->method == HTTP_GET) {
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Handshake done, the new websocket connection was opened");
websocket_handle = req->handle;
}
return ESP_OK;
}
static const httpd_uri_t ws_uri = {
.uri = "/ws",
.method = HTTP_GET,
.handler = ws_handler,
.user_ctx = NULL,
.is_websocket = true
};
esp_err_t start_websocket_server(httpd_handle_t _server) {
esp_err_t ret;
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init Websocket Server");
server = _server;
// Registering the ws handler
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Registering URI handler");
ret = httpd_register_uri_handler(server, &ws_uri);
if (ret != ESP_OK) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Registering Websocket URI handler failed: " + std::to_string(ret));
}
return ret;
}

View File

@@ -0,0 +1,10 @@
#ifndef WEBSOCKET_H
#define WEBSOCKET_H
#include <esp_http_server.h>
esp_err_t start_websocket_server(httpd_handle_t server);
esp_err_t schedule_websocket_message(std::string message);
#endif // WEBSOCKET_H

View File

@@ -443,7 +443,7 @@ void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
//free_psram_heap(std::string(TAG) + "->rgb_image (LoadFromMemory)", rgb_image);
}
rgb_image = stbi_load_from_memory(_buffer, len, &width, &height, &channels, STBI_rgb);
rgb_image = stbi_load_from_memory(_buffer, len, &width, &height, &channels, 3);
bpp = channels;
ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
@@ -459,44 +459,6 @@ void CImageBasis::LoadFromMemory(stbi_uc *_buffer, int len)
}
void CImageBasis::crop_image(unsigned short cropLeft, unsigned short cropRight, unsigned short cropTop, unsigned short cropBottom)
{
unsigned int maxTopIndex = cropTop * width * channels;
unsigned int minBottomIndex = ((width*height) - (cropBottom * width)) * channels;
unsigned short maxX = width - cropRight; // In pixels
unsigned short newWidth = width - cropLeft - cropRight;
unsigned short newHeight = height - cropTop - cropBottom;
unsigned int writeIndex = 0;
// Loop over all bytes
for (int i = 0; i < width * height * channels; i += channels) {
// Calculate current X, Y pixel position
int x = (i/channels) % width;
// Crop from the top
if (i < maxTopIndex) { continue; }
// Crop from the bottom
if (i > minBottomIndex) { continue; }
// Crop from the left
if (x <= cropLeft) { continue; }
// Crop from the right
if (x > maxX) { continue; }
// If we get here, keep the pixels
for (int c = 0; c < channels; c++) {
rgb_image[writeIndex++] = rgb_image[i+c];
}
}
// Set the new dimensions of the framebuffer for further use.
width = newWidth;
height = newHeight;
}
CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom)
{
name = _name;
@@ -636,20 +598,6 @@ CImageBasis::CImageBasis(string _name, uint8_t* _rgb_image, int _channels, int _
}
void CImageBasis::Negative(void)
{
RGBImageLock();
for (int i = 0; i < width * height * channels; i += channels) {
for (int c = 0; c < channels; c++) {
rgb_image[i+c] = 255 - rgb_image[i+c];
}
}
RGBImageRelease();
}
void CImageBasis::Contrast(float _contrast) //input range [-100..100]
{
stbi_uc* p_source;

View File

@@ -56,7 +56,6 @@ class CImageBasis
void drawEllipse(int x1, int y1, int radx, int rady, int r, int g, int b, int thickness = 1);
void setPixelColor(int x, int y, int r, int g, int b);
void Negative(void);
void Contrast(float _contrast);
bool ImageOkay();
bool CopyFromMemory(uint8_t* _source, int _size);
@@ -75,7 +74,6 @@ class CImageBasis
void Resize(int _new_dx, int _new_dy);
void Resize(int _new_dx, int _new_dy, CImageBasis *_target);
void crop_image(unsigned short cropLeft, unsigned short cropRight, unsigned short cropTop, unsigned short cropBottom);
void LoadFromMemory(stbi_uc *_buffer, int len);

View File

@@ -1,309 +1,353 @@
#include <string>
#include "CRotateImage.h"
#include "psram.h"
static const char *TAG = "C ROTATE IMG";
CRotateImage::CRotateImage(std::string _name, CImageBasis *_org, CImageBasis *_temp, bool _flip) : CImageBasis(_name)
{
rgb_image = _org->rgb_image;
channels = _org->channels;
width = _org->width;
height = _org->height;
bpp = _org->bpp;
externalImage = true;
ImageTMP = _temp;
ImageOrg = _org;
islocked = false;
doflip = _flip;
}
void CRotateImage::Rotate(float _angle, int _centerx, int _centery)
{
int org_width, org_height;
float m[2][3];
float x_center = _centerx;
float y_center = _centery;
_angle = _angle / 180 * M_PI;
if (doflip)
{
org_width = width;
org_height = height;
height = org_width;
width = org_height;
x_center = x_center - (org_width/2) + (org_height/2);
y_center = y_center + (org_width/2) - (org_height/2);
if (ImageOrg)
{
ImageOrg->height = height;
ImageOrg->width = width;
}
}
else
{
org_width = width;
org_height = height;
}
m[0][0] = cos(_angle);
m[0][1] = sin(_angle);
m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
m[1][0] = -m[0][1];
m[1][1] = m[0][0];
m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
if (doflip)
{
m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
}
int memsize = width * height * channels;
uint8_t* odata;
if (ImageTMP)
{
odata = ImageTMP->RGBImageLock();
}
else
{
odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
}
int x_source, y_source;
stbi_uc* p_target;
stbi_uc* p_source;
RGBImageLock();
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
p_target = odata + (channels * (y * width + x));
x_source = int(m[0][0] * x + m[0][1] * y);
y_source = int(m[1][0] * x + m[1][1] * y);
x_source += int(m[0][2]);
y_source += int(m[1][2]);
if ((x_source >= 0) && (x_source < org_width) && (y_source >= 0) && (y_source < org_height))
{
p_source = rgb_image + (channels * (y_source * org_width + x_source));
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = p_source[_channels];
}
else
{
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = 255;
}
}
// memcpy(rgb_image, odata, memsize);
memCopy(odata, rgb_image, memsize);
if (!ImageTMP)
{
free_psram_heap(std::string(TAG) + "->odata", odata);
}
if (ImageTMP)
ImageTMP->RGBImageRelease();
RGBImageRelease();
}
void CRotateImage::RotateAntiAliasing(float _angle, int _centerx, int _centery)
{
int org_width, org_height;
float m[2][3];
float x_center = _centerx;
float y_center = _centery;
_angle = _angle / 180 * M_PI;
if (doflip)
{
org_width = width;
org_height = height;
height = org_width;
width = org_height;
x_center = x_center - (org_width/2) + (org_height/2);
y_center = y_center + (org_width/2) - (org_height/2);
if (ImageOrg)
{
ImageOrg->height = height;
ImageOrg->width = width;
}
}
else
{
org_width = width;
org_height = height;
}
m[0][0] = cos(_angle);
m[0][1] = sin(_angle);
m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
m[1][0] = -m[0][1];
m[1][1] = m[0][0];
m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
if (doflip)
{
m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
}
int memsize = width * height * channels;
uint8_t* odata;
if (ImageTMP)
{
odata = ImageTMP->RGBImageLock();
}
else
{
odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
}
int x_source_1, y_source_1, x_source_2, y_source_2;
float x_source, y_source;
float quad_ul, quad_ur, quad_ol, quad_or;
stbi_uc* p_target;
stbi_uc *p_source_ul, *p_source_ur, *p_source_ol, *p_source_or;
RGBImageLock();
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
p_target = odata + (channels * (y * width + x));
x_source = (m[0][0] * x + m[0][1] * y);
y_source = (m[1][0] * x + m[1][1] * y);
x_source += (m[0][2]);
y_source += (m[1][2]);
x_source_1 = (int)x_source;
x_source_2 = x_source_1 + 1;
y_source_1 = (int)y_source;
y_source_2 = y_source_1 + 1;
quad_ul = (x_source_2 - x_source) * (y_source_2 - y_source);
quad_ur = (1- (x_source_2 - x_source)) * (y_source_2 - y_source);
quad_or = (x_source_2 - x_source) * (1-(y_source_2 - y_source));
quad_ol = (1- (x_source_2 - x_source)) * (1-(y_source_2 - y_source));
if ((x_source_1 >= 0) && (x_source_2 < org_width) && (y_source_1 >= 0) && (y_source_2 < org_height))
{
p_source_ul = rgb_image + (channels * (y_source_1 * org_width + x_source_1));
p_source_ur = rgb_image + (channels * (y_source_1 * org_width + x_source_2));
p_source_or = rgb_image + (channels * (y_source_2 * org_width + x_source_1));
p_source_ol = rgb_image + (channels * (y_source_2 * org_width + x_source_2));
for (int _channels = 0; _channels < channels; ++_channels)
{
p_target[_channels] = (int)((float)p_source_ul[_channels] * quad_ul
+ (float)p_source_ur[_channels] * quad_ur
+ (float)p_source_or[_channels] * quad_or
+ (float)p_source_ol[_channels] * quad_ol);
}
}
else
{
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = 255;
}
}
// memcpy(rgb_image, odata, memsize);
memCopy(odata, rgb_image, memsize);
if (!ImageTMP)
{
free_psram_heap(std::string(TAG) + "->odata", odata);
}
if (ImageTMP)
ImageTMP->RGBImageRelease();
RGBImageRelease();
}
void CRotateImage::Rotate(float _angle)
{
// ESP_LOGD(TAG, "width %d, height %d", width, height);
Rotate(_angle, width / 2, height / 2);
}
void CRotateImage::RotateAntiAliasing(float _angle)
{
// ESP_LOGD(TAG, "width %d, height %d", width, height);
RotateAntiAliasing(_angle, width / 2, height / 2);
}
void CRotateImage::Translate(int _dx, int _dy)
{
int memsize = width * height * channels;
uint8_t* odata;
if (ImageTMP)
{
odata = ImageTMP->RGBImageLock();
}
else
{
odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
}
int x_source, y_source;
stbi_uc* p_target;
stbi_uc* p_source;
RGBImageLock();
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
p_target = odata + (channels * (y * width + x));
x_source = x - _dx;
y_source = y - _dy;
if ((x_source >= 0) && (x_source < width) && (y_source >= 0) && (y_source < height))
{
p_source = rgb_image + (channels * (y_source * width + x_source));
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = p_source[_channels];
}
else
{
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = 255;
}
}
// memcpy(rgb_image, odata, memsize);
memCopy(odata, rgb_image, memsize);
if (!ImageTMP)
{
free_psram_heap(std::string(TAG) + "->odata", odata);
}
if (ImageTMP)
{
ImageTMP->RGBImageRelease();
}
RGBImageRelease();
}
#include <string>
#include "CRotateImage.h"
#include "psram.h"
static const char *TAG = "C ROTATE IMG";
CRotateImage::CRotateImage(std::string _name, CImageBasis *_org, CImageBasis *_temp, bool _flip) : CImageBasis(_name)
{
rgb_image = _org->rgb_image;
channels = _org->channels;
width = _org->width;
height = _org->height;
bpp = _org->bpp;
externalImage = true;
ImageTMP = _temp;
ImageOrg = _org;
islocked = false;
doflip = _flip;
}
void CRotateImage::Mirror(){
int memsize = width * height * channels;
uint8_t* odata;
if (ImageTMP)
{
odata = ImageTMP->RGBImageLock();
}
else
{
odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
}
int x_source, y_source;
stbi_uc* p_target;
stbi_uc* p_source;
RGBImageLock();
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
p_target = odata + (channels * (y * width + x));
x_source = width - x;
y_source = y;
p_source = rgb_image + (channels * (y_source * width + x_source));
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = p_source[_channels];
}
// memcpy(rgb_image, odata, memsize);
memCopy(odata, rgb_image, memsize);
if (!ImageTMP)
free_psram_heap(std::string(TAG) + "->odata", odata);
if (ImageTMP)
ImageTMP->RGBImageRelease();
RGBImageRelease();
}
void CRotateImage::Rotate(float _angle, int _centerx, int _centery)
{
int org_width, org_height;
float m[2][3];
float x_center = _centerx;
float y_center = _centery;
_angle = _angle / 180 * M_PI;
if (doflip)
{
org_width = width;
org_height = height;
height = org_width;
width = org_height;
x_center = x_center - (org_width/2) + (org_height/2);
y_center = y_center + (org_width/2) - (org_height/2);
if (ImageOrg)
{
ImageOrg->height = height;
ImageOrg->width = width;
}
}
else
{
org_width = width;
org_height = height;
}
m[0][0] = cos(_angle);
m[0][1] = sin(_angle);
m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
m[1][0] = -m[0][1];
m[1][1] = m[0][0];
m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
if (doflip)
{
m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
}
int memsize = width * height * channels;
uint8_t* odata;
if (ImageTMP)
{
odata = ImageTMP->RGBImageLock();
}
else
{
odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
}
int x_source, y_source;
stbi_uc* p_target;
stbi_uc* p_source;
RGBImageLock();
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
p_target = odata + (channels * (y * width + x));
x_source = int(m[0][0] * x + m[0][1] * y);
y_source = int(m[1][0] * x + m[1][1] * y);
x_source += int(m[0][2]);
y_source += int(m[1][2]);
if ((x_source >= 0) && (x_source < org_width) && (y_source >= 0) && (y_source < org_height))
{
p_source = rgb_image + (channels * (y_source * org_width + x_source));
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = p_source[_channels];
}
else
{
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = 255;
}
}
// memcpy(rgb_image, odata, memsize);
memCopy(odata, rgb_image, memsize);
if (!ImageTMP)
{
free_psram_heap(std::string(TAG) + "->odata", odata);
}
if (ImageTMP)
ImageTMP->RGBImageRelease();
RGBImageRelease();
}
void CRotateImage::RotateAntiAliasing(float _angle, int _centerx, int _centery)
{
int org_width, org_height;
float m[2][3];
float x_center = _centerx;
float y_center = _centery;
_angle = _angle / 180 * M_PI;
if (doflip)
{
org_width = width;
org_height = height;
height = org_width;
width = org_height;
x_center = x_center - (org_width/2) + (org_height/2);
y_center = y_center + (org_width/2) - (org_height/2);
if (ImageOrg)
{
ImageOrg->height = height;
ImageOrg->width = width;
}
}
else
{
org_width = width;
org_height = height;
}
m[0][0] = cos(_angle);
m[0][1] = sin(_angle);
m[0][2] = (1 - m[0][0]) * x_center - m[0][1] * y_center;
m[1][0] = -m[0][1];
m[1][1] = m[0][0];
m[1][2] = m[0][1] * x_center + (1 - m[0][0]) * y_center;
if (doflip)
{
m[0][2] = m[0][2] + (org_width/2) - (org_height/2);
m[1][2] = m[1][2] - (org_width/2) + (org_height/2);
}
int memsize = width * height * channels;
uint8_t* odata;
if (ImageTMP)
{
odata = ImageTMP->RGBImageLock();
}
else
{
odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
}
int x_source_1, y_source_1, x_source_2, y_source_2;
float x_source, y_source;
float quad_ul, quad_ur, quad_ol, quad_or;
stbi_uc* p_target;
stbi_uc *p_source_ul, *p_source_ur, *p_source_ol, *p_source_or;
RGBImageLock();
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
p_target = odata + (channels * (y * width + x));
x_source = (m[0][0] * x + m[0][1] * y);
y_source = (m[1][0] * x + m[1][1] * y);
x_source += (m[0][2]);
y_source += (m[1][2]);
x_source_1 = (int)x_source;
x_source_2 = x_source_1 + 1;
y_source_1 = (int)y_source;
y_source_2 = y_source_1 + 1;
quad_ul = (x_source_2 - x_source) * (y_source_2 - y_source);
quad_ur = (1- (x_source_2 - x_source)) * (y_source_2 - y_source);
quad_or = (x_source_2 - x_source) * (1-(y_source_2 - y_source));
quad_ol = (1- (x_source_2 - x_source)) * (1-(y_source_2 - y_source));
if ((x_source_1 >= 0) && (x_source_2 < org_width) && (y_source_1 >= 0) && (y_source_2 < org_height))
{
p_source_ul = rgb_image + (channels * (y_source_1 * org_width + x_source_1));
p_source_ur = rgb_image + (channels * (y_source_1 * org_width + x_source_2));
p_source_or = rgb_image + (channels * (y_source_2 * org_width + x_source_1));
p_source_ol = rgb_image + (channels * (y_source_2 * org_width + x_source_2));
for (int _channels = 0; _channels < channels; ++_channels)
{
p_target[_channels] = (int)((float)p_source_ul[_channels] * quad_ul
+ (float)p_source_ur[_channels] * quad_ur
+ (float)p_source_or[_channels] * quad_or
+ (float)p_source_ol[_channels] * quad_ol);
}
}
else
{
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = 255;
}
}
// memcpy(rgb_image, odata, memsize);
memCopy(odata, rgb_image, memsize);
if (!ImageTMP)
{
free_psram_heap(std::string(TAG) + "->odata", odata);
}
if (ImageTMP)
ImageTMP->RGBImageRelease();
RGBImageRelease();
}
void CRotateImage::Rotate(float _angle)
{
// ESP_LOGD(TAG, "width %d, height %d", width, height);
Rotate(_angle, width / 2, height / 2);
}
void CRotateImage::RotateAntiAliasing(float _angle)
{
// ESP_LOGD(TAG, "width %d, height %d", width, height);
RotateAntiAliasing(_angle, width / 2, height / 2);
}
void CRotateImage::Translate(int _dx, int _dy)
{
int memsize = width * height * channels;
uint8_t* odata;
if (ImageTMP)
{
odata = ImageTMP->RGBImageLock();
}
else
{
odata = (unsigned char*)malloc_psram_heap(std::string(TAG) + "->odata", memsize, MALLOC_CAP_SPIRAM);
}
int x_source, y_source;
stbi_uc* p_target;
stbi_uc* p_source;
RGBImageLock();
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
p_target = odata + (channels * (y * width + x));
x_source = x - _dx;
y_source = y - _dy;
if ((x_source >= 0) && (x_source < width) && (y_source >= 0) && (y_source < height))
{
p_source = rgb_image + (channels * (y_source * width + x_source));
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = p_source[_channels];
}
else
{
for (int _channels = 0; _channels < channels; ++_channels)
p_target[_channels] = 255;
}
}
// memcpy(rgb_image, odata, memsize);
memCopy(odata, rgb_image, memsize);
if (!ImageTMP)
{
free_psram_heap(std::string(TAG) + "->odata", odata);
}
if (ImageTMP)
{
ImageTMP->RGBImageRelease();
}
RGBImageRelease();
}

View File

@@ -1,28 +1,29 @@
#pragma once
#ifndef CROTATEIMAGE_H
#define CROTATEIMAGE_H
#include "CImageBasis.h"
class CRotateImage: public CImageBasis
{
public:
CImageBasis *ImageTMP, *ImageOrg;
bool doflip;
CRotateImage(std::string name, std::string _image, bool _flip = false) : CImageBasis(name, _image) {ImageTMP = NULL; ImageOrg = NULL; doflip = _flip;};
CRotateImage(std::string name, uint8_t* _rgb_image, int _channels, int _width, int _height, int _bpp, bool _flip = false) : CImageBasis(name, _rgb_image, _channels, _width, _height, _bpp) {ImageTMP = NULL; ImageOrg = NULL; doflip = _flip;};
CRotateImage(std::string name, CImageBasis *_org, CImageBasis *_temp, bool _flip = false);
void Rotate(float _angle);
void RotateAntiAliasing(float _angle);
void Rotate(float _angle, int _centerx, int _centery);
void RotateAntiAliasing(float _angle, int _centerx, int _centery);
void Translate(int _dx, int _dy);
};
#pragma once
#ifndef CROTATEIMAGE_H
#define CROTATEIMAGE_H
#include "CImageBasis.h"
class CRotateImage: public CImageBasis
{
public:
CImageBasis *ImageTMP, *ImageOrg;
bool doflip;
CRotateImage(std::string name, std::string _image, bool _flip = false) : CImageBasis(name, _image) {ImageTMP = NULL; ImageOrg = NULL; doflip = _flip;};
CRotateImage(std::string name, uint8_t* _rgb_image, int _channels, int _width, int _height, int _bpp, bool _flip = false) : CImageBasis(name, _rgb_image, _channels, _width, _height, _bpp) {ImageTMP = NULL; ImageOrg = NULL; doflip = _flip;};
CRotateImage(std::string name, CImageBasis *_org, CImageBasis *_temp, bool _flip = false);
void Rotate(float _angle);
void RotateAntiAliasing(float _angle);
void Rotate(float _angle, int _centerx, int _centery);
void RotateAntiAliasing(float _angle, int _centerx, int _centery);
void Translate(int _dx, int _dy);
void Mirror();
};
#endif //CROTATEIMAGE_H

View File

@@ -2,6 +2,6 @@ FILE(GLOB_RECURSE app_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.*)
idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "."
REQUIRES esp_http_client jomjol_logfile)
REQUIRES tflite-lib esp_http_client jomjol_logfile)

View File

@@ -5,7 +5,6 @@
#include <time.h>
#include "ClassLogFile.h"
#include "esp_http_client.h"
#include "time_sntp.h"
#include "../../include/defines.h"
@@ -17,21 +16,21 @@ std::string _influxDBUser;
std::string _influxDBPassword;
std::string _influxDB_V2_URI;
std::string _influxDB_V2_Bucket;
std::string _influxDB_V2_Database;
std::string _influxDB_V2_Token;
std::string _influxDB_V2_Org;
static esp_err_t http_event_handler(esp_http_client_event_t *evt);
void InfluxDB_V2_Init(std::string _uri, std::string _bucket, std::string _org, std::string _token)
void InfluxDB_V2_Init(std::string _uri, std::string _database, std::string _org, std::string _token)
{
_influxDB_V2_URI = _uri;
_influxDB_V2_Bucket = _bucket;
_influxDB_V2_Database = _database;
_influxDB_V2_Org = _org;
_influxDB_V2_Token = _token;
}
void InfluxDB_V2_Publish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC)
void InfluxDB_V2_Publish(std::string _measurement, std::string _key, std::string _content, std::string _timestamp)
{
char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
esp_http_client_config_t http_config = {
@@ -42,20 +41,32 @@ void InfluxDB_V2_Publish(std::string _measurement, std::string _key, std::string
.user_data = response_buffer
};
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "InfluxDB_V2_Publish - Key: " + _key + ", Content: " + _content + ", timeUTC: " + std::to_string(_timeUTC));
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "InfluxDB_V2_Publish - Key: " + _key + ", Content: " + _content + ", Timestamp: " + _timestamp);
std::string payload;
char nowTimestamp[21];
if (_timeUTC > 0)
if (_timestamp.length() > 0)
{
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Timestamp (UTC): " + std::to_string(_timeUTC));
sprintf(nowTimestamp,"%ld000000000", _timeUTC); // UTC
struct tm tm;
strptime(_timestamp.c_str(), PREVALUE_TIME_FORMAT_OUTPUT, &tm);
time_t t = mktime(&tm); // Time in Localtime (looks like timezone is not used by strptime)
// struct tm * ptm;
// ptm = gmtime ( &t );
// time_t utc = mktime(ptm);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Use handover timestamp: " + _timestamp + " converted GMT timestamp: " + std::to_string(t));
// utc = 2*t - utc; // Take care of timezone (looks difficult, but is easy: t = t + (t - utc), weil t-utc = timezone)
// LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "time conversion utc after: " + std::to_string(utc));
sprintf(nowTimestamp,"%ld000000000", (long) t); // UTC
payload = _measurement + " " + _key + "=" + _content + " " + nowTimestamp;
}
else
{
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "no timestamp given");
payload = _measurement + " " + _key + "=" + _content;
}
@@ -63,7 +74,7 @@ void InfluxDB_V2_Publish(std::string _measurement, std::string _key, std::string
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "sending line to influxdb:" + payload);
std::string apiURI = _influxDB_V2_URI + "/api/v2/write?org=" + _influxDB_V2_Org + "&bucket=" + _influxDB_V2_Bucket;
std::string apiURI = _influxDB_V2_URI + "/api/v2/write?org=" + _influxDB_V2_Org + "&bucket=" + _influxDB_V2_Database;
apiURI.shrink_to_fit();
http_config.url = apiURI.c_str();
ESP_LOGI(TAG, "http_config: %s", http_config.url); // Add mark on log to see when it restarted
@@ -105,7 +116,7 @@ static esp_err_t http_event_handler(esp_http_client_event_t *evt)
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client Error encountered");
break;
case HTTP_EVENT_ON_CONNECTED:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client connected");
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client Error encountered");
ESP_LOGI(TAG, "HTTP Client Connected");
break;
case HTTP_EVENT_HEADERS_SENT:
@@ -130,7 +141,7 @@ static esp_err_t http_event_handler(esp_http_client_event_t *evt)
return ESP_OK;
}
void InfluxDBPublish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC) {
void InfluxDBPublish(std::string _measurement, std::string _key, std::string _content, std::string _timestamp) {
char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
esp_http_client_config_t http_config = {
.user_agent = "ESP32 Meter reader",
@@ -149,17 +160,29 @@ void InfluxDBPublish(std::string _measurement, std::string _key, std::string _co
std::string payload;
char nowTimestamp[21];
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "InfluxDBPublish - Key: " + _key + ", Content: " + _content + ", timeUTC: " + std::to_string(_timeUTC));
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "InfluxDBPublish - Key: " + _key + ", Content: " + _content + ", Timestamp: " + _timestamp);
if (_timeUTC > 0)
if (_timestamp.length() > 0)
{
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Timestamp (UTC): " + std::to_string(_timeUTC));
sprintf(nowTimestamp,"%ld000000000", _timeUTC); // UTC
struct tm tm;
strptime(_timestamp.c_str(), PREVALUE_TIME_FORMAT_OUTPUT, &tm);
time_t t = mktime(&tm); // Time in Localtime (looks like timezone is not used by strptime)
// struct tm * ptm;
// ptm = gmtime ( &t );
// time_t utc = mktime(ptm);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Use handover timestamp: " + _timestamp + " converted GMT timestamp: " + std::to_string(t));
// utc = 2*t - utc; // Take care of timezone (looks difficult, but is easy: t = t + (t - utc), weil t-utc = timezone)
// LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "time conversion utc after: " + std::to_string(utc));
sprintf(nowTimestamp,"%ld000000000", (long) t); // UTC
payload = _measurement + " " + _key + "=" + _content + " " + nowTimestamp;
}
else
{
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "no timestamp given");
payload = _measurement + " " + _key + "=" + _content;
}
@@ -168,7 +191,7 @@ void InfluxDBPublish(std::string _measurement, std::string _key, std::string _co
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "sending line to influxdb:" + payload);
// use the default retention policy of the bucket
// use the default retention policy of the database
std::string apiURI = _influxDBURI + "/write?db=" + _influxDBDatabase;
// std::string apiURI = _influxDBURI + "/api/v2/write?bucket=" + _influxDBDatabase + "/";

View File

@@ -10,11 +10,11 @@
// Interface to InfluxDB v1.x
void InfluxDBInit(std::string _influxDBURI, std::string _database, std::string _user, std::string _password);
void InfluxDBPublish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC);
void InfluxDBPublish(std::string _measurement, std::string _key, std::string _content, std::string _timestamp);
// Interface to InfluxDB v2.x
void InfluxDB_V2_Init(std::string _uri, std::string _bucket, std::string _org, std::string _token);
void InfluxDB_V2_Publish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC);
void InfluxDB_V2_Init(std::string _uri, std::string _database, std::string _org, std::string _token);
void InfluxDB_V2_Publish(std::string _measurement, std::string _key, std::string _content, std::string _timestamp);

View File

@@ -32,7 +32,7 @@ void ClassLogFile::WriteHeapInfo(std::string _id)
}
void ClassLogFile::WriteToData(std::string _timestamp, std::string _name, std::string _ReturnRawValue, std::string _ReturnValue, std::string _ReturnPreValue, std::string _ReturnRateValue, std::string _ReturnChangeAbsolute, std::string _ErrorMessageText, std::string _digit, std::string _analog)
void ClassLogFile::WriteToData(std::string _timestamp, std::string _name, std::string _ReturnRawValue, std::string _ReturnValue, std::string _ReturnPreValue, std::string _ReturnRateValue, std::string _ReturnChangeAbsolute, std::string _ErrorMessageText, std::string _digital, std::string _analog)
{
ESP_LOGD(TAG, "Start WriteToData");
time_t rawtime;
@@ -67,7 +67,7 @@ void ClassLogFile::WriteToData(std::string _timestamp, std::string _name, std::s
fputs(_ReturnChangeAbsolute.c_str(), pFile);
fputs(",", pFile);
fputs(_ErrorMessageText.c_str(), pFile);
fputs(_digit.c_str(), pFile);
fputs(_digital.c_str(), pFile);
fputs(_analog.c_str(), pFile);
fputs("\n", pFile);

View File

@@ -39,8 +39,8 @@ public:
void RemoveOldLogFile();
void RemoveOldDataLog();
// void WriteToData(std::string _ReturnRawValue, std::string _ReturnValue, std::string _ReturnPreValue, std::string _ErrorMessageText, std::string _digit, std::string _analog);
void WriteToData(std::string _timestamp, std::string _name, std::string _ReturnRawValue, std::string _ReturnValue, std::string _ReturnPreValue, std::string _ReturnRateValue, std::string _ReturnChangeAbsolute, std::string _ErrorMessageText, std::string _digit, std::string _analog);
// void WriteToData(std::string _ReturnRawValue, std::string _ReturnValue, std::string _ReturnPreValue, std::string _ErrorMessageText, std::string _digital, std::string _analog);
void WriteToData(std::string _timestamp, std::string _name, std::string _ReturnRawValue, std::string _ReturnValue, std::string _ReturnPreValue, std::string _ReturnRateValue, std::string _ReturnChangeAbsolute, std::string _ErrorMessageText, std::string _digital, std::string _analog);
std::string GetCurrentFileName();

View File

@@ -2,4 +2,4 @@ FILE(GLOB_RECURSE app_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.*)
idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "."
REQUIRES esp_timer esp-tflite-micro mqtt jomjol_tfliteclass jomjol_helper jomjol_mqtt jomjol_wlan json)
REQUIRES esp_timer tflite-lib mqtt jomjol_tfliteclass jomjol_helper jomjol_mqtt jomjol_wlan json)

View File

@@ -2,9 +2,6 @@
#include "interface_mqtt.h"
#include "esp_log.h"
#if DEBUG_DETAIL_ON
#include "esp_timer.h"
#endif
#include "connect_wlan.h"
#include "mqtt_client.h"
#include "ClassLogFile.h"
@@ -12,11 +9,6 @@
#include "cJSON.h"
#include "../../include/defines.h"
#if DEBUG_DETAIL_ON
#include "esp_timer.h"
#endif
static const char *TAG = "MQTT IF";
std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
@@ -34,8 +26,7 @@ bool mqtt_initialized = false;
bool mqtt_connected = false;
esp_mqtt_client_handle_t client = NULL;
std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic, domoticz_in_topic;
std::string caCert, clientCert, clientKey;
std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic;
int keepalive;
bool SetRetainFlag;
void (*callbackOnConnected)(std::string, bool) = NULL;
@@ -173,10 +164,6 @@ static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, not authorized. Check username/password (0x05)");
}
else {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Other event id:" + event->error_handle->connect_return_code);
ESP_LOGE(TAG, "Other event id:%d", event->error_handle->connect_return_code);
}
#ifdef DEBUG_DETAIL_ON
ESP_LOGD(TAG, "MQTT_EVENT_ERROR - esp_mqtt_error_codes:");
@@ -205,8 +192,7 @@ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_
bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
std::string _maintopic, std::string _domoticz_in_topic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
std::string _cacertfilename, std::string _clientcertfilename, std::string _clientkeyfilename,
std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
int _keepalive, bool _SetRetainFlag, void *_callbackOnConnected) {
if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0))
{
@@ -222,28 +208,8 @@ bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _us
keepalive = _keepalive;
SetRetainFlag = _SetRetainFlag;
maintopic = _maintopic;
domoticz_in_topic = _domoticz_in_topic;
callbackOnConnected = ( void (*)(std::string, bool) )(_callbackOnConnected);
if (_clientcertfilename.length() && _clientkeyfilename.length()){
std::ifstream cert_ifs(_clientcertfilename);
std::string cert_content((std::istreambuf_iterator<char>(cert_ifs)), (std::istreambuf_iterator<char>()));
clientCert = cert_content;
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using clientCert: " + _clientcertfilename);
std::ifstream key_ifs(_clientkeyfilename);
std::string key_content((std::istreambuf_iterator<char>(key_ifs)), (std::istreambuf_iterator<char>()));
clientKey = key_content;
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using clientKey: " + _clientkeyfilename);
}
if (_cacertfilename.length() ){
std::ifstream ifs(_cacertfilename);
std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
caCert = content;
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using caCert: " + _cacertfilename);
}
if (_user.length() && _password.length()){
user = _user;
password = _password;
@@ -297,20 +263,6 @@ int MQTT_Init() {
mqtt_cfg.session.keepalive = keepalive;
mqtt_cfg.buffer.size = 1536; // size of MQTT send/receive buffer (Default: 1024)
if (caCert.length()){
mqtt_cfg.broker.verification.certificate = caCert.c_str();
mqtt_cfg.broker.verification.certificate_len = caCert.length() + 1;
mqtt_cfg.broker.verification.skip_cert_common_name_check = true;
}
if (clientCert.length() && clientKey.length()){
mqtt_cfg.credentials.authentication.certificate = clientCert.c_str();
mqtt_cfg.credentials.authentication.certificate_len = clientCert.length() + 1;
mqtt_cfg.credentials.authentication.key = clientKey.c_str();
mqtt_cfg.credentials.authentication.key_len = clientKey.length() + 1;
}
if (user.length() && password.length()){
mqtt_cfg.credentials.username = user.c_str();
mqtt_cfg.credentials.authentication.password = password.c_str();
@@ -389,7 +341,13 @@ bool mqtt_handler_flow_start(std::string _topic, char* _data, int _data_len)
{
ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
MQTTCtrlFlowStart(_topic);
if (_data_len > 0) {
MQTTCtrlFlowStart(_topic);
}
else {
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_flow_start: handler called, but no data");
}
return ESP_OK;
}
@@ -408,10 +366,8 @@ bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len)
if (cJSON_IsNumber(value)) { // Check if value is a number
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_set_prevalue called: numbersname: " + std::string(numbersname->valuestring) +
", value: " + std::to_string(value->valuedouble));
if (flowctrl.UpdatePrevalue(std::to_string(value->valuedouble), std::string(numbersname->valuestring), true)) {
cJSON_Delete(jsonData);
if (flowctrl.UpdatePrevalue(std::to_string(value->valuedouble), std::string(numbersname->valuestring), true))
return ESP_OK;
}
}
else {
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: value not a valid number (\"value\": 12345.12345)");
@@ -420,7 +376,6 @@ bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len)
else {
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: numbersname not a valid string (\"numbersname\": \"main\")");
}
cJSON_Delete(jsonData);
}
else {
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: handler called, but no data received");

View File

@@ -10,8 +10,7 @@
#include <functional>
bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
std::string _maintopic, std::string _domoticz_in_topic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
std::string _cacertfilename, std::string _clientcertfilename, std::string _clientkeyfilename,
std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
int _keepalive, bool SetRetainFlag, void *callbackOnConnected);
int MQTT_Init();
void MQTTdestroy_client(bool _disable);

View File

@@ -12,7 +12,6 @@
#include "interface_mqtt.h"
#include "time_sntp.h"
#include "../../include/defines.h"
#include "basic_auth.h"
@@ -22,7 +21,6 @@ static const char *TAG = "MQTT SERVER";
extern const char* libfive_git_version(void);
extern const char* libfive_git_revision(void);
extern const char* libfive_git_branch(void);
extern std::string getFwVersion(void);
std::vector<NumberPost*>* NUMBERS;
bool HomeassistantDiscovery = false;
@@ -33,11 +31,10 @@ std::string rateUnit = "Unit/Minute";
float roundInterval; // Minutes
int keepAlive = 0; // Seconds
bool retainFlag;
static std::string maintopic, domoticzintopic;
static std::string maintopic;
bool sendingOf_DiscoveryAndStaticTopics_scheduled = true; // Set it to true to make sure it gets sent at least once after startup
void mqttServer_setParameter(std::vector<NumberPost*>* _NUMBERS, int _keepAlive, float _roundInterval) {
NUMBERS = _NUMBERS;
keepAlive = _keepAlive;
@@ -51,15 +48,6 @@ void mqttServer_setMeterType(std::string _meterType, std::string _valueUnit, std
rateUnit = _rateUnit;
}
/**
* Takes any multi-level MQTT-topic and returns the last topic level as nodeId
* see https://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices/ for details about MQTT topics
*/
std::string createNodeId(std::string &topic) {
auto splitPos = topic.find_last_of('/');
return (splitPos == std::string::npos) ? topic : topic.substr(splitPos + 1);
}
bool sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
std::string name, std::string icon, std::string unit, std::string deviceClass, std::string stateClass, std::string entityCategory,
int qos) {
@@ -80,21 +68,11 @@ bool sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
name = group + " " + name;
}
/**
* homeassistant needs the MQTT discovery topic according to the following structure:
* <discovery_prefix>/<component>/[<node_id>/]<object_id>/config
* if the main topic is embedded in a nested structure, we just use the last part as node_id
* This means a maintopic "home/test/watermeter" is transformed to the discovery topic "homeassistant/sensor/watermeter/..."
*/
std::string node_id = createNodeId(maintopic);
if (field == "problem") { // Special case: Binary sensor which is based on error topic
topicFull = "homeassistant/binary_sensor/" + node_id + "/" + configTopic + "/config";
}
else if (field == "flowstart") { // Special case: Button
topicFull = "homeassistant/button/" + node_id + "/" + configTopic + "/config";
if (field == "problem") { // Special binary sensor which is based on error topic
topicFull = "homeassistant/binary_sensor/" + maintopic + "/" + configTopic + "/config";
}
else {
topicFull = "homeassistant/sensor/" + node_id + "/" + configTopic + "/config";
topicFull = "homeassistant/sensor/" + maintopic + "/" + configTopic + "/config";
}
/* See https://www.home-assistant.io/docs/mqtt/discovery/ */
@@ -106,7 +84,7 @@ bool sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
"\"icon\": \"mdi:" + icon + "\",";
if (group != "") {
if (field == "problem") { // Special case: Binary sensor which is based on error topic
if (field == "problem") { // Special binary sensor which is based on error topic
payload += "\"state_topic\": \"~/" + group + "/error\",";
payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\",";
}
@@ -115,13 +93,10 @@ bool sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
}
}
else {
if (field == "problem") { // Special case: Binary sensor which is based on error topic
if (field == "problem") { // Special binary sensor which is based on error topic
payload += "\"state_topic\": \"~/error\",";
payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\",";
}
else if (field == "flowstart") { // Special case: Button
payload += "\"cmd_t\":\"~/ctrl/flow_start\","; // Add command topic
}
else {
payload += "\"state_topic\": \"~/" + field + "\",";
}
@@ -176,7 +151,6 @@ bool MQTThomeassistantDiscovery(int qos) {
// Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "uptime", "Uptime", "clock-time-eight-outline", "s", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "MAC", "MAC Address", "network-outline", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "fwVersion", "Firmware Version", "application-outline", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "hostname", "Hostname", "network-outline", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "freeMem", "Free Memory", "memory", "B", "", "measurement", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "wifiRSSI", "Wi-Fi RSSI", "wifi", "dBm", "signal_strength", "", "diagnostic", qos);
@@ -184,7 +158,6 @@ bool MQTThomeassistantDiscovery(int qos) {
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "interval", "Interval", "clock-time-eight-outline", "min", "" , "measurement", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "IP", "IP", "network-outline", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "status", "Status", "list-status", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "flowstart", "Manual Flow Start", "timer-play-outline", "", "", "", "", qos);
for (int i = 0; i < (*NUMBERS).size(); ++i) {
@@ -193,26 +166,14 @@ bool MQTThomeassistantDiscovery(int qos) {
group = "";
}
/* If "Allow neg. rate" is true, use "measurement" instead of "total_increasing" for the State Class, see https://github.com/jomjol/AI-on-the-edge-device/issues/3331 */
std::string value_state_class = "total_increasing";
if ((*NUMBERS)[i]->AllowNegativeRates) {
value_state_class = "measurement";
}
/* Energy meters need a different Device Class, see https://github.com/jomjol/AI-on-the-edge-device/issues/3333 */
std::string rate_device_class = "volume_flow_rate";
if (meterType == "energy") {
rate_device_class = "power";
}
// Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "value", "Value", "gauge", valueUnit, meterType, value_state_class, "", qos); // State Class = "total_increasing" if <NUMBERS>.AllowNegativeRates = false, else use "measurement"
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "raw", "Raw Value", "raw", valueUnit, meterType, "measurement", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "value", "Value", "gauge", valueUnit, meterType, "total_increasing", "", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "raw", "Raw Value", "raw", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "error", "Error", "alert-circle-outline", "", "", "", "diagnostic", qos);
/* Not announcing "rate" as it is better to use rate_per_time_unit resp. rate_per_digitization_round */
/* Not announcing "rate" as it is better to use rate_per_time_unit resp. rate_per_digitalization_round */
// allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate", "Rate (Unit/Minute)", "swap-vertical", "", "", "", ""); // Legacy, always Unit per Minute
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_time_unit", "Rate (" + rateUnit + ")", "swap-vertical", rateUnit, rate_device_class, "measurement", "", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_digitization_round", "Change since last Digitization round", "arrow-expand-vertical", valueUnit, "", "measurement", "", qos); // correctly the Unit is Unit/Interval!
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_time_unit", "Rate (" + rateUnit + ")", "swap-vertical", rateUnit, "", "measurement", "", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_digitalization_round", "Change since last digitalization round", "arrow-expand-vertical", valueUnit, "", "measurement", "", qos); // correctly the Unit is Unit/Interval!
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "timestamp", "Timestamp", "clock-time-eight-outline", "", "timestamp", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "json", "JSON", "code-json", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "problem", "Problem", "alert-outline", "", "problem", "", "", qos); // Special binary sensor which is based on error topic
@@ -283,7 +244,6 @@ bool publishStaticData(int qos) {
int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
allSendsSuccessed |= MQTTPublish(maintopic + "/" + "fwVersion", getFwVersion().c_str(), qos, retainFlag);
allSendsSuccessed |= MQTTPublish(maintopic + "/" + "MAC", getMac(), qos, retainFlag);
allSendsSuccessed |= MQTTPublish(maintopic + "/" + "IP", *getIPAddress(), qos, retainFlag);
allSendsSuccessed |= MQTTPublish(maintopic + "/" + "hostname", wlan_config.hostname, qos, retainFlag);
@@ -348,7 +308,7 @@ void register_server_mqtt_uri(httpd_handle_t server) {
uri.method = HTTP_GET;
uri.uri = "/mqtt_publish_discovery";
uri.handler = APPLY_BASIC_AUTH_FILTER(scheduleSendingDiscovery_and_static_Topics);
uri.handler = scheduleSendingDiscovery_and_static_Topics;
uri.user_ctx = (void*) "";
httpd_register_uri_handler(server, &uri);
}
@@ -376,9 +336,4 @@ std::string mqttServer_getMainTopic() {
return maintopic;
}
void mqttServer_setDmoticzInTopic( std::string _domoticzintopic) {
domoticzintopic = _domoticzintopic;
}
#endif //ENABLE_MQTT

View File

@@ -12,9 +12,6 @@ void mqttServer_setParameter(std::vector<NumberPost*>* _NUMBERS, int interval, f
void mqttServer_setMeterType(std::string meterType, std::string valueUnit, std::string timeUnit,std::string rateUnit);
void setMqtt_Server_Retain(bool SetRetainFlag);
void mqttServer_setMainTopic( std::string maintopic);
void mqttServer_setDmoticzInTopic( std::string domoticzintopic);
std::string mqttServer_getMainTopic();
void register_server_mqtt_uri(httpd_handle_t server);
@@ -25,7 +22,6 @@ std::string getTimeUnit(void);
void GotConnected(std::string maintopic, bool SetRetainFlag);
esp_err_t sendDiscovery_and_static_Topics(void);
std::string createNodeId(std::string &topic);
#endif //SERVERMQTT_H
#endif //ENABLE_MQTT

View File

@@ -12,22 +12,6 @@
static const char *TAG = "TFLITE";
void CTfLiteClass::MakeStaticResolver()
{
resolver.AddFullyConnected();
resolver.AddReshape();
resolver.AddSoftmax();
resolver.AddConv2D();
resolver.AddMaxPool2D();
resolver.AddQuantize();
resolver.AddMul();
resolver.AddAdd();
resolver.AddLeakyRelu();
resolver.AddDequantize();
}
float CTfLiteClass::GetOutputValue(int nr)
{
TfLiteTensor* output2 = this->interpreter->output(0);
@@ -195,23 +179,22 @@ bool CTfLiteClass::LoadInputImageBasis(CImageBasis *rs)
}
bool CTfLiteClass::MakeAllocate()
{
MakeStaticResolver();
static tflite::AllOpsResolver resolver;
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("CTLiteClass::Alloc start");
#endif
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::MakeAllocate");
this->interpreter = new tflite::MicroInterpreter(this->model, resolver, this->tensor_arena, this->kTensorArenaSize);
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Trying to load the model. If it crashes here, it ist most likely due to a corrupted model!");
this->interpreter = new tflite::MicroInterpreter(this->model, resolver, this->tensor_arena, this->kTensorArenaSize, this->error_reporter);
if (this->interpreter)
{
TfLiteStatus allocate_status = this->interpreter->AllocateTensors();
if (allocate_status != kTfLiteOk) {
TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed");
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "AllocateTensors() failed");
this->GetInputDimension();
@@ -246,18 +229,9 @@ void CTfLiteClass::GetInputTensorSize()
long CTfLiteClass::GetFileSize(std::string filename)
{
struct stat stat_buf;
long rc = -1;
FILE *pFile = fopen(filename.c_str(), "rb"); // previously only "rb
if (pFile != NULL)
{
rc = stat(filename.c_str(), &stat_buf);
fclose(pFile);
}
return rc == 0 ? stat_buf.st_size : -1;
struct stat stat_buf;
long rc = stat(filename.c_str(), &stat_buf);
return rc == 0 ? stat_buf.st_size : -1;
}
@@ -279,33 +253,25 @@ bool CTfLiteClass::ReadFileToModel(std::string _fn)
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Loading Model " + _fn + " /size: " + std::to_string(size) + " bytes...");
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile start");
#endif
modelfile = (unsigned char*)psram_get_shared_model_memory();
if (modelfile != NULL)
if(modelfile != NULL)
{
FILE *pFile = fopen(_fn.c_str(), "rb"); // previously only "rb
if (pFile != NULL)
{
fread(modelfile, 1, size, pFile);
fclose(pFile);
FILE* f = fopen(_fn.c_str(), "rb"); // previously only "r
fread(modelfile, 1, size, f);
fclose(f);
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile successful");
#endif
#ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile successful");
#endif
return true;
}
else
{
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Model does not exist");
return false;
}
}
return true;
}
else
{
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Can't allocate enough memory: " + std::to_string(size));
@@ -318,6 +284,12 @@ bool CTfLiteClass::ReadFileToModel(std::string _fn)
bool CTfLiteClass::LoadModel(std::string _fn)
{
#ifdef SUPRESS_TFLITE_ERRORS
this->error_reporter = new tflite::OwnMicroErrorReporter;
#else
this->error_reporter = new tflite::MicroErrorReporter;
#endif
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::LoadModel");
if (!ReadFileToModel(_fn.c_str())) {
@@ -348,6 +320,16 @@ CTfLiteClass::CTfLiteClass()
CTfLiteClass::~CTfLiteClass()
{
delete this->interpreter;
delete this->error_reporter;
psram_free_shared_tensor_arena_and_model_memory();
}
namespace tflite
{
int OwnMicroErrorReporter::Report(const char* format, va_list args)
{
return 0;
}
}

View File

@@ -3,23 +3,38 @@
#ifndef CTFLITECLASS_H
#define CTFLITECLASS_H
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/micro/kernels/micro_ops.h"
#include "esp_err.h"
#include "esp_log.h"
#include "CImageBasis.h"
#ifdef SUPRESS_TFLITE_ERRORS
#include "tensorflow/lite/core/api/error_reporter.h"
#include "tensorflow/lite/micro/compatibility.h"
#include "tensorflow/lite/micro/debug_log.h"
///// OwnErrorReporter to prevent printing of Errors (especially unavoidable in CalculateActivationRangeQuantized@kerne_util.cc)
namespace tflite {
class OwnMicroErrorReporter : public ErrorReporter {
public:
int Report(const char* format, va_list args) override;
};
} // namespace tflite
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif
class CTfLiteClass
{
protected:
tflite::MicroMutableOpResolver<10> resolver;
tflite::ErrorReporter *error_reporter;
const tflite::Model* model;
tflite::MicroInterpreter* interpreter;
TfLiteTensor* output = nullptr;
static tflite::AllOpsResolver resolver;
int kTensorArenaSize;
uint8_t *tensor_arena;
@@ -33,7 +48,6 @@ class CTfLiteClass
long GetFileSize(std::string filename);
bool ReadFileToModel(std::string _fn);
void MakeStaticResolver();
public:
CTfLiteClass();

View File

@@ -2,6 +2,6 @@ FILE(GLOB_RECURSE app_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.*)
idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "."
REQUIRES esp_netif esp-tflite-micro jomjol_logfile jomjol_configfile)
REQUIRES tflite-lib jomjol_logfile jomjol_configfile jomjol_helper)

View File

@@ -10,10 +10,10 @@
#include "esp_log.h"
#include "esp_attr.h"
#include "esp_sleep.h"
#include "esp_netif_sntp.h"
#include "esp_sntp.h"
#include "../../include/defines.h"
#include "websocket.h"
#include "ClassLogFile.h"
#include "configFile.h"
@@ -32,9 +32,6 @@ std::string getNtpStatusText(sntp_sync_status_t status);
static void setTimeZone(std::string _tzstring);
static std::string getServerName(void);
int LocalTimeToUTCOffsetSeconds;
std::string ConvertTimeToString(time_t _time, const char * frm)
{
@@ -72,6 +69,8 @@ void time_sync_notification_cb(struct timeval *tv)
}
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is synced with NTP Server " +
getServerName() + ": " + getCurrentTimeString("%Y-%m-%d %H:%M:%S"));
schedule_websocket_message("{\"ntp\": \"synchronized\"}");
}
@@ -93,51 +92,15 @@ bool time_manual_reset_sync(void)
}
int getUTCOffsetSeconds(std::string &zeitzone)
{
int offset = 0;
int vorzeichen = 1;
int minuten = 0;
int stunden = 0;
time_t now;
struct tm timeinfo;
time (&now);
localtime_r(&now, &timeinfo);
char buffer[80];
strftime(buffer, 80, "%z", &timeinfo);
zeitzone = std::string(buffer);
if (zeitzone.length() == 5)
{
if (zeitzone[0] == '-')
vorzeichen = -1;
stunden = stoi(zeitzone.substr(1, 2));
minuten = stoi(zeitzone.substr(3, 2));
offset = ((stunden * 60) + minuten) * 60;
}
return offset;
}
void setTimeZone(std::string _tzstring)
{
setenv("TZ", _tzstring.c_str(), 1);
tzset();
_tzstring = "Time zone set to " + _tzstring;
LogFile.WriteToFile(ESP_LOG_INFO, TAG, _tzstring);
std::string zeitzone;
LocalTimeToUTCOffsetSeconds = getUTCOffsetSeconds(zeitzone);
// std::string zw = std::to_string(LocalTimeToUTCOffsetSeconds);
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "time zone: " + zeitzone + " Delta to UTC: " + std::to_string(LocalTimeToUTCOffsetSeconds) + " seconds");
}
std::string getNtpStatusText(sntp_sync_status_t status) {
if (status == SNTP_SYNC_STATUS_COMPLETED) {
return "Synchronized";
@@ -275,13 +238,21 @@ bool setupTime() {
if (useNtp) {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Configuring NTP Client...");
esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(timeServer.c_str());
config.sync_cb = time_sync_notification_cb;
esp_netif_sntp_init(&config);
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, timeServer.c_str());
sntp_set_time_sync_notification_cb(time_sync_notification_cb);
setTimeZone(timeZone);
sntp_init();
/*
if (!wait_for_timesync())
{
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Timesync at startup failed.");
}
*/
}
/* The RTC keeps the time after a restart (Except on Power On or Pin Reset)
* There should only be a minor correction through NTP */
@@ -290,7 +261,6 @@ bool setupTime() {
localtime_r(&now, &timeinfo);
strftime(strftime_buf, sizeof(strftime_buf), "%Y-%m-%d %H:%M:%S", &timeinfo);
if (getTimeIsSet()) {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Time is already set: " + std::string(strftime_buf));
}

View File

@@ -28,7 +28,5 @@ bool setupTime();
bool time_manual_reset_sync(void);
extern int LocalTimeToUTCOffsetSeconds;
#endif //TIMESNTP_H

View File

@@ -1,7 +0,0 @@
FILE(GLOB_RECURSE app_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.*)
idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "."
REQUIRES esp_http_client jomjol_logfile jomjol_flowcontroll json)

View File

@@ -1,170 +0,0 @@
#ifdef ENABLE_WEBHOOK
#include "interface_webhook.h"
#include "esp_log.h"
#include <time.h>
#include "ClassLogFile.h"
#include "esp_http_client.h"
#include "time_sntp.h"
#include "../../include/defines.h"
#include <cJSON.h>
#include <ClassFlowDefineTypes.h>
static const char *TAG = "WEBHOOK";
std::string _webhookURI;
std::string _webhookApiKey;
long _lastTimestamp;
static esp_err_t http_event_handler(esp_http_client_event_t *evt);
void WebhookInit(std::string _uri, std::string _apiKey)
{
_webhookURI = _uri;
_webhookApiKey = _apiKey;
_lastTimestamp = 0L;
}
bool WebhookPublish(std::vector<NumberPost*>* numbers)
{
bool numbersWithError = false;
cJSON *jsonArray = cJSON_CreateArray();
for (int i = 0; i < (*numbers).size(); ++i)
{
string timezw = "";
char buffer[80];
time_t &lastPreValue = (*numbers)[i]->timeStampLastPreValue;
struct tm* timeinfo = localtime(&lastPreValue);
_lastTimestamp = static_cast<long>(lastPreValue);
strftime(buffer, 80, PREVALUE_TIME_FORMAT_OUTPUT, timeinfo);
timezw = std::string(buffer);
cJSON *json = cJSON_CreateObject();
cJSON_AddStringToObject(json, "timestamp", timezw.c_str());
cJSON_AddStringToObject(json, "timestampLong", std::to_string(_lastTimestamp).c_str());
cJSON_AddStringToObject(json, "name", (*numbers)[i]->name.c_str());
cJSON_AddStringToObject(json, "rawValue", (*numbers)[i]->ReturnRawValue.c_str());
cJSON_AddStringToObject(json, "value", (*numbers)[i]->ReturnValue.c_str());
cJSON_AddStringToObject(json, "preValue", (*numbers)[i]->ReturnPreValue.c_str());
cJSON_AddStringToObject(json, "rate", (*numbers)[i]->ReturnRateValue.c_str());
cJSON_AddStringToObject(json, "changeAbsolute", (*numbers)[i]->ReturnChangeAbsolute.c_str());
cJSON_AddStringToObject(json, "error", (*numbers)[i]->ErrorMessageText.c_str());
cJSON_AddItemToArray(jsonArray, json);
if ((*numbers)[i]->ErrorMessage) {
numbersWithError = true;
}
}
char *jsonString = cJSON_PrintUnformatted(jsonArray);
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "sending webhook");
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "sending JSON: " + std::string(jsonString));
char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
esp_http_client_config_t http_config = {
.url = _webhookURI.c_str(),
.user_agent = "ESP32 Meter reader",
.method = HTTP_METHOD_POST,
.event_handler = http_event_handler,
.buffer_size = MAX_HTTP_OUTPUT_BUFFER,
.user_data = response_buffer
};
esp_http_client_handle_t http_client = esp_http_client_init(&http_config);
esp_http_client_set_header(http_client, "Content-Type", "application/json");
esp_http_client_set_header(http_client, "APIKEY", _webhookApiKey.c_str());
ESP_ERROR_CHECK(esp_http_client_set_post_field(http_client, jsonString, strlen(jsonString)));
esp_err_t err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_perform(http_client));
if(err == ESP_OK) {
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP request was performed");
int status_code = esp_http_client_get_status_code(http_client);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP status code: " + std::to_string(status_code));
} else {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "HTTP request failed");
}
esp_http_client_cleanup(http_client);
cJSON_Delete(jsonArray);
free(jsonString);
return numbersWithError;
}
void WebhookUploadPic(ImageData *Img) {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Starting WebhookUploadPic");
std::string fullURI = _webhookURI + "?timestamp=" + std::to_string(_lastTimestamp);
char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
esp_http_client_config_t http_config = {
.url = fullURI.c_str(),
.user_agent = "ESP32 Meter reader",
.method = HTTP_METHOD_PUT,
.event_handler = http_event_handler,
.buffer_size = MAX_HTTP_OUTPUT_BUFFER,
.user_data = response_buffer
};
esp_http_client_handle_t http_client = esp_http_client_init(&http_config);
esp_http_client_set_header(http_client, "Content-Type", "image/jpeg");
esp_http_client_set_header(http_client, "APIKEY", _webhookApiKey.c_str());
esp_err_t err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_set_post_field(http_client, (const char *)Img->data, Img->size));
err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_perform(http_client));
if (err == ESP_OK) {
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP PUT request was performed successfully");
int status_code = esp_http_client_get_status_code(http_client);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP status code: " + std::to_string(status_code));
} else {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "HTTP PUT request failed");
}
esp_http_client_cleanup(http_client);
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "WebhookUploadPic finished");
}
static esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
switch(evt->event_id)
{
case HTTP_EVENT_ERROR:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client Error encountered");
break;
case HTTP_EVENT_ON_CONNECTED:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client connected");
ESP_LOGI(TAG, "HTTP Client Connected");
break;
case HTTP_EVENT_HEADERS_SENT:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client sent all request headers");
break;
case HTTP_EVENT_ON_HEADER:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Header: key=" + std::string(evt->header_key) + ", value=" + std::string(evt->header_value));
break;
case HTTP_EVENT_ON_DATA:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client data recevied: len=" + std::to_string(evt->data_len));
break;
case HTTP_EVENT_ON_FINISH:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client finished");
break;
case HTTP_EVENT_DISCONNECTED:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Client Disconnected");
break;
case HTTP_EVENT_REDIRECT:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP Redirect");
break;
}
return ESP_OK;
}
#endif //ENABLE_WEBHOOK

View File

@@ -1,17 +0,0 @@
#ifdef ENABLE_WEBHOOK
#pragma once
#ifndef INTERFACE_WEBHOOK_H
#define INTERFACE_WEBHOOK_H
#include <string>
#include <map>
#include <functional>
#include <ClassFlowDefineTypes.h>
void WebhookInit(std::string _webhookURI, std::string _apiKey);
bool WebhookPublish(std::vector<NumberPost*>* numbers);
void WebhookUploadPic(ImageData *Img);
#endif //INTERFACE_WEBHOOK_H
#endif //ENABLE_WEBHOOK

View File

@@ -1,107 +0,0 @@
#include "basic_auth.h"
#include "read_wlanini.h"
#include <esp_tls_crypto.h>
#include <esp_log.h>
#define HTTPD_401 "401 UNAUTHORIZED"
static const char *TAG = "HTTPAUTH";
typedef struct {
const char *username;
const char *password;
} basic_auth_info_t;
basic_auth_info_t basic_auth_info = { NULL, NULL };
void init_basic_auth() {
if (!wlan_config.http_username.empty() && !wlan_config.http_password.empty()) {
basic_auth_info.username = wlan_config.http_username.c_str();
basic_auth_info.password = wlan_config.http_password.c_str();
}
}
static char *http_auth_basic(const char *username, const char *password)
{
int out;
char *user_info = NULL;
char *digest = NULL;
size_t n = 0;
asprintf(&user_info, "%s:%s", username, password);
if (!user_info) {
ESP_LOGE(TAG, "No enough memory for user information");
return NULL;
}
esp_crypto_base64_encode(NULL, 0, &n, (const unsigned char *)user_info, strlen(user_info));
/* 6: The length of the "Basic " string
* n: Number of bytes for a base64 encode format
* 1: Number of bytes for a reserved which be used to fill zero
*/
digest = static_cast<char*>(calloc(1, 6 + n + 1));
if (digest) {
strcpy(digest, "Basic ");
esp_crypto_base64_encode((unsigned char *)digest + 6, n, (size_t *)&out, (const unsigned char *)user_info, strlen(user_info));
}
free(user_info);
return digest;
}
esp_err_t basic_auth_request_filter(httpd_req_t *req, esp_err_t original_handler(httpd_req_t *))
{
char *buf = NULL;
size_t buf_len = 0;
esp_err_t ret = ESP_OK;
char unauthorized[] = "You are not authorized to use this website!";
if (basic_auth_info.username == NULL || basic_auth_info.password == NULL) {
ret = original_handler(req);
} else {
buf_len = httpd_req_get_hdr_value_len(req, "Authorization") + 1;
if (buf_len > 1) {
buf = static_cast<char*>(calloc(1, buf_len));
if (!buf) {
ESP_LOGE(TAG, "No enough memory for basic authorization");
return ESP_ERR_NO_MEM;
}
if (httpd_req_get_hdr_value_str(req, "Authorization", buf, buf_len) == ESP_OK) {
ESP_LOGI(TAG, "Found header => Authorization: %s", buf);
} else {
ESP_LOGE(TAG, "No auth value received");
}
char *auth_credentials = http_auth_basic(basic_auth_info.username, basic_auth_info.password);
if (!auth_credentials) {
ESP_LOGE(TAG, "No enough memory for basic authorization credentials");
free(buf);
return ESP_ERR_NO_MEM;
}
if (strncmp(auth_credentials, buf, buf_len)) {
ESP_LOGE(TAG, "Not authenticated");
httpd_resp_set_status(req, HTTPD_401);
httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
httpd_resp_set_hdr(req, "Connection", "keep-alive");
httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\"");
httpd_resp_send(req, unauthorized, strlen(unauthorized));
} else {
ESP_LOGI(TAG, "Authenticated calling http handler now!");
ret=original_handler(req);
}
free(auth_credentials);
free(buf);
} else {
ESP_LOGE(TAG, "No auth header received");
httpd_resp_set_status(req, HTTPD_401);
httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
httpd_resp_set_hdr(req, "Connection", "keep-alive");
httpd_resp_set_hdr(req, "WWW-Authenticate", "Basic realm=\"AIOTED\"");
httpd_resp_send(req, unauthorized, strlen(unauthorized));
}
}
return ret;
}

View File

@@ -1,8 +0,0 @@
#pragma once
#include <esp_http_server.h>
void init_basic_auth();
esp_err_t basic_auth_request_filter(httpd_req_t *req, esp_err_t original_handler(httpd_req_t *));
#define APPLY_BASIC_AUTH_FILTER(method) [](httpd_req_t *req){ return basic_auth_request_filter(req, method); }

View File

@@ -49,9 +49,6 @@
#define ets_delay_us(a) esp_rom_delay_us(a)
#endif
#include "../../esp-protocols/components/mdns/include/mdns.h"
static const char *TAG = "WIFI";
static bool APWithBetterRSSI = false;
@@ -381,7 +378,7 @@ void wifi_scan(void)
else {
if (esp_wifi_scan_get_ap_records(&max_number_of_ap_found, wifi_ap_records) != ESP_OK) { // Retrieve results (and free internal heap)
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "wifi_scan: esp_wifi_scan_get_ap_records: Error retrieving datasets");
delete[] wifi_ap_records;
delete wifi_ap_records;
return;
}
}
@@ -404,7 +401,7 @@ void wifi_scan(void)
APWithBetterRSSI = true;
}
}
delete[] wifi_ap_records;
delete wifi_ap_records;
}
@@ -483,8 +480,7 @@ static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_
if (WIFIReconnectCnt >= 10) {
WIFIReconnectCnt = 0;
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Disconnected, multiple reconnect attempts failed (" +
std::to_string(disconn->reason) + "), retrying after 5s");
vTaskDelay(5000 / portTICK_PERIOD_MS); // Delay between the reconnections
std::to_string(disconn->reason) + "), still retrying...");
}
}
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED)
@@ -660,14 +656,6 @@ esp_err_t wifi_init_sta(void)
else {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Set hostname to: " + wlan_config.hostname);
}
//initialize mDNS service
retval = mdns_init();
if (retval != ESP_OK) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "mdns_init failed! Error: " + std::to_string(retval));
} else {
//set mdns hostname
mdns_hostname_set(wlan_config.hostname.c_str());
}
}
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init successful");

View File

@@ -145,29 +145,6 @@ int LoadWlanFromFile(std::string fn)
wlan_config.dns = tmp;
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "DNS: " + wlan_config.dns);
}
else if ((splitted.size() > 1) && (toUpper(splitted[0]) == "HTTP_USERNAME")){
tmp = splitted[1];
if ((tmp[0] == '"') && (tmp[tmp.length()-1] == '"')){
tmp = tmp.substr(1, tmp.length()-2);
}
wlan_config.http_username = tmp;
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "HTTP_USERNAME: " + wlan_config.http_username);
}
else if ((splitted.size() > 1) && (toUpper(splitted[0]) == "HTTP_PASSWORD")){
tmp = splitted[1];
if ((tmp[0] == '"') && (tmp[tmp.length()-1] == '"')){
tmp = tmp.substr(1, tmp.length()-2);
}
wlan_config.http_password = tmp;
#ifndef __HIDE_PASSWORD
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "HTTP_PASSWORD: " + wlan_config.http_password);
#else
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "HTTP_PASSWORD: XXXXXXXX");
#endif
}
#if (defined WLAN_USE_ROAMING_BY_SCANNING || (defined WLAN_USE_MESH_ROAMING && defined WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES))
else if ((splitted.size() > 1) && (toUpper(splitted[0]) == "RSSITHRESHOLD")){
tmp = trim(splitted[1]);
@@ -197,12 +174,10 @@ int LoadWlanFromFile(std::string fn)
}
/* Check if password is empty (mandatory parameter) */
/* Disabled see issue #2393
if (wlan_config.password.empty()) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Password empty. Device init aborted!");
return -2;
}
*/
return 0;
}

View File

@@ -13,8 +13,6 @@ struct wlan_config {
std::string gateway = "";
std::string netmask = "";
std::string dns = "";
std::string http_username = "";
std::string http_password = "";
int rssi_threshold = 0; // Default: 0 -> ROAMING disabled
};
extern struct wlan_config wlan_config;

View File

@@ -1,7 +0,0 @@
FILE(GLOB_RECURSE app_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.*)
idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "."
REQUIRES jomjol_image_proc)

Some files were not shown because too many files have changed in this diff Show More