Compare commits

..

323 Commits

Author SHA1 Message Date
CaCO3
1ceb47fbc7 . 2025-02-25 00:22:47 +01:00
CaCO3
a413d0228e . 2025-02-25 00:10:29 +01:00
CaCO3
e22eaa2736 . 2025-02-25 00:01:17 +01:00
CaCO3
154d159595 . 2025-02-24 23:58:27 +01:00
CaCO3
23a5458a2b . 2025-02-24 23:53:57 +01:00
CaCO3
89097fa5a2 . 2025-02-24 23:46:38 +01:00
CaCO3
6952db0298 swap HTML folders after extracting 2025-02-24 23:26:55 +01:00
CaCO3
550889c373 rename html folder 2025-02-24 23:10:03 +01:00
CaCO3
1200ee1289 Merge branch 'fix-gz' of https://github.com/jomjol/AI-on-the-edge-device into fix-gz 2025-02-24 21:57:09 +01:00
CaCO3
fceccb90b0 delete HTML directory on an update 2025-02-24 21:56:49 +01:00
CaCO3
8f5bf209d9 Gz html files fix missing file server.html (#3582)
* Add files via upload

* Delete sd-card/html/file_server.html

* Update server_file.cpp

* Update server_file.cpp

---------

Co-authored-by: SybexX <Heinrich-Tuning@web.de>
2025-02-24 21:55:16 +01:00
CaCO3
ec639d4236 revert unwanted removal of Autotimer title in config page
Revert removal of title. It got removed in 708fd68cf5 but should have stayed
2025-02-24 21:39:31 +01:00
CaCO3
d68c95d626 delete HTML directory on an update 2025-02-24 21:30:14 +01:00
CaCO3
5304981733 Fix thermometer config (#3578)
* fix thermometer config

* update note

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
2025-02-23 21:12:20 +01:00
SybexX
7a9955477a add data export (CSV files) (#3537)
* Update backup.html

* Add files via upload

* Update data_export.html

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2025-02-23 17:38:32 +01:00
SybexX
04fe25e875 Update timezones.html
fix missing searchicon.png
2025-02-20 19:23:33 +01:00
SybexX
02dcd584bf Add files via upload 2025-02-20 19:19:59 +01:00
SybexX
68a262ef22 Update ClassFlowControll.cpp
fix .gz in GetJPGStream(std::string _fn, httpd_req_t *req)
2025-02-18 00:54:00 +01:00
SybexX
f2b6b4f819 Update sdcard_check.cpp
fix .gz in SDCardCheckFolderFilePresence()
2025-02-17 22:23:55 +01:00
CaCO3
6b672ff9a5 compress all HTML files (#3568)
* compress all HTML files

* remove gz files, they get zipped in the build pipeline

* Update build.yaml

* removed flipImageSize.png, it is not used anywhere anymore

* Update build.yaml
2025-02-16 19:11:09 +01:00
SybexX
26770d877e Update main.cpp
If the camera could only be initialized on the second attempt, "Camera Framebuffer Check" and "Print camera infos" was skipped.
2025-02-16 12:01:30 +01:00
jomjol
e60c12b25d Create Licence.md 2025-02-16 10:56:52 +01:00
CaCO3
b10336b59c Add thermometer (#3454)
* add thermometer

* .

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
2025-02-16 10:34:10 +01:00
SybexX
dadb004e85 add .gz (#3538)
* Update server_help.cpp

* Add files via upload

* Add files via upload

* Update server_help.cpp
2025-02-16 10:28:06 +01:00
CaCO3
e2f3e3d05b corrected enable/disable texts to make it more intuitive (#3565) 2025-02-16 09:59:52 +01:00
CaCO3
8c5a6528d9 Update RetainMessages.md 2025-02-15 22:43:14 +01:00
CaCO3
69024adac7 updated param doc 2025-02-15 22:11:27 +01:00
CaCO3
9f1b7c9ef7 updated param doc 2025-02-15 21:55:57 +01:00
CaCO3
15fd7a6a33 Update webinstaller job (#3563)
* Update manual-update-webinstaller.yaml

* Update build.yaml
2025-02-15 00:28:30 +01:00
SybexX
9c3fbb4aff Update main.cpp 2025-02-14 21:41:28 +01:00
SybexX
eb4c9276d5 Merge pull request #3455 from jomjol/mqtt-add-ValidateServerCert-Parameter
MQTT add validate server cert parameter
2025-02-14 21:28:29 +01:00
SybexX
842229ea98 Merge branch 'main' into mqtt-add-ValidateServerCert-Parameter 2025-02-14 21:20:37 +01:00
jomjol
b83717aece Update manual-update-webinstaller.yaml 2025-02-14 20:21:43 +01:00
jomjol
b01e42b893 Revert to old version 2025-02-14 20:19:37 +01:00
jomjol
902f1bc2a8 Revert "Update manual-update-webinstaller.yaml"
This reverts commit 71f31dc841.
2025-02-14 20:13:51 +01:00
jomjol
5c51990b40 Merge branch 'main' of https://github.com/jomjol/AI-on-the-edge-device 2025-02-14 20:12:18 +01:00
jomjol
55cbbf02cb Revert "Update manual-update-webinstaller.yaml"
This reverts commit 20a0d8530a.
2025-02-14 20:11:39 +01:00
jomjol
e37817e3e2 Update manual-update-webinstaller.yaml 2025-02-14 19:57:53 +01:00
jomjol
a78ca53d60 Update manual-update-webinstaller.yaml 2025-02-14 19:55:10 +01:00
jomjol
20a0d8530a Update manual-update-webinstaller.yaml 2025-02-14 19:47:27 +01:00
jomjol
af1e3257be Update manual-update-webinstaller.yaml 2025-02-14 19:45:03 +01:00
jomjol
93c21d30a1 Update manual-update-webinstaller.yaml 2025-02-14 19:39:11 +01:00
jomjol
7111a7fdcd Update manual-update-webinstaller.yaml 2025-02-14 19:37:57 +01:00
jomjol
bd541ede60 Update manual-update-webinstaller.yaml 2025-02-14 19:25:58 +01:00
jomjol
52aab2f8a6 Update manual-update-webinstaller.yaml 2025-02-14 19:24:08 +01:00
jomjol
a1aee5b346 Update manual-update-webinstaller.yaml 2025-02-14 19:19:24 +01:00
jomjol
71f31dc841 Update manual-update-webinstaller.yaml 2025-02-14 19:18:03 +01:00
jomjol
f6a363a871 Update WebInstaller 2025-02-14 18:35:54 +01:00
SybexX
7de18753d9 Update smartled driver (#3500)
* update-SmartLeds

* Update sdkconfig.defaults
2025-02-14 18:07:55 +01:00
michael
fea0c1b859 TOOLTIPs_revised 2025-02-02 22:14:58 +01:00
SybexX
603fcfef33 fix 2025-01-31 11:49:46 +01:00
SybexX
be3312e912 fix 2025-01-31 11:49:34 +01:00
jomjol
ff657ebb5c Documentation of intreace_influxdb 2025-01-26 16:58:28 +01:00
jomjol
42d4916cb8 Rewrite InfluxDB Interfache (#3520)
* Replace influxdb interface

* Implement InfluxDBV2

* Update interface_influxdb.cpp

* Cleanup new InfluxDB interface
2025-01-25 23:01:32 +01:00
SybexX
a73cd97629 Update sdkconfig.defaults 2025-01-25 17:17:56 +01:00
SybexX
636d816727 Update main.cpp 2025-01-25 00:16:23 +01:00
SybexX
c6f6341c87 Update sdkconfig.defaults 2025-01-24 06:47:13 +01:00
SybexX
ad886898a8 Update ClassFlowMQTT.cpp 2025-01-24 06:43:52 +01:00
SybexX
f16cf1406c Update interface_mqtt.cpp 2025-01-24 06:41:38 +01:00
SybexX
5dfd9a7db0 Update interface_mqtt.cpp 2025-01-21 05:50:34 +01:00
SybexX
89dc941d40 Update platformio.ini 2025-01-21 05:36:50 +01:00
SybexX
3f3c845e9f Update sdkconfig.defaults 2025-01-21 05:34:22 +01:00
fsck-block
1e60d839b7 added and activated espressif mDNS service (#3494)
* added and activated espressif mDNS service

* moved esp-protocols to code/components
2025-01-17 23:16:55 +01:00
jomjol
6e474441f6 Create License-DRAFT.md 2025-01-05 20:06:09 +01:00
jomjol
bf2a2f553f Create dig-class11_1910_s2_q.tflite 2025-01-05 19:53:25 +01:00
jomjol
21ab5cb203 additional tflite v0810 2025-01-05 19:20:48 +01:00
SybexX
1af1796ee0 Update ClassControllCamera.cpp
.jpeg_quality = 6 can cause problems with some cameras
2025-01-04 13:30:25 +01:00
michael
095cf984c4 remove_soc_temperature_for_s3_support 2025-01-03 18:36:11 +01:00
michael
b72d809e59 fix_soc_sdmmc_and_add_soc_temperature_for_s3_support 2025-01-02 16:39:26 +01:00
SybexX
c6a593ba0d fix for incorrect decimal shift? (#3446)
* Update ClassFlowCNNGeneral.cpp

* Update ClassFlowCNNGeneral.cpp

* Update ClassFlowCNNGeneral.cpp

* Update ClassFlowCNNGeneral.cpp

* Update code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.cpp

* Update code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.cpp

* Update code/components/jomjol_flowcontroll/ClassFlowCNNGeneral.cpp

* Update ClassFlowCNNGeneral.cpp

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-12-31 12:01:02 +01:00
SybexX
c41a0a476d Update sdkconfig.defaults 2024-12-28 13:21:53 +01:00
jomjol
c68463359b Update tflite 2024-12-27 16:52:03 +01:00
CaCO3
a1c2145e77 Update Changelog.md 2024-12-25 20:53:25 +01:00
CaCO3
2986c6122d Add Web Interface and REST auth (#3436)
* Ported https://github.com/jomjol/AI-on-the-edge-device/pull/2241 to latest main and extended it for all REST APIs

* .

* fix compile errors

* .

* .

* Update Changelog.md

* Update Changelog.md

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: michael <Heinrich-Tuning@web.de>
2024-12-25 20:49:47 +01:00
CaCO3
a348a51f14 Update NUMBER.ChangeRateThreshold.md 2024-12-25 10:27:47 +01:00
michael
6da894142e test3 2024-12-24 14:07:59 +01:00
michael
4846a52d45 test2 2024-12-24 13:14:19 +01:00
michael
4d74d0c522 test1 2024-12-24 12:14:53 +01:00
michael
53e818186a test 2024-12-24 04:27:12 +01:00
CaCO3
26ca15e18a fix crash fue to empty CAM parameters in migration (#3450)
Co-authored-by: CaCO3 <caco@ruinelli.ch>
2024-12-22 22:12:49 +01:00
CaCO3
f4dccc1d52 Update Interval.md 2024-12-05 23:21:01 +01:00
CaCO3
a07c2cf46d Update AutoStart.md 2024-12-05 23:20:30 +01:00
CaCO3
2f39d9bdd4 Update Interval.md 2024-12-05 23:14:02 +01:00
CaCO3
7836323fbc Prepare RC5 (#3422)
* Update Changelog.md

* Update Changelog.md

* Update Changelog.md

* Update Changelog.md
2024-12-05 01:05:38 +01:00
CaCO3
708fd68cf5 Remove Autostart parameter and make the flow to be always enabled (#3423)
* removed Autostart parameter and make it enabled by default

* .

* show menu entry in UI

* cleanup migration

* .

* .

* .

* .

* .

* .

* .

* .
2024-12-05 01:04:24 +01:00
github-actions[bot]
1b5ff2ef1a docs(contributor): contrib-readme-action has updated readme 2024-12-04 22:40:54 +00:00
CaCO3
1701aaed42 Update README.md (#3421) 2024-12-04 23:40:24 +01:00
CaCO3
c07e5a740a Add files via upload 2024-12-04 23:36:29 +01:00
SURYANSH RAI
3868cf98f6 Better Footer with social links #3311 (#3361)
* Added footer

* Update README.md

* Update index.html

* Update index.html

* Add files via upload

* Delete images/mail.jpg

* Update README.md

* Update sd-card/html/index.html

* Update docs/index.html

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-12-04 23:33:58 +01:00
CaCO3
179005f4ce Extend Homeassistant discovery with button for flow start (#3415)
* feat(homeassistant discovery): Add button for flow start

* Update

* Update

* Allow Flow Start MQTT topic to have a zero-length payload

* remove unused payload

---------

Co-authored-by: Slider0007 <jobbelle@gmx.net>
2024-12-04 23:17:06 +01:00
SybexX
50ada0a5a8 fix (#3418) 2024-12-04 22:57:43 +01:00
SybexX
be7146c886 fix (#3417) 2024-12-03 21:12:19 +01:00
CaCO3
8f89a396f8 typo 2024-12-02 23:03:48 +01:00
SybexX
9e84d28ee9 overview_add_date_and_time (#3398)
* overview_add_date_and_time

* Update overview.html

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-12-02 00:26:54 +01:00
CaCO3
3f4aaf303f Revert ec00e94
See https://github.com/jomjol/AI-on-the-edge-device/issues/3305#issuecomment-2510295853
2024-12-02 00:14:52 +01:00
gneluka
08baf1824c Add support for Domoticz MQTT integration (#3359)
* initial changes to add domoticz support

* error correction

* further changes

* further changes

* Refactoring

* further refactoring

* further refactoring

* Update DomoticzTopicIn.md

* Update NUMBER.DomoticzIDX.md

* Update DomoticzTopicIn.md

* Update NUMBER.DomoticzIDX.md

* Update config.ini

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update DomoticzTopicIn.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-12-02 00:07:02 +01:00
SybexX
2c7740ec16 Update CTfLiteClass.cpp (#3397) 2024-11-21 22:01:57 +01:00
SybexX
3ee32d8cf0 Merge pull request #3393 from tkopczuk/patch-1
Fix 'AnalogToDigitTransitionStart' always using 9.2 regardless of the configured value.
2024-11-20 03:33:23 +01:00
Tomek Kopczuk
25ae0465d8 Fix 'AnalogToDigitTransitionStart' always using 9.2 regardless of the configured value.
After the recent parameter rename we're trying to compare the toUpper version of the config parameter against "AnalogToDigitTransitionStart" - which will always fail - hence always using the default value of 9.2.
2024-11-19 23:14:24 +01:00
CaCO3
14e9d6a9cc renamed issue templates 2024-11-15 17:45:40 +01:00
CaCO3
94c2de1c2a Rename blank.yaml to x_blank.yaml 2024-11-15 17:27:48 +01:00
CaCO3
541e9841c2 Rename x_plain.yaml to blank.yaml 2024-11-15 17:27:23 +01:00
jomjol
fc3c70c63a Update dig-cont tlite to v712
Minor errata in quantization
2024-11-01 18:23:17 +01:00
github-actions[bot]
bfde8316ce docs(contributor): contrib-readme-action has updated readme 2024-10-19 08:36:57 +00:00
Bilal Mirza
fe0fec7fac Allow to Add a Move to Top button to enhance the ease of navigation for README readers. (#3344)
* Allow to Add a Move to Top button to enhance the ease of navigation for README readers.

* totally top of readme

* .

* Update README.md

* Update README.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-10-19 10:36:19 +02:00
jomjol
56abefe3df Update esp-nn and tflite to newest version (#3346)
* Pulled down update esp-nn

* Pulled tflite to master

* Update from main
2024-10-18 21:48:59 +02:00
CaCO3
43f15fcba3 Fix HA menu entry (#3342)
* Fix HA menu entry

* Update index.html

* Update index.html

* Update index.html

* Update index.html

* Update index.html
2024-10-18 10:45:05 +02:00
Bilal Mirza
dadf18f5c9 Fix: Broken Links i.e 404 page not found #3335 (#3336)
* Fix: Broken Links

* Update README.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-10-14 22:07:14 +02:00
CaCO3
c448ece680 Update the Homeasistant Discovery topics (#3332)
Update the Homeassistant Discovery topics
2024-10-13 23:04:28 +02:00
CaCO3
07d6eca456 Update README.md 2024-10-13 16:12:24 +02:00
CaCO3
4083d35b61 Update README.md 2024-10-13 15:55:30 +02:00
CaCO3
2319f8d302 Update README.md 2024-10-13 14:51:24 +02:00
Ranjana761
224e4380a8 Add batches to README.md (#3330)
* Update README.md

* Update README.md
2024-10-13 12:00:24 +02:00
jomjol
14d0c88a28 Update dig-cont_0711_s3_q.tflite
Error corrected version ov 0710 (adjusted quantization)
2024-10-13 10:13:06 +02:00
Farookh Zaheer Siddiqui
3c9b2c46c8 Update FeatureRequest.md (#3328) 2024-10-09 21:29:12 +02:00
jomjol
0752694600 Return vo v0700 2024-10-09 21:28:58 +02:00
github-actions[bot]
cf0ed268dd docs(contributor): contrib-readme-action has updated readme 2024-10-08 22:14:26 +00:00
CaCO3
f1979a142e Manual update of contributors list (#3325)
* Create manually-update-contributors-list

* Update and rename manually-update-contributors-list to manual-update-contributors-li.yamlst

* Update build.yaml

* Rename manual-update-contributors-li.yamlst to manual-update-contributors-li.yaml

* Rename manual-update-contributors-li.yaml to manual-update-contributors-list.yaml

* Update README.md
2024-10-09 00:13:43 +02:00
Austin Drenski
2a4f0f4a2d Update softAP.cpp (#3324) 2024-10-08 23:34:25 +02:00
KrishCode
45269bf45b Fixed docs README.md (#3323)
* Fixed docs README.md

I improved the file and enhanced its readability

* Update README.md

* Update README.md

* Update README.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-10-08 23:33:14 +02:00
Naman Tyagi
57db60fee4 fix: corrected grammatical and typographical errors in changelog (#3321) 2024-10-07 21:40:11 +02:00
Naman Tyagi
e1c49f39f0 Update README.md (#3322) 2024-10-07 21:39:09 +02:00
jomjol
7bebae3776 Clean up of old tflite files 2024-10-07 19:52:18 +02:00
CaCO3
0a4560ea95 Update Changelog.md 2024-10-07 00:21:07 +02:00
CaCO3
b44db21714 Update esp32-camera submodule to v2.0.13 (#3316)
Co-authored-by: CaCO3 <caco@ruinelli.ch>
2024-10-07 00:20:38 +02:00
CaCO3
34796ed091 Update build.yaml 2024-10-07 00:19:47 +02:00
CaCO3
a46dfd1c23 Add demo files (#3315)
* updated changelog

* add demo files

* Update build.yaml

* Update build.yaml

* Update build.yaml

* added missing files

* .

* .

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
2024-10-07 00:06:03 +02:00
CaCO3
32eb583036 Add contributor list (#3317)
* feat: #3310 Automatically Update Contributor List  (#3312)

* Create main.yml

* Update README.md

* docs(contributor): contrib-readme-action has updated readme

* Update main.yml

* docs(contributor): contrib-readme-action has updated readme

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* Update build.yaml

* docs(contributor): contrib-readme-action has updated readme

* Delete .github/workflows/main.yml

* Update README.md

* docs(contributor): contrib-readme-action has updated readme

* Update README.md

* docs(contributor): contrib-readme-action has updated readme

* Update build.yaml

* Update README.md

---------

Co-authored-by: Ayush Jhawar <111112495+Ayushjhawar8@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-10-06 23:25:19 +02:00
michael
6ee83b8413 Update ClassControllCamera.cpp (#3313)
https://github.com/jomjol/AI-on-the-edge-device/issues/3300#issuecomment-2395561022
2024-10-06 22:42:27 +02:00
CaCO3
f034232f36 Update config.ini 2024-10-06 22:33:24 +02:00
CaCO3
b80e43dfe9 Update config.ini 2024-10-06 22:31:56 +02:00
CaCO3
40c7c253ea Update config.ini 2024-10-06 22:29:06 +02:00
CaCO3
d11b312a96 Typos (#3309)
* Update edit_reference.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_reference.html
2024-10-06 16:57:26 +02:00
Naman Tyagi
2c1e531ed2 Fix grammar and typos in README.md for clarity and consistency (#3308) 2024-10-06 16:53:16 +02:00
CaCO3
c352e539bc Update build.yaml 2024-10-05 23:15:38 +02:00
CaCO3
a0333d906f use lower case for MQTT topic rate_per_digitization_round 2024-10-05 22:32:50 +02:00
CaCO3
ec00e943da Allow earlier start for AnalogToDigitTransitionStart 2024-10-05 22:26:26 +02:00
CaCO3
6175471a00 typo 2024-10-05 22:20:24 +02:00
CaCO3
948e76876f revert TFlite submodule update as certain modules crash with it, see #3269 (2nd attempt) 2024-10-05 22:18:37 +02:00
CaCO3
f4edb206d8 Master (#3297)
* fix pipeline (#3294)

* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>

* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: michael <Heinrich-Tuning@web.de>

* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update Changelog.md

* Update Changelog.md

* Prepare next release (#3267) (#3270)

* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------



* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------



* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------



* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.



* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------



* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------




* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------



* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------



* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------



* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------



* Update Changelog.md

* Update Changelog.md

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>

* revert TFlite submodule update as certain modules crash with it, see https://github.com/jomjol/AI-on-the-edge-device/issues/3269

* Rename NUMBER.AnalogDigitTransitionStart.md to NUMBER.AnalogToDigitTransitionStart.md

* Update NUMBER.AnalogToDigitTransitionStart.md

* Update edit_config_template.html

* changed the webhook UploadImg to false

* changed the webhook UploadImg to false (#3279)

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Show boolean option in settings page (#3285)

* changed the webhook UploadImg to false

* show boolean value on boolean drop down boxes

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* changed default value from boolean to numeric value in parameter camDenoise documentation

* Update edit_explain_7.html

https://github.com/jomjol/AI-on-the-edge-device/issues/3284?notification_referrer_id=NT_kwDOAAj1wbIxMjY3MDI1Njk3MDo1ODcyMDE#issuecomment-2387102786

* docs: update README.md (#3290)

prefered -> preferred

* rename/remove unused parameters (#3291)

* migrate-cam-parameters (#3288)

* Update main.cpp

* remove commented out code

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update Changelog.md

* cleanup

* Skip release jobs on non-release changes

* Update build.yaml

* Update build.yaml

* Update build.yaml

* Update build.yaml

* Update build.yaml

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>
Co-authored-by: Ikko Eltociear Ashimine <eltociear@gmail.com>

* update pipeline (#3296)

* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>

* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: michael <Heinrich-Tuning@web.de>

* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update Changelog.md

* Update Changelog.md

* Prepare next release (#3267) (#3270)

* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------



* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------



* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------



* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.



* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------



* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------




* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------



* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------



* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------



* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------



* Update Changelog.md

* Update Changelog.md

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>

* revert TFlite submodule update as certain modules crash with it, see https://github.com/jomjol/AI-on-the-edge-device/issues/3269

* Rename NUMBER.AnalogDigitTransitionStart.md to NUMBER.AnalogToDigitTransitionStart.md

* Update NUMBER.AnalogToDigitTransitionStart.md

* Update edit_config_template.html

* changed the webhook UploadImg to false

* changed the webhook UploadImg to false (#3279)

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Show boolean option in settings page (#3285)

* changed the webhook UploadImg to false

* show boolean value on boolean drop down boxes

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* changed default value from boolean to numeric value in parameter camDenoise documentation

* Update edit_explain_7.html

https://github.com/jomjol/AI-on-the-edge-device/issues/3284?notification_referrer_id=NT_kwDOAAj1wbIxMjY3MDI1Njk3MDo1ODcyMDE#issuecomment-2387102786

* docs: update README.md (#3290)

prefered -> preferred

* rename/remove unused parameters (#3291)

* migrate-cam-parameters (#3288)

* Update main.cpp

* remove commented out code

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update Changelog.md

* cleanup

* Skip release jobs on non-release changes

* Update build.yaml

* Update build.yaml

* Update build.yaml

* Update build.yaml

* Update build.yaml

* fix pipeline

* Update build.yaml

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>
Co-authored-by: Ikko Eltociear Ashimine <eltociear@gmail.com>

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>
Co-authored-by: Ikko Eltociear Ashimine <eltociear@gmail.com>
2024-10-04 23:25:59 +02:00
CaCO3
a9db769595 Update build.yaml 2024-10-04 23:19:24 +02:00
CaCO3
f0497eb924 fix pipeline 2024-10-04 23:07:36 +02:00
CaCO3
e53af6de0d Merge branch 'master' into rolling 2024-10-04 23:06:44 +02:00
CaCO3
3b7fe93d02 Update build.yaml 2024-10-04 23:05:46 +02:00
CaCO3
2f1d7e577c updated pipeline (#3293)
* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>

* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: michael <Heinrich-Tuning@web.de>

* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update Changelog.md

* Update Changelog.md

* Prepare next release (#3267) (#3270)

* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------



* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------



* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------



* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.



* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------



* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------




* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------



* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------



* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------



* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------



* Update Changelog.md

* Update Changelog.md

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>

* revert TFlite submodule update as certain modules crash with it, see https://github.com/jomjol/AI-on-the-edge-device/issues/3269

* Rename NUMBER.AnalogDigitTransitionStart.md to NUMBER.AnalogToDigitTransitionStart.md

* Update NUMBER.AnalogToDigitTransitionStart.md

* Update edit_config_template.html

* changed the webhook UploadImg to false

* changed the webhook UploadImg to false (#3279)

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Show boolean option in settings page (#3285)

* changed the webhook UploadImg to false

* show boolean value on boolean drop down boxes

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* changed default value from boolean to numeric value in parameter camDenoise documentation

* Update edit_explain_7.html

https://github.com/jomjol/AI-on-the-edge-device/issues/3284?notification_referrer_id=NT_kwDOAAj1wbIxMjY3MDI1Njk3MDo1ODcyMDE#issuecomment-2387102786

* docs: update README.md (#3290)

prefered -> preferred

* rename/remove unused parameters (#3291)

* migrate-cam-parameters (#3288)

* Update main.cpp

* remove commented out code

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update Changelog.md

* cleanup

* Skip release jobs on non-release changes

* Update build.yaml

* Update build.yaml

* Update build.yaml

* Update build.yaml

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>
Co-authored-by: Ikko Eltociear Ashimine <eltociear@gmail.com>
2024-10-04 22:59:44 +02:00
CaCO3
2a7247abfe Update build.yaml 2024-10-04 22:55:07 +02:00
CaCO3
37ba85717f Update build.yaml 2024-10-04 22:54:11 +02:00
CaCO3
97656114b6 Update build.yaml 2024-10-04 22:36:58 +02:00
CaCO3
6cf1d5ad98 Update build.yaml 2024-10-04 22:22:53 +02:00
CaCO3
fed729bcee Skip release jobs on non-release changes 2024-10-04 22:20:38 +02:00
CaCO3
89c36374b3 RC2 preparations (#3292)
* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>

* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: michael <Heinrich-Tuning@web.de>

* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update Changelog.md

* Update Changelog.md

* Prepare next release (#3267) (#3270)

* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------



* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------



* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------



* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.



* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------



* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------




* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------



* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------



* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------



* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------



* Update Changelog.md

* Update Changelog.md

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>

* revert TFlite submodule update as certain modules crash with it, see https://github.com/jomjol/AI-on-the-edge-device/issues/3269

* Rename NUMBER.AnalogDigitTransitionStart.md to NUMBER.AnalogToDigitTransitionStart.md

* Update NUMBER.AnalogToDigitTransitionStart.md

* Update edit_config_template.html

* changed the webhook UploadImg to false

* changed the webhook UploadImg to false (#3279)

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Show boolean option in settings page (#3285)

* changed the webhook UploadImg to false

* show boolean value on boolean drop down boxes

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* changed default value from boolean to numeric value in parameter camDenoise documentation

* Update edit_explain_7.html

https://github.com/jomjol/AI-on-the-edge-device/issues/3284?notification_referrer_id=NT_kwDOAAj1wbIxMjY3MDI1Njk3MDo1ODcyMDE#issuecomment-2387102786

* docs: update README.md (#3290)

prefered -> preferred

* rename/remove unused parameters (#3291)

* migrate-cam-parameters (#3288)

* Update main.cpp

* remove commented out code

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update Changelog.md

* cleanup

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>
Co-authored-by: Ikko Eltociear Ashimine <eltociear@gmail.com>
2024-10-04 22:05:15 +02:00
CaCO3
bb69929247 cleanup 2024-10-04 22:03:41 +02:00
CaCO3
e1ea09c501 Merge branch 'master' into rolling 2024-10-04 22:00:28 +02:00
CaCO3
39a827258d Update Changelog.md 2024-10-04 21:55:45 +02:00
michael
1d8c6fa257 migrate-cam-parameters (#3288)
* Update main.cpp

* remove commented out code

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-10-04 21:43:06 +02:00
CaCO3
a9aadbdb06 rename/remove unused parameters (#3291) 2024-10-04 21:31:57 +02:00
Ikko Eltociear Ashimine
a5927f98d2 docs: update README.md (#3290)
prefered -> preferred
2024-10-04 21:14:47 +02:00
michael
c708e2374a Update edit_explain_7.html
https://github.com/jomjol/AI-on-the-edge-device/issues/3284?notification_referrer_id=NT_kwDOAAj1wbIxMjY3MDI1Njk3MDo1ODcyMDE#issuecomment-2387102786
2024-10-02 01:43:50 +02:00
CaCO3
4c3dcd8c29 changed default value from boolean to numeric value in parameter camDenoise documentation 2024-10-02 00:43:32 +02:00
CaCO3
be93567956 Merge branch 'rolling' of https://github.com/jomjol/AI-on-the-edge-device into rolling 2024-10-02 00:40:35 +02:00
CaCO3
d4406f47ea Show boolean option in settings page (#3285)
* changed the webhook UploadImg to false

* show boolean value on boolean drop down boxes

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
2024-10-02 00:38:59 +02:00
CaCO3
52efedcfa0 Merge branch 'rolling' of https://github.com/jomjol/AI-on-the-edge-device into rolling 2024-10-01 18:52:19 +02:00
CaCO3
28d93253f0 changed the webhook UploadImg to false (#3279)
Co-authored-by: CaCO3 <caco@ruinelli.ch>
2024-09-30 21:16:22 +02:00
CaCO3
c7fdc46df2 changed the webhook UploadImg to false 2024-09-30 21:08:48 +02:00
CaCO3
74491e9bde Update edit_config_template.html 2024-09-30 20:50:20 +02:00
CaCO3
a092142c65 Update NUMBER.AnalogToDigitTransitionStart.md 2024-09-30 20:46:29 +02:00
CaCO3
f6a3dc5851 Rename NUMBER.AnalogDigitTransitionStart.md to NUMBER.AnalogToDigitTransitionStart.md 2024-09-30 20:40:02 +02:00
CaCO3
d027adf006 revert TFlite submodule update as certain modules crash with it, see https://github.com/jomjol/AI-on-the-edge-device/issues/3269 2024-09-30 19:48:49 +02:00
CaCO3
bd5be5c5ec Prepare next release (#3267) (#3270)
* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------



* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------



* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------



* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.



* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------



* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------




* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------



* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------



* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------



* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------



* Update Changelog.md

* Update Changelog.md

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>
2024-09-29 23:22:55 +02:00
CaCO3
ca01f5a38f Prepare next release (#3267)
* Create dig-cont_0640_s3_q.tflite

* Update edit_reference.html (#2924)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist

* Update edit_config_template.html (#2925)

Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen

* The parameter "negative" is processed on the MCU

* Renamed menu entry Alignment -> References

* renamed model file to make naming consistent

* Fix test (#2933)

* always reset change absolute (#2956)

* Create dig-class11_1701_s2.tflite

* Update tflite

* Update tflite

* Camera settings (#3029)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Fix minor typo and harmonize spaces (#3030)

* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>

* Source code formatting, ClassFlowPostProcessing.cpp

* fix edit_config_template.html

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix readconfigparam.js

Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^

* fix edit_config_template.html

TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.

* Update info.html

function loadWLANSSID() was present three times

* Update overview.html

CamFrameSize is no longer needed/used for zoom

* Update reply-bot.yaml

* homeassistant service discovery: derive node_id when using nested topics (#3088)

* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery

* add Prometheus/OpenMetrics exporter (#3081)

* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Typo

* update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)

* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update reply-bot.yaml (#3107)

* Fix actions-label-commenter

* Update Helper.cpp

* Update Helper.h

* Update Helper.cpp

* Update readconfigparam.js

fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!

* proposal for renaming and documentation (#3115)

* Update server_camera.cpp

 Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowAlignment.cpp

* Fix building with `-D DEBUG_DETAIL_ON` (#3160)

Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Handle empty prevalue.ini gracefully (#3162)

Fixes #2149.

* Bugfix for boot loop (#3175)

* Add files via upload

* Add files via upload

* Add files via upload

* Delete param-docs/parameter-pages/TakeImage/Aec2.md

has been replaced by CamAec2.md

* Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md

has been replaced by CamAeLevel.md

* Delete param-docs/parameter-pages/TakeImage/Brightness.md

has been replaced by CamBrightness.md

* Delete param-docs/parameter-pages/TakeImage/Contrast.md

has been replaced by CamContrast.md

* Delete param-docs/parameter-pages/TakeImage/Grayscale.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Negative.md

has been replaced by CamSpecialEffect.md

* Delete param-docs/parameter-pages/TakeImage/Saturation.md

has been replaced by CamSaturation.md

* Delete param-docs/parameter-pages/TakeImage/Sharpness.md

has been replaced by CamSharpness.md

* Delete param-docs/parameter-pages/TakeImage/ImageQuality.md

has been replaced by CamQuality.md

* Delete param-docs/parameter-pages/TakeImage/Zoom.md

has been replaced by CamZoom.md

* Delete param-docs/parameter-pages/TakeImage/ZoomMode.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md

has been replaced by CamZoomOffsetX.md

* Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md

has been replaced by CamZoomOffsetY.md

* Delete param-docs/parameter-pages/TakeImage/ImageSize.md

has been replaced by CamZoomSize.md

* Delete param-docs/parameter-pages/TakeImage/FixedExposure.md

has been replaced by CamAec.md

* Delete param-docs/parameter-pages/Alignment/FlipImageSize.md

has been replaced by CamVflip.md

* Delete param-docs/parameter-pages/Alignment/InitialMirror.md

has been replaced by CamHmirror.md

* CamParameter documentation update

https://github.com/jomjol/AI-on-the-edge-device/issues/3185

* typo

* add Webhook #3148 (#3163)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Bugfix for time stamp (#3180)

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp

* Update readconfigcommon.js

fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".

* fix svg favicon 

The svg one got added in 33893eb566 but does not work on Firefox

* Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)

* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: michael <Heinrich-Tuning@web.de>

* Update MainFlowControl.cpp

* Add support for OV5640 camera (#3063)

* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors

* Update MainFlowControl.cpp

* Add rate threshold parameter (#3195)

* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Update main.cpp

* Update config.ini

Adjusted camera settings to make the image brighter.

* Update readconfigparam.js

Adjusted camera settings to make the image brighter.

* add optional ImageUpload for Webhook (#3174)

* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>

* Add files via upload (#3207)

* Update ClassFlowPostProcessing.cpp

deleted some unnecessary double entries
RateType renamed to MaxRateType

* Update ClassFlowDefineTypes.h

RateType renamed to MaxRateType

* Update text on recognition page

* Update digital CNN

* add a Delay between the WiFi reconnections (#3068)

* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log

* cleanup

* cleanup

* cleanup

* Update edit_alignment.html

* cleanup

* cleanup

* Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1)

* Handle crash on corrupted model (#3220)

* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* new dig-class100-173-s2-q on 23.800 images (#3257)

* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.

* moved number edit box styles into new file edit_style.css (#3262)

changed input[type=number] from 60px to 3em, to show 3 digits with current font size.

* added note about only TLS 1.2 is supported (#3213)

* Renamed digital to digit (#3219)

* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>

* Update Changelog.md

* Update Changelog.md

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
Co-authored-by: michael <Heinrich-Tuning@web.de>
Co-authored-by: Frank Haverland <fspapaping@googlemail.com>
Co-authored-by: kub3let <95883234+kub3let@users.noreply.github.com>
Co-authored-by: Marco H <myxor@users.noreply.github.com>
Co-authored-by: Henry Thasler <henrythasler@users.noreply.github.com>
Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: Sebastian Lövdahl <slovdahl@hibox.fi>
Co-authored-by: Raphael Hehl <raphael@rhehl.de>
Co-authored-by: jasaw <jasaw@dius.com.au>
Co-authored-by: Francesco Carnielli <hex7c0@gmail.com>
Co-authored-by: kalwados <kalwados@gmx.de>
2024-09-29 23:22:33 +02:00
CaCO3
3b3a3ebcc9 Update Changelog.md 2024-09-29 23:20:15 +02:00
CaCO3
7d62cf67fe Update Changelog.md 2024-09-29 23:00:30 +02:00
CaCO3
f6bdd48bca Renamed digital to digit (#3219)
* renamed Digital to Digit

* added param migration

* Update .github/label-commenter-config.yaml

* renamed AnalogDigitTransition* to AnalogToDigitTransition*

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
2024-09-29 22:10:10 +02:00
CaCO3
5496573369 added note about only TLS 1.2 is supported (#3213) 2024-09-29 22:01:38 +02:00
kalwados
4522ba087f moved number edit box styles into new file edit_style.css (#3262)
changed input[type=number] from 60px to 3em, to show 3 digits with current font size.
2024-09-29 21:08:45 +02:00
Frank Haverland
d370ba5fe6 new dig-class100-173-s2-q on 23.800 images (#3257)
* new dig-class100-173-s2-q on 23.800 images

* platformio/espressif32 @ 6.8.1 for esp32cam-dev

* Revert "platformio/espressif32 @ 6.8.1 for esp32cam-dev"

This reverts commit cc9297d483.

* not using platformio 6.1.16

* Revert "not using platformio 6.1.16"

This reverts commit ef18e4fae7.
2024-09-28 15:40:24 +02:00
CaCO3
f39dacc1c5 Handle crash on corrupted model (#3220)
* Upgrade esp-tflite-micro to 1.3.1

* Added log message to hint in case it crashes on loading a corrupted model

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
2024-09-28 15:29:15 +02:00
michael
aad1a0e78d Update platformIO to 6.9.0 (Contains ESP IDF 5.3.1) 2024-09-26 21:22:22 +02:00
michael
276efef783 cleanup 2024-09-26 17:34:12 +02:00
michael
79476a8458 cleanup 2024-09-26 16:29:31 +02:00
michael
2b7da5b44e Update edit_alignment.html 2024-09-26 14:41:25 +02:00
michael
ebcec97d1d cleanup 2024-09-24 03:12:27 +02:00
michael
85375b6505 cleanup 2024-09-24 02:53:36 +02:00
michael
085c47b651 cleanup 2024-09-23 15:44:30 +02:00
Francesco Carnielli
20a04b888f add a Delay between the WiFi reconnections (#3068)
* add a Delay between the WiFi reconnections

* log the delay between the WiFi reconnections

move the delay after the log
2024-09-22 21:50:38 +02:00
jomjol
098b1bd025 Update digital CNN 2024-09-17 20:47:13 +02:00
CaCO3
d1c815ce69 Update text on recognition page 2024-09-03 23:10:15 +02:00
michael
67c3020d7d Update ClassFlowDefineTypes.h
RateType renamed to MaxRateType
2024-09-01 16:36:51 +02:00
michael
61bca4ebb8 Update ClassFlowPostProcessing.cpp
deleted some unnecessary double entries
RateType renamed to MaxRateType
2024-09-01 16:36:40 +02:00
michael
3219202c53 Add files via upload (#3207) 2024-09-01 08:34:29 +02:00
Raphael Hehl
cd29690b96 add optional ImageUpload for Webhook (#3174)
* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: add img upload

* webhoop added config for imgupload

* webhook html fixes

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

* add checkbox for Webhook_UploadImg

* Update sd-card/html/edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* Update edit_config_template.html

* added a long timestamp to both webhook requests

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-09-01 08:33:46 +02:00
michael
3a34564ee2 Update readconfigparam.js
Adjusted camera settings to make the image brighter.
2024-08-31 16:09:29 +02:00
michael
174743ae7f Update config.ini
Adjusted camera settings to make the image brighter.
2024-08-31 16:08:48 +02:00
michael
e5eca6a53f Update main.cpp 2024-08-31 15:33:06 +02:00
michael
d8e37dce48 Add rate threshold parameter (#3195)
* still needs to be tested

https://github.com/jomjol/AI-on-the-edge-device/issues/3143

* Update ClassFlowPostProcessing.cpp

code formatting

* Update ClassFlowDefineTypes.h

code formatting

* Update ClassFlowPostProcessing.h

code formatting

* Update edit_config_template.html

* fix

* Update config.ini

* Update edit_config_template.html

* Updated param doc

* Rename parameters

* Update edit_config_template.html

* Update NUMBER.ChangeRateThreshold.md

* Update NUMBER.ChangeRateThreshold.md

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-08-30 19:29:57 +02:00
michael
822753bb4f Update MainFlowControl.cpp 2024-08-30 00:18:35 +02:00
jasaw
7225792b4b Add support for OV5640 camera (#3063)
* Add support for OV5640 camera

* clean up sharpness handling

* limit sharpness range to -2 and +2

* refactor

* Fix OV3660 sharpness handling

* refactor sharpness handling

* fix OV3660 zoom mode

* reinstate aspect ratio via imageSize

* Changed OV5640 full frame size to match datasheet

* various fixes

* add denoise config and general clean up

* fix line endings to LF

* Support enabling red blue swap via web interface

* update jpeg quality limits

* remove color swap config; color swap workaround dependent on vflip

* fix missing commit

* fix gain ceiling

* Update cam vflip param page

* fix typo: camdenoise, not camsdenoise

* fix compile errors
2024-08-29 21:57:26 +02:00
michael
b4f6b1a4fb Update MainFlowControl.cpp 2024-08-29 18:45:35 +02:00
CaCO3
21ec58daa0 Update platformIO to 6.8.1 (Contains ESP IDF 5.3) (#3196)
* Update platformIO to 6.8.1 (ESP IDF 5.3)

* removed now redundant typedef

* updated IDF manifest hash

* Add files via upload

so it should work now

* Update server_main.cpp

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
Co-authored-by: michael <Heinrich-Tuning@web.de>
2024-08-28 22:26:44 +02:00
CaCO3
2c69e90fac fix svg favicon
The svg one got added in 33893eb566 but does not work on Firefox
2024-08-27 21:01:56 +02:00
michael
5c57522b71 Update readconfigcommon.js
fix for: The same message("Image Contrast got enhanced") came up with "Update Marker" and "Enhance Image Contrast".
2024-08-27 16:56:23 +02:00
michael
f8eb4db171 Bugfix for time stamp (#3180)
* Update ClassFlowPostProcessing.cpp

* Update ClassFlowDefineTypes.h

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update ClassFlowPostProcessing.cpp

* Update interface_webhook.cpp
2024-08-24 13:19:21 +02:00
Raphael Hehl
c9a3df4eec add Webhook #3148 (#3163)
* WIP add Webhook

* fix config html for webhook
add tooltips for webhook

* webhook: fix not enabling webhook

* send webhook as json

* Update ApiKey.md

* webhook: fix only sending last "Number"

* webhook JSON is now closer to the data log in CSV format

* webhook: drop timeStampTimeUTC and switch from timeStamp to lastvalue like lokal csv to fix no timestamp on error

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-08-24 00:05:16 +02:00
CaCO3
acf669900f typo 2024-08-20 23:00:24 +02:00
michael
cb3f082218 CamParameter documentation update
https://github.com/jomjol/AI-on-the-edge-device/issues/3185
2024-08-19 00:42:33 +02:00
michael
20980b2bcd Delete param-docs/parameter-pages/Alignment/InitialMirror.md
has been replaced by CamHmirror.md
2024-08-18 04:39:21 +02:00
michael
773d21a875 Delete param-docs/parameter-pages/Alignment/FlipImageSize.md
has been replaced by CamVflip.md
2024-08-18 04:38:07 +02:00
michael
3a9c9ac2a4 Delete param-docs/parameter-pages/TakeImage/FixedExposure.md
has been replaced by CamAec.md
2024-08-18 04:36:01 +02:00
michael
c7e340d3a5 Delete param-docs/parameter-pages/TakeImage/ImageSize.md
has been replaced by CamZoomSize.md
2024-08-18 04:29:11 +02:00
michael
0441753a33 Delete param-docs/parameter-pages/TakeImage/ZoomOffsetY.md
has been replaced by CamZoomOffsetY.md
2024-08-18 04:27:18 +02:00
michael
fb6cb44728 Delete param-docs/parameter-pages/TakeImage/ZoomOffsetX.md
has been replaced by CamZoomOffsetX.md
2024-08-18 04:26:32 +02:00
michael
ae69942dd9 Delete param-docs/parameter-pages/TakeImage/ZoomMode.md
has been replaced by CamZoomSize.md
2024-08-18 04:25:47 +02:00
michael
65437727f7 Delete param-docs/parameter-pages/TakeImage/Zoom.md
has been replaced by CamZoom.md
2024-08-18 04:24:42 +02:00
michael
ccefe57795 Delete param-docs/parameter-pages/TakeImage/ImageQuality.md
has been replaced by CamQuality.md
2024-08-18 04:22:49 +02:00
michael
e3ff049720 Delete param-docs/parameter-pages/TakeImage/Sharpness.md
has been replaced by CamSharpness.md
2024-08-18 04:21:41 +02:00
michael
39e84baf8b Delete param-docs/parameter-pages/TakeImage/Saturation.md
has been replaced by CamSaturation.md
2024-08-18 04:20:44 +02:00
michael
eb7d078a1a Delete param-docs/parameter-pages/TakeImage/Negative.md
has been replaced by CamSpecialEffect.md
2024-08-18 04:19:42 +02:00
michael
b6c6805a08 Delete param-docs/parameter-pages/TakeImage/Grayscale.md
has been replaced by CamSpecialEffect.md
2024-08-18 04:19:22 +02:00
michael
d567a5d7f2 Delete param-docs/parameter-pages/TakeImage/Contrast.md
has been replaced by CamContrast.md
2024-08-18 04:17:35 +02:00
michael
6922970185 Delete param-docs/parameter-pages/TakeImage/Brightness.md
has been replaced by CamBrightness.md
2024-08-18 04:16:33 +02:00
michael
9a4b51d6de Delete param-docs/parameter-pages/TakeImage/AutoExposureLevel.md
has been replaced by CamAeLevel.md
2024-08-18 04:15:42 +02:00
michael
2546ab81ff Delete param-docs/parameter-pages/TakeImage/Aec2.md
has been replaced by CamAec2.md
2024-08-18 04:14:09 +02:00
michael
7b7544079f Bugfix for boot loop (#3175)
* Add files via upload

* Add files via upload

* Add files via upload
2024-08-17 23:02:21 +02:00
Sebastian Lövdahl
17fe87b349 Handle empty prevalue.ini gracefully (#3162)
Fixes #2149.
2024-08-09 01:01:58 +02:00
Sebastian Lövdahl
f99dc8fdfc Fix building with -D DEBUG_DETAIL_ON (#3160)
Building with `-D DEBUG_DETAIL_ON` has been broken since #3029.

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-08-09 01:00:38 +02:00
michael
cce992754c Update ClassFlowAlignment.cpp 2024-08-06 00:59:39 +02:00
michael
eefccf6e11 Update ClassFlowPostProcessing.cpp 2024-08-06 00:56:55 +02:00
michael
64bb4f0ff6 Update server_camera.cpp
Fix building with -D DEBUG_DETAIL_ON 

better alternative to:
https://github.com/jomjol/AI-on-the-edge-device/pull/3160
2024-08-05 23:57:17 +02:00
Henry Thasler
f534741205 proposal for renaming and documentation (#3115) 2024-07-21 14:09:51 +02:00
michael
ee38bc7dc6 Update readconfigparam.js
fix for:
In the selected field the value '1' in the section 'TakeImage' in the field 'CamGainceiling' is invalid. PLEASE CHECK BEFORE SAVING!
2024-07-20 15:53:16 +02:00
michael
132834c3fd Update Helper.cpp 2024-07-17 16:07:23 +02:00
michael
d3d9c64f3b Update Helper.h 2024-07-17 13:14:00 +02:00
michael
aa2a4edf7e Update Helper.cpp 2024-07-17 13:12:15 +02:00
CaCO3
8012b7f43e Fix actions-label-commenter 2024-06-09 23:20:13 +02:00
CaCO3
009ab4c896 Update reply-bot.yaml (#3107) 2024-06-09 23:13:34 +02:00
CaCO3
c54ca18e4e update platformIO to 6.7.0 (ESP IDF 5.2.1) (#3098)
* update to platformio/espressif32 @ 6.7.0

* remove unused getReadout() as it throws errors (error: 'virtual std::string ClassFlow::getReadout()' was hidden).

---------

Co-authored-by: CaCO3 <caco@ruinelli.ch>
2024-06-03 23:36:14 +02:00
CaCO3
beb09593eb Typo 2024-06-02 23:04:42 +02:00
Henry Thasler
1a76ae121c add Prometheus/OpenMetrics exporter (#3081)
* add prometheus endpoint

* refine metrics implementation

* move metrics generator to ClassFlowControll

* add more metrics
align prefix

* add more metrics
clean up

* refine documentation

* revert dependencies change

* sanitize labels

* create separate module for openmetrics

* move openmetrics to separate folder

* clean up

* add basic unit-tests

* work with const numbers
add replaceAll for string replacement
avoid opening std namespace
adapt unit-tests

* Update code/main/server_main.cpp

---------

Co-authored-by: CaCO3 <caco3@ruinelli.ch>
2024-06-02 21:13:15 +02:00
Henry Thasler
1300242d4a homeassistant service discovery: derive node_id when using nested topics (#3088)
* derive correct node_id for homeassistant service discovery in nested topics (fixes #1792)

* explicit use of std::string

* move nodeId creation to separate function
add unit-tests

* add documentation about node_id generation for Home Assistant MQTT Service Discovery
2024-06-02 21:00:44 +02:00
CaCO3
79543df23b Update reply-bot.yaml 2024-05-07 23:57:02 +02:00
michael
4049d752ba Update overview.html
CamFrameSize is no longer needed/used for zoom
2024-04-27 00:03:26 +02:00
michael
dc90972659 Update info.html
function loadWLANSSID() was present three times
2024-04-24 07:25:14 +02:00
michael
32282ecfe2 fix edit_config_template.html
TakeImage_CamZoomMode_value1 was replaced by TakeImage_CamZoomSize_value1, but not deleted.
This caused problems when saving the camera settings.
2024-04-16 13:14:27 +02:00
michael
ae6a94544b fix readconfigparam.js
Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^
2024-04-16 04:26:35 +02:00
michael
70b031eacc fix edit_config_template.html
Unfortunately, I didn't take out some entries from other experiments because I overlooked/forgot them^^
2024-04-16 04:25:51 +02:00
michael
c3fadf5c2a Source code formatting, ClassFlowPostProcessing.cpp 2024-04-15 22:12:02 +02:00
Marco H
7e5f6bf4a5 Fix minor typo and harmonize spaces (#3030)
* Update edit_digits.html

* Update edit_analog.html

* Update overview.html

* Update edit_reference.html

---------

Co-authored-by: jomjol <30766535+jomjol@users.noreply.github.com>
2024-04-11 21:28:33 +02:00
michael
88b531ae8b Camera settings (#3029)
* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload
2024-04-11 21:12:40 +02:00
jomjol
8481cc4b26 Update tflite 2024-03-30 14:47:26 +01:00
jomjol
ecaed38c1d Update tflite 2024-03-30 09:07:42 +01:00
jomjol
d6a1838d47 Create dig-class11_1701_s2.tflite 2024-03-25 08:25:47 +01:00
kub3let
5194c466be always reset change absolute (#2956) 2024-03-22 21:55:11 +01:00
Frank Haverland
043de9265a Fix test (#2933) 2024-03-20 19:22:33 +01:00
CaCO3
08a350172d renamed model file to make naming consistent 2024-03-13 22:28:41 +01:00
CaCO3
7e806df64d Renamed menu entry Alignment -> References 2024-02-18 09:52:24 +01:00
CaCO3
dccfb5e91e The parameter "negative" is processed on the MCU 2024-02-17 22:01:31 +01:00
michael
fbe4609bb9 Update edit_config_template.html (#2925)
Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist +
Kameraeinstellungen nicht nur in der config.ini speichern, sondern auch setzen
2024-02-17 10:17:08 +01:00
michael
3e85cfb456 Update edit_reference.html (#2924)
Zoom-Einstellungen ausblenden, wenn zoom deaktiviert ist
2024-02-17 10:17:00 +01:00
jomjol
5dff4ca8cf Create dig-cont_0640_s3_q.tflite 2024-02-17 08:25:12 +01:00
CaCO3
0d0b0187f4 Update index.html 2024-02-17 01:13:17 +01:00
CaCO3
4cf9ea6c45 updated changelog 2024-02-17 00:51:10 +01:00
CaCO3
1b76e0f449 restructure menu 2024-02-17 00:50:41 +01:00
CaCO3
d4a0ad20ff Restructure menus (#2921)
* renamed config pages
* restructured menu
2024-02-17 00:40:46 +01:00
CaCO3
df72445e79 show note a bit longer 2024-02-16 22:45:32 +01:00
CaCO3
456cb93809 Update reply-bot.yaml 2024-02-16 22:36:16 +01:00
CaCO3
d968a7adc6 Update reply-bot.yaml 2024-02-16 22:33:38 +01:00
CaCO3
9a52b8b2f3 Update reply-bot.yaml 2024-02-16 22:30:15 +01:00
CaCO3
8caa852bbf Update info.html 2024-02-16 22:27:00 +01:00
michael
4faca4c46c Update edit_reference.html (#2914)
On the ref image page, when a cam setting gets changed, disable the save button to enforce creating a new image first
2024-02-16 22:16:38 +01:00
michael
238fc5fae3 Update edit_config_param_template.html (#2915)
Show Warning when changing camera settings in edit config param
2024-02-16 22:13:09 +01:00
CaCO3
c32ca5a23c the yaml files must have the file extention yaml. If they are called yml, they are threated slightly different in the actions section 2024-02-16 00:03:24 +01:00
CaCO3
827d9d1700 updated param doc: added note that the ref image and alignment marks need to be updated as well (#2916)
param-doc: added note that the ref image and alignment marks need to be updated as well
2024-02-15 23:49:14 +01:00
CaCO3
0ea4b3b3ce Update Changelog.md 2024-02-15 23:28:50 +01:00
CaCO3
3e26c6c743 restructured ROI pages 2024-02-15 22:16:18 +01:00
michael
fa5c99b3cb Button to hide other red Digit Frames (#2907)
Button to hide other red Digit Frames for easier setup, implements #2680
2024-02-15 21:55:01 +01:00
CaCO3
6feae4e239 Use valid default values 2024-02-15 00:12:37 +01:00
CaCO3
ef64be3888 Enhance ref image page (#2910)
Enhanced Reference Image page
2024-02-14 23:49:35 +01:00
CaCO3
cc89d625f2 Enhance ref image page2 (#2908)
minor fixes
2024-02-14 21:02:08 +01:00
CaCO3
08ba754b88 Restructure reference image page (#2905) 2024-02-14 16:54:31 +01:00
michael
6b38e44d7f Loading alignment page faster (#2868)
Da es Probleme mit param_temp gab (mal ging es, mal nicht), habe ich extra Parameter angelegt (_rotate_temp, _mirror_temp, _isize_temp, _grayscale_temp, _negative_temp, _aec2_temp, _FixedExposure_temp, _zoom_temp, _zm_temp, _x_temp, _y_temp, _intensity_temp, _brightness_temp, _contrast_temp, _saturation_temp, _sharpness_temp, _ae_temp).
Bei den bisherigen Tests, hat alles so funktioniert wie es soll.
2024-02-14 16:24:29 +01:00
CaCO3
141aea7fa7 Revert "Implemented late analog / digital transition (#2778)"
This reverts commit b5a4cfed96.
2024-02-12 22:41:56 +01:00
CaCO3
bcd07761b6 . 2024-02-12 22:37:46 +01:00
CaCO3
fe4d861e15 . 2024-02-12 22:37:46 +01:00
CaCO3
71322c9fbe fixed review findings 2024-02-12 22:37:46 +01:00
CaCO3
f8b4881a50 . 2024-02-12 22:37:46 +01:00
CaCO3
438d5696e4 . 2024-02-12 22:37:46 +01:00
CaCO3
0d391c8780 . 2024-02-12 22:37:46 +01:00
CaCO3
59de6319a1 . 2024-02-12 22:37:46 +01:00
CaCO3
3805687219 . 2024-02-12 22:37:46 +01:00
CaCO3
c6a789dc45 . 2024-02-12 22:37:46 +01:00
CaCO3
246f9cfc31 . 2024-02-12 22:37:46 +01:00
CaCO3
b2d8c60bb1 . 2024-02-12 22:37:46 +01:00
CaCO3
1d573cd18a . 2024-02-12 22:37:46 +01:00
CaCO3
b2e5cdd8a3 . 2024-02-12 22:37:46 +01:00
CaCO3
f7fde7c430 . 2024-02-12 22:37:46 +01:00
CaCO3
2c19080a66 . 2024-02-12 22:37:46 +01:00
CaCO3
35663c5fd4 add tooltip css 2024-02-12 22:37:46 +01:00
CaCO3
5b449d5c45 update param doc 2024-02-12 22:37:46 +01:00
CaCO3
3a5f3496d5 fix typo in variable name 2024-02-12 22:37:46 +01:00
CaCO3
00434d01c3 update action 2024-02-12 22:37:46 +01:00
CaCO3
3e0bb81e32 added tooltips to reference image page 2024-02-12 22:37:46 +01:00
CaCO3
4f57f9eafd add spacing 2024-02-12 22:37:46 +01:00
CaCO3
f24ec581e6 Added FixedExposure to reference image page 2024-02-12 22:37:46 +01:00
CaCO3
0d78bb78ea corrected default 2024-02-12 22:37:46 +01:00
CaCO3
47aea007b3 Added param InitialMirror to config page 2024-02-12 22:37:46 +01:00
CaCO3
284b3f428e on reference image page, hide expert params and add checkbox to unhide them 2024-02-12 22:37:46 +01:00
CaCO3
92d45c7971 Moved 6 Reference Impage Parameters from expert to normal level 2024-02-12 22:37:46 +01:00
CaCO3
ff1d9d3b4f prepare table row IDs to be removed as tehy seem unused 2024-02-12 22:37:46 +01:00
CaCO3
2b57dd0853 . 2024-02-12 22:37:46 +01:00
CaCO3
dd8f5eea22 Added parameters to config page 2024-02-12 22:37:46 +01:00
Joo Aun Saw
60c5305378 Fix up Zoom option documentation 2024-02-12 22:37:46 +01:00
Joo Aun Saw
8b1c65a38a add documentation for new TakeImage options 2024-02-12 22:37:46 +01:00
Joo Aun Saw
4f5933c4f2 add default values for new TakeImage options in config.ini 2024-02-12 22:37:46 +01:00
Joo Aun Saw
06c9bfb0de html: fix negative not applied correctly after saving reference 2024-02-12 22:37:46 +01:00
Joo Aun Saw
69f1a99b55 ov2640: support sharpness control 2024-02-12 22:37:46 +01:00
Joo Aun Saw
a8fb88a35d Support negative photo effect and auto exposure control 2 2024-02-12 22:37:46 +01:00
Joo Aun Saw
d418d22155 removed redundant changes 2024-02-12 22:37:46 +01:00
Joo Aun Saw
53e8cf49f9 limit auto exposure values to range -2 to +2 2024-02-12 22:37:46 +01:00
Joo Aun Saw
ac4f823cbf Support crop image on sensor, grayscale, auto exposure level 2024-02-12 22:37:46 +01:00
CaCO3
444dc0fa39 add missing image 2024-02-11 22:14:57 +01:00
CaCO3
5053a31245 renaming 2024-02-11 22:10:41 +01:00
CaCO3
44cf8933d4 . 2024-02-11 22:10:41 +01:00
CaCO3
35de56be04 Add Firmware Version to MQTT 2024-02-11 22:10:41 +01:00
257 changed files with 17585 additions and 9795 deletions

View File

@@ -115,9 +115,9 @@
labeled: labeled:
issue: issue:
body: | body: |
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. 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.
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/). 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: discussion:
body: | body: |
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. 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.
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/). 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,7 +14,7 @@ jobs:
uses: fkirc/skip-duplicate-actions@v5 uses: fkirc/skip-duplicate-actions@v5
with: with:
concurrent_skipping: same_content_newer concurrent_skipping: same_content_newer
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
submodules: recursive submodules: recursive
@@ -37,14 +37,14 @@ jobs:
path: ~/.platformio path: ~/.platformio
key: platformio-${{ github.run_id }} 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 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 - name: Update Build cache on every commit
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
path: ./code/.pio/ path: ./code/.pio/
key: build-${{ github.run_id }} 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 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 - name: Update generated-files cache on every commit
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
@@ -53,6 +53,7 @@ jobs:
./code/.pio/build/esp32cam/partitions.bin ./code/.pio/build/esp32cam/partitions.bin
./code/.pio/build/esp32cam/bootloader.bin ./code/.pio/build/esp32cam/bootloader.bin
./html/* ./html/*
./demo/*
key: generated-files-${{ github.run_id }} 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 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
@@ -85,8 +86,22 @@ jobs:
cp -r ./sd-card/html/* ./html/ cp -r ./sd-card/html/* ./html/
echo "Replacing variables..." echo "Replacing variables..."
cd html; find . -type f -exec sed -i 's/$COMMIT_HASH/${{ steps.vars.outputs.sha_short }}/g' {} \; cd html
find . -type f -exec sed -i 's/$COMMIT_HASH/${{ steps.vars.outputs.sha_short }}/g' {} \;
echo "compressing all html files..."
find . -name "*.html" -type f -exec gzip {} \;
find . -name "*.css" -type f -exec gzip {} \;
find . -name "*.js" -type f -exec gzip {} \;
find . -name "*.jpg" -type f -exec gzip {} \;
find . -name "*.png" -type f -exec gzip {} \;
find . -name "*.svg" -type f -exec gzip {} \;
find . -name "*.map" -type f -exec gzip {} \;
- name: Prepare Demo mode files
run: |
rm -rf ./demo
mkdir demo
cp -r ./sd-card/demo/* ./demo/
######################################################################################### #########################################################################################
## Pack for Update ## Pack for Update
@@ -97,6 +112,7 @@ jobs:
# - /firmware.bin # - /firmware.bin
# - (optional) /html/* (inkl. subfolders) # - (optional) /html/* (inkl. subfolders)
# - (optional) /config/*.tfl # - (optional) /config/*.tfl
# - (optional) /demo/*
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: build needs: build
@@ -111,6 +127,7 @@ jobs:
./code/.pio/build/esp32cam/partitions.bin ./code/.pio/build/esp32cam/partitions.bin
./code/.pio/build/esp32cam/bootloader.bin ./code/.pio/build/esp32cam/bootloader.bin
./html/* ./html/*
./demo/*
key: generated-files-${{ github.run_id }} 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 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
@@ -120,7 +137,7 @@ jobs:
path: update path: update
key: update-${{ github.run_id }} 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 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 - name: Set Variables
id: vars id: vars
run: | run: |
@@ -135,6 +152,9 @@ jobs:
- name: Add Web UI to update - name: Add Web UI to update
run: cp -r ./html ./update/ run: cp -r ./html ./update/
- name: Add Demo mode files to update
run: cp -r ./demo ./update/
- name: Add CNN to update - name: Add CNN to update
run: | run: |
@@ -150,7 +170,6 @@ jobs:
path: ./update/* path: ./update/*
######################################################################################### #########################################################################################
## Pack for Remote Setup ## Pack for Remote Setup
######################################################################################### #########################################################################################
@@ -159,6 +178,7 @@ jobs:
# remote_setup__version.zip file with following content: # remote_setup__version.zip file with following content:
# - /firmware.bin # - /firmware.bin
# - /html/* (inkl. subfolders) # - /html/* (inkl. subfolders)
# - /demo/*
# - /config/* # - /config/*
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: build needs: build
@@ -174,9 +194,10 @@ jobs:
./code/.pio/build/esp32cam/partitions.bin ./code/.pio/build/esp32cam/partitions.bin
./code/.pio/build/esp32cam/bootloader.bin ./code/.pio/build/esp32cam/bootloader.bin
./html/* ./html/*
./demo/*
key: generated-files-${{ github.run_id }} 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 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 - name: Update remote_setup cache on every commit
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
@@ -198,6 +219,9 @@ jobs:
- name: Add Web UI to remote_setup - name: Add Web UI to remote_setup
run: cp -r ./html ./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 - name: Add whole config folder to remote_setup
run: | run: |
rm -rf ./remote_setup/config/ rm -rf ./remote_setup/config/
@@ -230,6 +254,7 @@ jobs:
./code/.pio/build/esp32cam/partitions.bin ./code/.pio/build/esp32cam/partitions.bin
./code/.pio/build/esp32cam/bootloader.bin ./code/.pio/build/esp32cam/bootloader.bin
./html/* ./html/*
./demo/*
key: generated-files-${{ github.run_id }} 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 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
@@ -258,10 +283,12 @@ jobs:
cp -f "./code/.pio/build/esp32cam/bootloader.bin" "manual_setup/bootloader.bin" cp -f "./code/.pio/build/esp32cam/bootloader.bin" "manual_setup/bootloader.bin"
cp -f "./code/.pio/build/esp32cam/partitions.bin" "manual_setup/partitions.bin" cp -f "./code/.pio/build/esp32cam/partitions.bin" "manual_setup/partitions.bin"
rm -rf ./sd-card/html 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 ./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 sd-card; zip -r ../manual_setup/sd-card.zip *; cd ..
cd ./manual_setup cd ./manual_setup
- name: Upload manual_setup.zip artifact (Firmware + Bootloader + Partitions + Web UI) - name: Upload manual_setup.zip artifact (Firmware + Bootloader + Partitions + Web UI)
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
@@ -272,7 +299,7 @@ jobs:
######################################################################################### #########################################################################################
## Prepare and create release ## Prepare and create release
######################################################################################### #########################################################################################
release: prepare-release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: [pack-for-update, pack-for-manual_setup, pack-for-remote_setup] needs: [pack-for-update, pack-for-manual_setup, pack-for-remote_setup]
if: startsWith(github.ref, 'refs/tags/') if: startsWith(github.ref, 'refs/tags/')
@@ -285,21 +312,21 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Update update cache on every commit - name: Update update cache on every commit
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
path: update path: update
key: update-${{ github.run_id }} 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 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 - name: Update remote_setup cache on every commit
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
path: remote_setup path: remote_setup
key: remote_setup-${{ github.run_id }} 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 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 - name: Update manual_setup cache on every commit
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
@@ -332,21 +359,18 @@ jobs:
# extract the version used in next step # extract the version used in next step
- id: get_version - id: get_version
if: startsWith(github.ref, 'refs/tags/') uses: drewg13/get-version-action@98dda2a47a257e202c2e6c2ed2e6072ec23f448e
uses: Simply007/get-version-action@v2
# # the changelog [unreleased] will now be changed to the release version # # the changelog [unreleased] will now be changed to the release version
# - name: Update changelog # - name: Update changelog
# uses: thomaseizinger/keep-a-changelog-new-release@v1 # uses: thomaseizinger/keep-a-changelog-new-release@v1
# if: startsWith(github.ref, 'refs/tags/')
# with: # with:
# changelogPath: Changelog.md # changelogPath: Changelog.md
# version: ${{ steps.get_version.outputs.version-without-v }} # version: ${{ steps.get_version.outputs.version-without-v }}
# # the release notes will be extracted from changelog # # the release notes will be extracted from changelog
# - name: Extract release notes # - name: Extract release notes
# id: extract-release-notes # id: extract-release-notes
# if: startsWith(github.ref, 'refs/tags/')
# uses: ffurrer2/extract-release-notes@v1 # uses: ffurrer2/extract-release-notes@v1
# with: # with:
# changelog_file: Changelog.md # changelog_file: Changelog.md
@@ -354,12 +378,11 @@ jobs:
# Releases should only be created on master by tagging the last commit. # Releases should only be created on master by tagging the last commit.
# all artifacts in firmware folder pushed to the release # all artifacts in firmware folder pushed to the release
- name: Release - name: Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v2.0.8
# Note: # Note:
# If you get the error "Resource not accessible by integration", # If you get the error "Resource not accessible by integration",
# The access rights are not sufficient, see # The access rights are not sufficient, see
# https://github.com/softprops/action-gh-release/issues/232#issuecomment-1131379440 # https://github.com/softprops/action-gh-release/issues/232#issuecomment-1131379440
if: startsWith(github.ref, 'refs/tags/')
with: with:
name: ${{ steps.get_version.outputs.version-without-v }} name: ${{ steps.get_version.outputs.version-without-v }}
body: ${{ steps.extract-release-notes.outputs.release_notes }} body: ${{ steps.extract-release-notes.outputs.release_notes }}
@@ -368,7 +391,6 @@ jobs:
# # Commit&Push Changelog to master branch. Must be manually merged back to rolling # # Commit&Push Changelog to master branch. Must be manually merged back to rolling
# - name: Commit changes and push changes # - name: Commit changes and push changes
# if: startsWith(github.ref, 'refs/tags/')
# run: | # run: |
# git config user.name github-actions # git config user.name github-actions
# git config user.email github-actions@github.com # git config user.email github-actions@github.com
@@ -381,8 +403,9 @@ jobs:
## Update the Web Installer on a release ## Update the Web Installer on a release
######################################################################################### #########################################################################################
# Make sure to also update update-webinstaller.yml! # Make sure to also update update-webinstaller.yml!
update-web-installer: update-web-installer:
needs: [release] if: github.event_name == 'release' && github.event.action == 'published' # Only run on release but not on prerelease
needs: [prepare-release]
environment: environment:
name: github-pages name: github-pages
url: ${{ steps.deployment.outputs.page_url }} url: ${{ steps.deployment.outputs.page_url }}
@@ -397,15 +420,16 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Get version of last release - name: Get version of last release
id: last_release id: last_release
uses: mindojo/get-latest-release@0b8ef1434d7468d6bffcc8263baff5c777f72321 uses: joutvhu/get-release@v1
with: with:
myToken: ${{ github.token }} latest: true
exclude_types: "draft|prerelease" prerelease: false
view_top: 1 env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Add binary to Web Installer and update manifest - name: Add binary to Web Installer and update manifest
run: | run: |
echo "Updating Web installer to use firmware from ${{ steps.last_release.outputs.tag_name }}..." echo "Updating Web installer to use firmware from ${{ steps.last_release.outputs.tag_name }}..."

View File

@@ -0,0 +1,21 @@
# 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

@@ -12,7 +12,7 @@ on:
# - rolling # - rolling
# paths: # paths:
# - docs # The path filter somehow does not work, so lets run it on every change to rolling # - docs # The path filter somehow does not work, so lets run it on every change to rolling
jobs: jobs:
manually-update-web-installer: manually-update-web-installer:
environment: environment:
@@ -32,12 +32,13 @@ jobs:
- name: Get version of last release - name: Get version of last release
id: last_release id: last_release
uses: mindojo/get-latest-release@0b8ef1434d7468d6bffcc8263baff5c777f72321 uses: joutvhu/get-release@v1
with: with:
myToken: ${{ github.token }} latest: true
exclude_types: "draft|prerelease" prerelease: false
view_top: 1 env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Add binary to Web Installer and update manifest - name: Add binary to Web Installer and update manifest
run: | run: |
echo "Updating Web installer to use firmware from ${{ steps.last_release.outputs.tag_name }}..." echo "Updating Web installer to use firmware from ${{ steps.last_release.outputs.tag_name }}..."
@@ -50,14 +51,13 @@ jobs:
sed -i 's/$VERSION/${{ steps.last_release.outputs.tag_name }}/g' docs/manifest.json sed -i 's/$VERSION/${{ steps.last_release.outputs.tag_name }}/g' docs/manifest.json
- name: Setup Pages - name: Setup Pages
uses: actions/configure-pages@v2 uses: actions/configure-pages@v5
- name: Upload artifact - name: Upload artifact
uses: actions/upload-pages-artifact@v1 uses: actions/upload-pages-artifact@v3
with: with:
path: 'docs' path: 'docs'
- name: Deploy to GitHub Pages - name: Deploy to GitHub Pages
id: deployment id: deployment
uses: actions/deploy-pages@v1 uses: actions/deploy-pages@v4

View File

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

3
.gitmodules vendored
View File

@@ -10,3 +10,6 @@
[submodule "code/components/stb"] [submodule "code/components/stb"]
path = code/components/stb path = code/components/stb
url = https://github.com/nothings/stb.git url = https://github.com/nothings/stb.git
[submodule "code/components/esp-protocols"]
path = code/components/esp-protocols
url = https://github.com/espressif/esp-protocols.git

View File

@@ -1,3 +1,154 @@
## [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 ## [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) 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)
@@ -14,7 +165,7 @@ For a full list of changes see [Full list of changes](https://github.com/jomjol/
- Update PlattformIO to v6.5.0, which means esp-idf to v5.1 - Update PlattformIO to v6.5.0, which means esp-idf to v5.1
- Enhance busy notification - Enhance busy notification
- Implemented late analog / digital transition - Implemented late analog / digit transition
#### Fixed #### Fixed
@@ -42,6 +193,8 @@ For a full list of changes see [Full list of changes](https://github.com/jomjol/
- dig-class100-0167_s2_q.tflite - dig-class100-0167_s2_q.tflite
- dig-class11_1700_s2.tflite - dig-class11_1700_s2.tflite
- ana-cont_1208_s2_q.tflite - ana-cont_1208_s2_q.tflite
- Added config entries for MQTT TLS
#### Fixed #### Fixed
@@ -172,7 +325,7 @@ For a full list of changes see [Full list of changes](https://github.com/jomjol/
:bangbang: **Attention:** Update your configuration! :bangbang: **Attention:** Update your configuration!
- Hybrid CNN network to `dig-cont_0611_s3` - Hybrid CNN network to `dig-cont_0611_s3`
- Analog CNN network to `ana-cont-11.0.5` and `ana-clas100-1.5.7` - Analog CNN network to `ana-cont-11.0.5` and `ana-clas100-1.5.7`
- Digital CNN network to `dig-class100-1.6.0` - Digit CNN network to `dig-class100-1.6.0`
- Various Web interface Improvements/Enhancements: - Various Web interface Improvements/Enhancements:
- Restructured Menu (Needs cache clearing to be applied) - Restructured Menu (Needs cache clearing to be applied)
- Enhanced `Previous Value` page - Enhanced `Previous Value` page
@@ -308,7 +461,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) - 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 - Added data logging in `/log/data` - One day per file and each measurement is on one line
- Format: csv - comma separated - Format: csv - comma separated
- Content: `time`, `name-of-number`, `raw-value`, `return-value`, `pre-value`, `change-rate`, `change-absolute`, `error-text`, `cnn-digital`, `cnn-analog` - Content: `time`, `name-of-number`, `raw-value`, `return-value`, `pre-value`, `change-rate`, `change-absolute`, `error-text`, `cnn-digit`, `cnn-analog`
- Show graph of values direct in the user interface (thanks to [@rdmueller](https://github.com/rdmueller)) - Show graph of values direct in the user interface (thanks to [@rdmueller](https://github.com/rdmueller))
- Using new data logging (see above) - Using new data logging (see above)
@@ -326,10 +479,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 OTA functionality (more robust, but not fully bullet prove yet)
- Updated Espressif library to `espressif32@v5.2.0` - 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 - [#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 `AnalogDigitalTransitionStart`. 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 `AnalogDigTransitionStart`. 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 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: Update Tool "Logfile downloader and combiner" to handle the new csv file format.
- NEW v13.0.2: MQTT: Added MQTT topic `status` (Digitalization Status), Timezone to MQTT topic `timestamp`.# - NEW v13.0.2: MQTT: Added MQTT topic `status` (Digitization Status), Timezone to MQTT topic `timestamp`.#
- NEW v13.0.2: Logging: Disable heap logs by default, cleanup - NEW v13.0.2: Logging: Disable heap logs by default, cleanup
- NEW v13.0.7: - NEW v13.0.7:
- log NTP server name - log NTP server name
@@ -454,7 +607,7 @@ Intermediate Digits
- Updated analog neural network file (`ana-cont_11.3.0_s2.tflite` - default, `ana-class100_0120_s1_q.tflite`) - Updated analog neural network file (`ana-cont_11.3.0_s2.tflite` - default, `ana-class100_0120_s1_q.tflite`)
- Updated digital neural network file (`dig-cont_0570_s3.tflite` - default, `dig-class100_0120_s2_q.tflite`) - Updated digit 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)**) - Added automated filtering of tflite-file in the graphical configuration (thanks to @**[caco3](https://github.com/caco3)**)
@@ -466,8 +619,8 @@ Intermediate Digits
Intermediate Digits Intermediate Digits
- New and improved consistency check (especially with analog and digital counters mixed) - New and improved consistency check (especially with analog and digit counters mixed)
- Bug Fix: digital counter algorithm - Bug Fix: digit counter algorithm
## [11.0.1](https://github.com/jomjol/AI-on-the-edge-device/releases/tag/v11.0.1), 2022-08-18 ## [11.0.1](https://github.com/jomjol/AI-on-the-edge-device/releases/tag/v11.0.1), 2022-08-18
@@ -478,16 +631,16 @@ Intermediate Digits
- Implementation of new CNN types to detect intermediate values of digits with rolling numbers - 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) - 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 selection a tflite file with the new trained model in the 'config.ini' - Activation can be done by selecting 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) - **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 adaption to new naming convention) - Updated neural network files (and adaptation to new naming convention)
- Published a tool to download and combine log files - **Thanks to ** - Published a tool to download and combine log files - Thanks to [Contributor]
- Files see ['/tools/logfile-tool'](tbd), How-to see [wiki](https://github.com/jomjol/AI-on-the-edge-device/wiki/Gasmeter-Log-Downloader) - 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 grahic configuration - Bug Fix: InfluxDB enabling in graphic configuration
## [10.6.2](https://github.com/jomjol/AI-on-the-edge-device/releases/tag/v10.6.2), 2022-07-24 ## [10.6.2](https://github.com/jomjol/AI-on-the-edge-device/releases/tag/v10.6.2), 2022-07-24
@@ -501,13 +654,13 @@ Stability Increase
- **NEW 10.6.1**: Bug Fix: tflite-filename with ".", HTML spelling error - **NEW 10.6.1**: Bug Fix: tflite-filename with ".", HTML spelling error
- IndluxDB: direct injection into InfluxDB - thanks to **[wetneb](https://github.com/wetneb)** - InfluxDB: direct injection into InfluxDB - thanks to **[wetneb](https://github.com/wetneb)**
- MQTT: implemented "Retain Flag" and extend with absolute Change (in addition to rate) - MQTT: implemented "Retain Flag" and extend with absolute Change (in addition to rate)
- `config.ini`: removal of modelsize (readout from tflite) - `config.ini`: removal of modelsize (readout from tflite)
- Updated analog neural network file (`ana1000s2.tflite`) & digital neural network file (`dig1400s2q.tflite`) - Updated analog neural network file (`ana1000s2.tflite`) & digit neural network file (`dig1400s2q.tflite`)
- TFMicro/Lite: Update (espressif Version 20220716) - TFMicro/Lite: Update (espressif Version 20220716)
@@ -543,7 +696,7 @@ Stability Increase
- In the future the new files will also be copied to the `firmware` directory of the repository - In the future the new files will also be copied to the `firmware` directory of the repository
- Added Wifi RSSI to MQTT information - Added Wifi RSSI to MQTT information
- Updated analog neural network file (`ana-s3-q-20220105.tflite`) - Updated analog neural network file (`ana-s3-q-20220105.tflite`)
- Updated digital neural network file (`dig-s1-q-20220102.tflite`) - Updated digit neural network file (`dig-s1-q-20220102.tflite`)
- Updated build environment to `Espressif 3.5.0` - Updated build environment to `Espressif 3.5.0`
## [10.3.0] - (2022-01-29) ## [10.3.0] - (2022-01-29)
@@ -609,7 +762,7 @@ Stability Increase
- Update analog neural network (ana-s3-q-20220105.tflite) - Update analog neural network (ana-s3-q-20220105.tflite)
- Update digital neural network (dig-s1-q-20220102.tflite) - Update digit neural network (dig-s1-q-20220102.tflite)
- Increased web-server buffers - Increased web-server buffers
@@ -646,7 +799,7 @@ External Illumination
- Direct JSON access: `http://IP-ADRESS/json` - Direct JSON access: `http://IP-ADRESS/json`
- Error message in log file in case camera error during startup - Error message in log file in case camera error during startup
- Upgrade analog CNN to v9.1.0 - Upgrade analog CNN to v9.1.0
- Upgrade digital CNN to v13.3.0 (added new images) - Upgrade digit CNN to v13.3.0 (added new images)
- html: support of different ports - html: support of different ports
## [9.1.1] - External Illumination (2021-11-16) ## [9.1.1] - External Illumination (2021-11-16)
@@ -671,7 +824,7 @@ External Illumination
### Changed ### Changed
- Upgrade digital CNN to v13.1.0 (added new images) - Upgrade digit CNN to v13.1.0 (added new images)
- bug fix: wlan password with space, double digit output - bug fix: wlan password with space, double digit output
## [8.4.0] - Multi Meter Support (2021-09-25) ## [8.4.0] - Multi Meter Support (2021-09-25)
@@ -701,7 +854,7 @@ External Illumination
### Changed ### Changed
- Upgrade digital CNN to v12.1.0 (added new images) - Upgrade digit CNN to v12.1.0 (added new images)
- Dedicated NaN handling, internal refactoring (CNN-Handling) - Dedicated NaN handling, internal refactoring (CNN-Handling)
- HTML: confirmation after config.ini update - HTML: confirmation after config.ini update
- Bug fixing - Bug fixing
@@ -723,7 +876,7 @@ External Illumination
- GPIO: using the general mqtt main topic for GPIO - GPIO: using the general mqtt main topic for GPIO
- Upgrade digital CNN to v12.0.0 (added new images) - Upgrade digit CNN to v12.0.0 (added new images)
- Update tfmicro to new master (2021-08-07) - Update tfmicro to new master (2021-08-07)
- Bug fix: remove text in mqtt value, remove connect limit in wlan reconnet - Bug fix: remove text in mqtt value, remove connect limit in wlan reconnet
@@ -759,7 +912,7 @@ External Illumination
- Update wlan handling to esp-idf 4.1 - Update wlan handling to esp-idf 4.1
- Upgrade digital CNN to v8.7.0 (added new images) - Upgrade digit CNN to v8.7.0 (added new images)
- Bug fix: MQTT, WLAN, LED-Controll, GPIO usage, fixed IP, calculation flow rate - Bug fix: MQTT, WLAN, LED-Controll, GPIO usage, fixed IP, calculation flow rate
@@ -770,7 +923,7 @@ External Illumination
- NEW: 7.0.1: bug fix wlan password with "=" - NEW: 7.0.1: bug fix wlan password with "="
- Upgrade digital CNN to v8.5.0 (added new images) - Upgrade digit CNN to v8.5.0 (added new images)
- New MQTT topics: flow rate (units/minute), time stamp (last correct read readout) - New MQTT topics: flow rate (units/minute), time stamp (last correct read readout)
@@ -787,7 +940,7 @@ External Illumination
- NEW 6.7.1: Improved stability of camera (back to v6.6.1) - remove black strips and areas - NEW 6.7.1: Improved stability of camera (back to v6.6.1) - remove black strips and areas
- Upgrade digital CNN to v8.3.0 (added new type of digits) - Upgrade digit CNN to v8.3.0 (added new type of digits)
- Internal update: TFlite (v2.5), esp32cam, startup sequence - Internal update: TFlite (v2.5), esp32cam, startup sequence
@@ -808,7 +961,7 @@ External Illumination
### Changed ### Changed
- Upgrade digital CNN to v8.2.0 (added new type of digits) - Upgrade digit CNN to v8.2.0 (added new type of digits)
- Supporting alignment structures in ROI definition - Supporting alignment structures in ROI definition
@@ -844,7 +997,7 @@ External Illumination
- Determination of fixed illumination settings during startup - speed up of 5s in each run - Determination of fixed illumination settings during startup - speed up of 5s in each run
- Update digital CNN to v8.1.1 (additional digital images trained) - Update digit CNN to v8.1.1 (additional digit images trained)
- Extended error message in MQTT error message - Extended error message in MQTT error message
@@ -856,7 +1009,7 @@ External Illumination
### Changed ### Changed
- Disabling of analog / digital counters in configuration - Disabling of analog / digit counters in configuration
- Improved Alignment Algorithm (`AlignmentAlgo` = `Default`, `Accurate` , `Fast`) - Improved Alignment Algorithm (`AlignmentAlgo` = `Default`, `Accurate` , `Fast`)
@@ -876,7 +1029,7 @@ External Illumination
- MQTT: Last Will Testament (LWT) implemented: "connection lost" in case of connection lost to `TopicError` - 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 - Disabled `CheckDigitIncreaseConsistency` in default configuration - must now be explicit enabled if needed
- Update digital CNN to v7.2.1 (additional digital images trained) - Update digit CNN to v7.2.1 (additional digit images trained)
- Setting of arbitrary time server in `config.ini` - Setting of arbitrary time server in `config.ini`
- Option for fixed IP-, DNS-Settings in `wlan.ini` - Option for fixed IP-, DNS-Settings in `wlan.ini`
- Increased stability (internal image and camera handling) - Increased stability (internal image and camera handling)
@@ -910,7 +1063,7 @@ External Illumination
- standardized access to current logfile via `http://IP-ADRESS/logfileact` - standardized access to current logfile via `http://IP-ADRESS/logfileact`
- Update digital CNN to v7.2.0, analog CNN to 6.3.0 - Update digit CNN to v7.2.0, analog CNN to 6.3.0
- Bug fixing: truncation error, CheckDigitConsistency & PreValue implementation - Bug fixing: truncation error, CheckDigitConsistency & PreValue implementation
@@ -929,7 +1082,7 @@ External Illumination
### Changed ### Changed
- Update digital CNN to v6.5.0 and HTML (Info to hostname, IP, ssid) - Update digit CNN to v6.5.0 and HTML (Info to hostname, IP, ssid)
- New implementation of "checkDigitConsistency" also for digits - New implementation of "checkDigitConsistency" also for digits
@@ -1016,7 +1169,7 @@ External Illumination
- Bug in configuration of analog ROIs corrected - Bug in configuration of analog ROIs corrected
- minor bug correction - minor Bug correction
## [1.0.1](2020-09-05) ## [1.0.1](2020-09-05)
@@ -1025,7 +1178,7 @@ External Illumination
- preValue.ini Bug corrected - preValue.ini Bug corrected
- minor bug correction - minor Bug correction
## [1.0.0](2020-09-04) ## [1.0.0](2020-09-04)

View File

@@ -40,16 +40,16 @@ ____
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...). 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 #### #35 Use the same model, but provide the image from a Smartphone Camera
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. 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.
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. 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 #### #34 implement state and Roi for water leak detection
for example see Roi on the next picture.. for example see Roi in the next picture..
![grafik](https://user-images.githubusercontent.com/38385805/207858812-2a6ba41d-1a8c-4fa1-9b6a-53cdd113c106.png) ![grafik](https://user-images.githubusercontent.com/38385805/207858812-2a6ba41d-1a8c-4fa1-9b6a-53cdd113c106.png)
in case of position change between the measurments set this state to true, if there is no change set it back to false. in case of position change between the measurements 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.. In a defined time window this movement can lead into an alarm state / water leak..
haveing this state in the mqtt broker can trigger functions like closing the ater pipe walve and so on... having this state in the mqtt broker can trigger functions like closing the water pipe valve and so on...
@@ -65,7 +65,7 @@ haveing this state in the mqtt broker can trigger functions like closing the ate
#### #31 Implement InfluxDB v2.x interface #### #31 Implement InfluxDB v2.x interface
* Currently only InfluxDB v1.x is supportet, extend to v2.x * Currently only InfluxDB v1.x is supported, extend to v2.x
* Remark: interface has changed * Remark: interface has changed
* see [#1160](https://github.com/jomjol/AI-on-the-edge-device/issues/1160) * see [#1160](https://github.com/jomjol/AI-on-the-edge-device/issues/1160)
@@ -82,7 +82,7 @@ haveing this state in the mqtt broker can trigger functions like closing the ate
#### #28 Improved error handling for ROIs #### #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 * 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 configuratioin of ROI * Implement a error message for wrong configuration of ROI
#### #27 Use Homie Spec for Mqtt binding #### #27 Use Homie Spec for Mqtt binding

68
Licence.md Normal file
View File

@@ -0,0 +1,68 @@
# **Dual Use License for AI-on-the-Edge Device**
Version: 1.0
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.

721
README.md
View File

@@ -1,108 +1,667 @@
# Welcome to the AI-on-the-edge-device <h1 align="center">AI on the Edge Device: Digitizing Your non-digital meters with an ESP32-CAM</h1>
<img src="images/icon/watermeter.svg" width="100px"> <br>
<br>
Artificial intelligence based systems have become established in our everyday lives. Just think of speech or image recognition. Most of the systems rely on either powerful processors or a direct connection to the cloud for doing the calculations there. With the increasing power of modern processors, the AI systems are coming closer to the end user which is usually called **edge computing**. ## Table of Contents
Here, this edge computing is put into a practically oriented example, where an AI network is implemented on an ESP32 device so: **AI on the edge**. - [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)
This project allows you to digitize your **analog** water, gas, power and other meters using cheap and easily available hardware. <p align="center">
<a href="#top">
All you need is an [ESP32 board with a supported camera](https://jomjol.github.io/AI-on-the-edge-device-docs/Hardware-Compatibility/) and something of a practical hand. <img src="https://img.shields.io/badge/Back%20to%20Top-000000?style=for-the-badge&logo=github&logoColor=white" alt="Back to Top">
</a>
<img src="images/esp32-cam.png" width="200px"> </p>
## Key features
- Tensorflow Lite (TFlite) integration including easy-to-use wrapper
- Inline image processing (feature detection, alignment, ROI extraction)
- **Small** and **cheap** device (3 x 4.5 x 2 cm³, < 10 EUR)
- Integrated camera and illumination
- Web interface for administration and control
- OTA interface for updating directly via the web interface
- Full integration into Homeassistant
- Support for Influx DB 1 and 2
- MQTT
- REST API
## Workflow
The device takes a photo of your meter at a defined interval. 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. Either send it to an MQTT broker, write it to an InfluxDb or simply provide access to it via 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 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 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 created useful Youtube videos which might help you getting started. [![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)
Here a small selection: [![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/)
- [youtube.com/watch?v=HKBofb1cnNc](https://www.youtube.com/watch?v=HKBofb1cnNc) <p align="center" id="top">
- [youtube.com/watch?v=yyf0ORNLCk4](https://www.youtube.com/watch?v=yyf0ORNLCk4) <img src="images/icon/watermeter.svg" width="150px">
- [youtube.com/watch?v=XxmTubGek6M](https://www.youtube.com/watch?v=XxmTubGek6M) </p>
- [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) and [Programming on the ESP32](https://www.heise.de/select/make/2022/2/2204010051597422030). 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.
### Download 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). The latest available version can be found on the [Releases page](https://github.com/jomjol/AI-on-the-edge-device/releases).
### 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 WIFI).
<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).
There are different ways to flash your ESP32: There are different ways to flash your ESP32:
- The prefered way is the [Web Installer and Console](https://jomjol.github.io/AI-on-the-edge-device/index.html) which is a browser-based tool to flash the ESP32 and extract the log over USB: - 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) ![](images/web-installer.png)
- Flash Tool from Espressif - 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 [documentation](https://jomjol.github.io/AI-on-the-edge-device-docs/Installation/) for more information.
### Flashing the SD Card ---
The SD card can be setup automatically after the firmware got 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 formated (which is the default on a new SD card).
Alternatively the SD card still can be setup manually, see the [documentation](https://jomjol.github.io/AI-on-the-edge-device-docs/Installation/#3-sd-card) for details!
## Casing <br>
Various 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)
## Donate ## Flashing the SD Card 💾
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). 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 href="https://www.paypal.com/donate?hosted_button_id=8TRSVYNYKDSWL"><img border="0" src="images/paypal.png" width="200px" target="_blank"></a> 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.
## Support ---
If you have any technical problems please search the [discussions](https://github.com/jomjol/AI-on-the-edge-device/discussions). In case you found a ug or have a feature request, please open an [issue](https://github.com/jomjol/AI-on-the-edge-device/issues).
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"> <br>
## Changes and History ## Casing 🛠️
See [Changelog](Changelog.md). 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)
## Build It Yourself ---
See [Build Instructions](code/README.md).
## Tools <br>
* Logfile downloader and combiner (Thx to [reserve85](https://github.com/reserve85))
* Files see ['/tools/logfile-tool'](tbd), how-to see [documentation](https://jomjol.github.io/AI-on-the-edge-device-docs/outdated--Gasmeter-Log-Downloader/)
## Additional Ideas ## Donate ☕
There are some ideas and feature requests which are not currently being pursued mainly due to capacity reasons on the part of the developers. 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).
They features are collected in the [issues](https://github.com/jomjol/AI-on-the-edge-device/issues) and in [FeatureRequest.md](FeatureRequest.md).
<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>
---
<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>

View File

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

View File

@@ -1,27 +1,53 @@
/********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#include "Color.h" #include "Color.h"
#include <algorithm> #include <algorithm>
#include <cmath>
#include <cassert> #include <cassert>
#include <cmath>
namespace { namespace {
// Int -> fixed point // Int -> fixed point
int up( int x ) { return x * 255; } int up(int x) { return x * 255; }
} // namespace } // namespace
int iRgbSqrt( int num ) { int iRgbSqrt(int num) {
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29 // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29
assert( "sqrt input should be non-negative" && num >= 0 ); assert("sqrt input should be non-negative" && num >= 0);
assert( "sqrt input should no exceed 16 bits" && num <= 0xFFFF ); assert("sqrt input should no exceed 16 bits" && num <= 0xFFFF);
int res = 0; int res = 0;
int bit = 1 << 16; int bit = 1 << 16;
while ( bit > num ) while (bit > num)
bit >>= 2; bit >>= 2;
while ( bit != 0 ) { while (bit != 0) {
if ( num >= res + bit ) { if (num >= res + bit) {
num -= res + bit; num -= res + bit;
res = ( res >> 1 ) + bit; res = (res >> 1) + bit;
} else } else
res >>= 1; res >>= 1;
bit >>= 2; bit >>= 2;
@@ -29,104 +55,133 @@ int iRgbSqrt( int num ) {
return res; return res;
} }
Rgb::Rgb( Hsv y ) { Rgb::Rgb(const Hsv& y) {
// https://stackoverflow.com/questions/24152553/hsv-to-rgb-and-back-without-floating-point-math-in-python // https://stackoverflow.com/questions/24152553/hsv-to-rgb-and-back-without-floating-point-math-in-python
// greyscale // greyscale
if( y.s == 0 ) { if (y.s == 0) {
r = g = b = y.v; r = g = b = y.v;
return; return;
} }
const int region = y.h / 43; const int region = y.h / 43;
const int remainder = ( y.h - ( region * 43 ) ) * 6; const int remainder = (y.h - (region * 43)) * 6;
const int p = ( y.v * ( 255 - y.s ) ) >> 8; const int p = (y.v * (255 - y.s)) >> 8;
const int q = ( y.v * ( 255 - ( ( y.s * remainder ) >> 8 ) ) ) >> 8; const int q = (y.v * (255 - ((y.s * remainder) >> 8))) >> 8;
const int t = ( y.v * ( 255 - ( ( y.s * (255 -remainder ) ) >> 8 ) ) ) >> 8; const int t = (y.v * (255 - ((y.s * (255 - remainder)) >> 8))) >> 8;
switch( region ) { switch (region) {
case 0: r = y.v; g = t; b = p; break; case 0:
case 1: r = q; g = y.v; b = p; break; r = y.v;
case 2: r = p; g = y.v; b = t; break; g = t;
case 3: r = p; g = q; b = y.v; break; b = p;
case 4: r = t; g = p; b = y.v; break; break;
case 5: r = y.v; g = p; b = q; break; case 1:
default: __builtin_trap(); r = q;
g = y.v;
b = p;
break;
case 2:
r = p;
g = y.v;
b = t;
break;
case 3:
r = p;
g = q;
b = y.v;
break;
case 4:
r = t;
g = p;
b = y.v;
break;
case 5:
r = y.v;
g = p;
b = q;
break;
default:
__builtin_trap();
} }
a = y.a; a = y.a;
} }
Rgb& Rgb::operator=( Hsv hsv ) { Rgb& Rgb::operator=(const Hsv& hsv) {
Rgb r{ hsv }; Rgb r { hsv };
swap( r ); swap(r);
return *this; return *this;
} }
Rgb Rgb::operator+( Rgb in ) const { Rgb Rgb::operator+(const Rgb& in) const {
auto copy = *this; auto copy = *this;
copy += in; copy += in;
return copy; return copy;
} }
Rgb& Rgb::operator+=( Rgb in ) { Rgb& Rgb::operator+=(const Rgb& in) {
unsigned int red = r + in.r; unsigned int red = r + in.r;
r = ( red < 255 ) ? red : 255; r = (red < 255) ? red : 255;
unsigned int green = g + in.g; unsigned int green = g + in.g;
g = ( green < 255 ) ? green : 255; g = (green < 255) ? green : 255;
unsigned int blue = b + in.b; unsigned int blue = b + in.b;
b = ( blue < 255 ) ? blue : 255; b = (blue < 255) ? blue : 255;
return *this; return *this;
} }
Rgb& Rgb::blend( Rgb in ) { Rgb Rgb::operator-(const Rgb& in) const {
unsigned int inAlpha = in.a * ( 255 - a ); auto copy = *this;
copy -= in;
return copy;
}
Rgb& Rgb::operator-=(const Rgb& in) {
r = (in.r > r) ? 0 : r - in.r;
g = (in.g > g) ? 0 : g - in.g;
b = (in.b > b) ? 0 : b - in.b;
return *this;
}
Rgb& Rgb::blend(const Rgb& in) {
unsigned int inAlpha = in.a * (255 - a);
unsigned int alpha = a + inAlpha; unsigned int alpha = a + inAlpha;
r = iRgbSqrt( ( ( r * r * a ) + ( in.r * in.r * inAlpha ) ) / alpha ); r = iRgbSqrt(((r * r * a) + (in.r * in.r * inAlpha)) / alpha);
g = iRgbSqrt( ( ( g * g * a ) + ( in.g * in.g * inAlpha ) ) / alpha ); g = iRgbSqrt(((g * g * a) + (in.g * in.g * inAlpha)) / alpha);
b = iRgbSqrt( ( ( b * b * a ) + ( in.b * in.b * inAlpha ) ) / alpha ); b = iRgbSqrt(((b * b * a) + (in.b * in.b * inAlpha)) / alpha);
a = alpha; a = alpha;
return *this; return *this;
} }
uint8_t IRAM_ATTR Rgb::getGrb( int idx ) { Hsv::Hsv(const Rgb& r) {
switch ( idx ) { int min = std::min(r.r, std::min(r.g, r.b));
case 0: return g; int max = std::max(r.r, std::max(r.g, r.b));
case 1: return r;
case 2: return b;
}
__builtin_unreachable();
}
Hsv::Hsv( Rgb r ) {
int min = std::min( r.r, std::min( r.g, r.b ) );
int max = std::max( r.r, std::max( r.g, r.b ) );
int chroma = max - min; int chroma = max - min;
v = max; v = max;
if ( chroma == 0 ) { if (chroma == 0) {
h = s = 0; h = s = 0;
return; return;
} }
s = up( chroma ) / max; s = up(chroma) / max;
int hh; int hh;
if ( max == r.r ) if (max == r.r)
hh = ( up( int( r.g ) - int( r.b ) ) ) / chroma / 6; hh = (up(int(r.g) - int(r.b))) / chroma / 6;
else if ( max == r.g ) else if (max == r.g)
hh = 255 / 3 + ( up( int( r.b ) - int( r.r ) ) ) / chroma / 6; hh = 255 / 3 + (up(int(r.b) - int(r.r))) / chroma / 6;
else else
hh = 2 * 255 / 3 + ( up( int( r.r ) - int( r.g ) ) ) / chroma / 6; hh = 2 * 255 / 3 + (up(int(r.r) - int(r.g))) / chroma / 6;
if ( hh < 0 ) if (hh < 0)
hh += 255; hh += 255;
h = hh; h = hh;
a = r.a; a = r.a;
} }
Hsv& Hsv::operator=( Rgb rgb ) { Hsv& Hsv::operator=(const Rgb& rgb) {
Hsv h{ rgb }; Hsv h { rgb };
swap( h ); swap(h);
return *this; return *this;
} }

View File

@@ -1,51 +1,90 @@
/********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#pragma once #pragma once
#ifndef COLOR_H
#define COLOR_H
#include <cstdint>
#include "esp_attr.h" #include "esp_attr.h"
#include <cstdint>
union Hsv; union Hsv;
union Rgb { union Rgb {
struct __attribute__ ((packed)) { struct __attribute__((packed)) {
uint8_t r, g, b, a; uint8_t g, r, b, a;
}; };
uint32_t value; uint32_t value;
Rgb( uint8_t r = 0, uint8_t g = 0, uint8_t b = 0, uint8_t a = 255 ) : r( r ), g( g ), b( b ), a( a ) {} Rgb(uint8_t r = 0, uint8_t g = 0, uint8_t b = 0, uint8_t a = 255)
Rgb( Hsv c ); : g(g)
Rgb& operator=( Rgb rgb ) { swap( rgb ); return *this; } , r(r)
Rgb& operator=( Hsv hsv ); , b(b)
Rgb operator+( Rgb in ) const; , a(a) {}
Rgb& operator+=( Rgb in ); Rgb(const Hsv& c);
bool operator==( Rgb in ) const { return in.value == value; } Rgb(const Rgb&) = default;
Rgb& blend( Rgb in ); Rgb& operator=(const Rgb& rgb) {
void swap( Rgb& o ) { value = o.value; } swap(rgb);
return *this;
}
Rgb& operator=(const Hsv& hsv);
Rgb operator+(const Rgb& in) const;
Rgb& operator+=(const Rgb& in);
Rgb operator-(const Rgb& in) const;
Rgb& operator-=(const Rgb& in);
bool operator==(const Rgb& in) const { return in.value == value; }
Rgb& blend(const Rgb& in);
void swap(const Rgb& o) { value = o.value; }
void linearize() { void linearize() {
r = channelGamma(r); r = channelGamma(r);
g = channelGamma(g); g = channelGamma(g);
b = channelGamma(b); b = channelGamma(b);
} }
uint8_t IRAM_ATTR getGrb( int idx ); inline uint8_t IRAM_ATTR getGrb(int idx) {
switch (idx) {
void stretchChannels( uint8_t maxR, uint8_t maxG, uint8_t maxB ) { case 0:
r = stretch( r, maxR ); return g;
g = stretch( g, maxG ); case 1:
b = stretch( b, maxB ); return r;
case 2:
return b;
}
__builtin_unreachable();
} }
void stretchChannelsEvenly( uint8_t max ) { void stretchChannels(uint8_t maxR, uint8_t maxG, uint8_t maxB) {
stretchChannels( max, max, max ); r = stretch(r, maxR);
g = stretch(g, maxG);
b = stretch(b, maxB);
} }
void stretchChannelsEvenly(uint8_t max) { stretchChannels(max, max, max); }
private: private:
uint8_t stretch( int value, uint8_t max ) { uint8_t stretch(int value, uint8_t max) { return (value * max) >> 8; }
return ( value * max ) >> 8;
}
uint8_t channelGamma( int channel ) { uint8_t channelGamma(int channel) {
/* The optimal gamma correction is x^2.8. However, this is expensive to /* The optimal gamma correction is x^2.8. However, this is expensive to
* compute. Therefore, we use x^3 for gamma correction. Also, we add a * compute. Therefore, we use x^3 for gamma correction. Also, we add a
* bias as the WS2812 LEDs do not turn on for values less than 4. */ * bias as the WS2812 LEDs do not turn on for values less than 4. */
@@ -53,22 +92,27 @@ private:
return channel; return channel;
channel = channel * channel * channel * 251; channel = channel * channel * channel * 251;
channel >>= 24; channel >>= 24;
return static_cast< uint8_t >( 4 + channel ); return static_cast<uint8_t>(4 + channel);
} }
}; };
union Hsv { union Hsv {
struct __attribute__ ((packed)) { struct __attribute__((packed)) {
uint8_t h, s, v, a; uint8_t h, s, v, a;
}; };
uint32_t value; uint32_t value;
Hsv( uint8_t h, uint8_t s = 0, uint8_t v = 0, uint8_t a = 255 ) : h( h ), s( s ), v( v ), a( a ) {} Hsv(uint8_t h, uint8_t s = 0, uint8_t v = 0, uint8_t a = 255)
Hsv( Rgb r ); : h(h)
Hsv& operator=( Hsv h ) { swap( h ); return *this; } , s(s)
Hsv& operator=( Rgb rgb ); , v(v)
bool operator==( Hsv in ) const { return in.value == value; } , a(a) {}
void swap( Hsv& o ) { value = o.value; } Hsv(const Rgb& r);
Hsv& operator=(const Hsv& h) {
swap(h);
return *this;
}
Hsv& operator=(const Rgb& rgb);
bool operator==(const Hsv& in) const { return in.value == value; }
void swap(const Hsv& o) { value = o.value; }
}; };
#endif //COLOR_H

View File

@@ -0,0 +1,60 @@
/********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#pragma once
#include <esp_system.h>
#include <stdint.h>
#if defined(ESP_IDF_VERSION)
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
#define SMARTLEDS_NEW_RMT_DRIVER 1
#else
#define SMARTLEDS_NEW_RMT_DRIVER 0
#endif
#else
#define SMARTLEDS_NEW_RMT_DRIVER 0
#endif
namespace detail {
struct TimingParams {
uint32_t T0H;
uint32_t T1H;
uint32_t T0L;
uint32_t T1L;
uint32_t TRS;
};
using LedType = TimingParams;
} // namespace detail
#if SMARTLEDS_NEW_RMT_DRIVER
#include "RmtDriver5.h"
#else
#include "RmtDriver4.h"
#endif

View File

@@ -0,0 +1,143 @@
/********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#include "RmtDriver4.h"
#if !SMARTLEDS_NEW_RMT_DRIVER
#include "SmartLeds.h"
namespace detail {
// 8 still seems to work, but timings become marginal
static const int DIVIDER = 4;
// minimum time of a single RMT duration based on clock ns
static const double RMT_DURATION_NS = 12.5;
RmtDriver::RmtDriver(const LedType& timing, int count, int pin, int channel_num, SemaphoreHandle_t finishedFlag)
: _timing(timing)
, _count(count)
, _pin((gpio_num_t)pin)
, _finishedFlag(finishedFlag)
, _channel((rmt_channel_t)channel_num) {
_bitToRmt[0].level0 = 1;
_bitToRmt[0].level1 = 0;
_bitToRmt[0].duration0 = _timing.T0H / (RMT_DURATION_NS * DIVIDER);
_bitToRmt[0].duration1 = _timing.T0L / (RMT_DURATION_NS * DIVIDER);
_bitToRmt[1].level0 = 1;
_bitToRmt[1].level1 = 0;
_bitToRmt[1].duration0 = _timing.T1H / (RMT_DURATION_NS * DIVIDER);
_bitToRmt[1].duration1 = _timing.T1L / (RMT_DURATION_NS * DIVIDER);
}
esp_err_t RmtDriver::init() {
rmt_config_t config = RMT_DEFAULT_CONFIG_TX(_pin, _channel);
config.rmt_mode = RMT_MODE_TX;
config.clk_div = DIVIDER;
config.mem_block_num = 1;
return rmt_config(&config);
}
esp_err_t RmtDriver::registerIsr(bool isFirstRegisteredChannel) {
auto err = rmt_driver_install(_channel, 0,
#if defined(CONFIG_RMT_ISR_IRAM_SAFE)
ESP_INTR_FLAG_IRAM
#else
0
#endif
);
if (err != ESP_OK) {
return err;
}
if (isFirstRegisteredChannel) {
rmt_register_tx_end_callback(txEndCallback, NULL);
}
err = rmt_translator_init(_channel, translateSample);
if (err != ESP_OK) {
return err;
}
return rmt_translator_set_context(_channel, this);
}
esp_err_t RmtDriver::unregisterIsr() { return rmt_driver_uninstall(_channel); }
void IRAM_ATTR RmtDriver::txEndCallback(rmt_channel_t channel, void* arg) {
xSemaphoreGiveFromISR(SmartLed::ledForChannel(channel)->_finishedFlag, nullptr);
}
void IRAM_ATTR RmtDriver::translateSample(const void* src, rmt_item32_t* dest, size_t src_size,
size_t wanted_rmt_items_num, size_t* out_consumed_src_bytes, size_t* out_used_rmt_items) {
RmtDriver* self;
ESP_ERROR_CHECK(rmt_translator_get_context(out_used_rmt_items, (void**)&self));
const auto& _bitToRmt = self->_bitToRmt;
const auto src_offset = self->_translatorSourceOffset;
auto* src_components = (const uint8_t*)src;
size_t consumed_src_bytes = 0;
size_t used_rmt_items = 0;
while (consumed_src_bytes < src_size && used_rmt_items + 7 < wanted_rmt_items_num) {
uint8_t val = *src_components;
// each bit, from highest to lowest
for (uint8_t j = 0; j != 8; j++, val <<= 1) {
dest->val = _bitToRmt[val >> 7].val;
++dest;
}
used_rmt_items += 8;
++src_components;
++consumed_src_bytes;
// skip alpha byte
if (((src_offset + consumed_src_bytes) % 4) == 3) {
++src_components;
++consumed_src_bytes;
// TRST delay after last pixel in strip
if (consumed_src_bytes == src_size) {
(dest - 1)->duration1 = self->_timing.TRS / (detail::RMT_DURATION_NS * detail::DIVIDER);
}
}
}
self->_translatorSourceOffset = src_offset + consumed_src_bytes;
*out_consumed_src_bytes = consumed_src_bytes;
*out_used_rmt_items = used_rmt_items;
}
esp_err_t RmtDriver::transmit(const Rgb* buffer) {
static_assert(sizeof(Rgb) == 4); // The translator code above assumes RGB is 4 bytes
_translatorSourceOffset = 0;
return rmt_write_sample(_channel, (const uint8_t*)buffer, _count * 4, false);
}
};
#endif // !SMARTLEDS_NEW_RMT_DRIVER

View File

@@ -0,0 +1,68 @@
/********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#pragma once
#include "RmtDriver.h"
#if !SMARTLEDS_NEW_RMT_DRIVER
#include "Color.h"
#include <driver/rmt.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
namespace detail {
constexpr const int CHANNEL_COUNT = RMT_CHANNEL_MAX;
class RmtDriver {
public:
RmtDriver(const LedType& timing, int count, int pin, int channel_num, SemaphoreHandle_t finishedFlag);
RmtDriver(const RmtDriver&) = delete;
esp_err_t init();
esp_err_t registerIsr(bool isFirstRegisteredChannel);
esp_err_t unregisterIsr();
esp_err_t transmit(const Rgb* buffer);
private:
static void IRAM_ATTR txEndCallback(rmt_channel_t channel, void* arg);
static void IRAM_ATTR translateSample(const void* src, rmt_item32_t* dest, size_t src_size,
size_t wanted_rmt_items_num, size_t* out_consumed_src_bytes, size_t* out_used_rmt_items);
const LedType& _timing;
int _count;
gpio_num_t _pin;
SemaphoreHandle_t _finishedFlag;
rmt_channel_t _channel;
rmt_item32_t _bitToRmt[2];
size_t _translatorSourceOffset;
};
};
#endif // !SMARTLEDS_NEW_RMT_DRIVER

View File

@@ -0,0 +1,202 @@
/********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#include "RmtDriver5.h"
#if SMARTLEDS_NEW_RMT_DRIVER
#include <cstddef>
#include "SmartLeds.h"
namespace detail {
static constexpr const uint32_t RMT_RESOLUTION_HZ = 20 * 1000 * 1000; // 20 MHz
static constexpr const uint32_t RMT_NS_PER_TICK = 1000000000LLU / RMT_RESOLUTION_HZ;
static RmtEncoderWrapper* IRAM_ATTR encSelf(rmt_encoder_t* encoder) {
return (RmtEncoderWrapper*)(((intptr_t)encoder) - offsetof(RmtEncoderWrapper, base));
}
static size_t IRAM_ATTR encEncode(rmt_encoder_t* encoder, rmt_channel_handle_t tx_channel, const void* primary_data,
size_t data_size, rmt_encode_state_t* ret_state) {
auto* self = encSelf(encoder);
// Delay after last pixel
if ((self->last_state & RMT_ENCODING_COMPLETE) && self->frame_idx == data_size) {
*ret_state = (rmt_encode_state_t)0;
return self->copy_encoder->encode(
self->copy_encoder, tx_channel, (const void*)&self->reset_code, sizeof(self->reset_code), ret_state);
}
if (self->last_state & RMT_ENCODING_COMPLETE) {
Rgb* pixel = ((Rgb*)primary_data) + self->frame_idx;
self->buffer_len = sizeof(self->buffer);
for (size_t i = 0; i < sizeof(self->buffer); ++i) {
self->buffer[i] = pixel->getGrb(self->component_idx);
if (++self->component_idx == 3) {
self->component_idx = 0;
if (++self->frame_idx == data_size) {
self->buffer_len = i + 1;
break;
}
++pixel;
}
}
}
self->last_state = (rmt_encode_state_t)0;
auto encoded_symbols = self->bytes_encoder->encode(
self->bytes_encoder, tx_channel, (const void*)&self->buffer, self->buffer_len, &self->last_state);
if (self->last_state & RMT_ENCODING_MEM_FULL) {
*ret_state = RMT_ENCODING_MEM_FULL;
} else {
*ret_state = (rmt_encode_state_t)0;
}
return encoded_symbols;
}
static esp_err_t encReset(rmt_encoder_t* encoder) {
auto* self = encSelf(encoder);
rmt_encoder_reset(self->bytes_encoder);
rmt_encoder_reset(self->copy_encoder);
self->last_state = RMT_ENCODING_COMPLETE;
self->frame_idx = 0;
self->component_idx = 0;
return ESP_OK;
}
static esp_err_t encDelete(rmt_encoder_t* encoder) {
auto* self = encSelf(encoder);
rmt_del_encoder(self->bytes_encoder);
rmt_del_encoder(self->copy_encoder);
return ESP_OK;
}
RmtDriver::RmtDriver(const LedType& timing, int count, int pin, int channel_num, SemaphoreHandle_t finishedFlag)
: _timing(timing)
, _count(count)
, _pin(pin)
, _finishedFlag(finishedFlag)
, _channel(nullptr)
, _encoder {} {}
esp_err_t RmtDriver::init() {
_encoder.base.encode = encEncode;
_encoder.base.reset = encReset;
_encoder.base.del = encDelete;
_encoder.reset_code.duration0 = _timing.TRS / RMT_NS_PER_TICK;
rmt_bytes_encoder_config_t bytes_cfg = {
.bit0 = {
.duration0 = uint16_t(_timing.T0H / RMT_NS_PER_TICK),
.level0 = 1,
.duration1 = uint16_t(_timing.T0L / RMT_NS_PER_TICK),
.level1 = 0,
},
.bit1 = {
.duration0 = uint16_t(_timing.T1H / RMT_NS_PER_TICK),
.level0 = 1,
.duration1 = uint16_t(_timing.T1L / RMT_NS_PER_TICK),
.level1 = 0,
},
.flags = {
.msb_first = 1,
},
};
auto err = rmt_new_bytes_encoder(&bytes_cfg, &_encoder.bytes_encoder);
if (err != ESP_OK) {
return err;
}
rmt_copy_encoder_config_t copy_cfg = {};
err = rmt_new_copy_encoder(&copy_cfg, &_encoder.copy_encoder);
if (err != ESP_OK) {
return err;
}
// The config must be in registerIsr, because rmt_new_tx_channel
// registers the ISR
return ESP_OK;
}
esp_err_t RmtDriver::registerIsr(bool isFirstRegisteredChannel) {
rmt_tx_channel_config_t conf = {
.gpio_num = (gpio_num_t)_pin,
.clk_src = RMT_CLK_SRC_DEFAULT, //.clk_src = RMT_CLK_SRC_APB,
.resolution_hz = RMT_RESOLUTION_HZ,
.mem_block_symbols = SOC_RMT_MEM_WORDS_PER_CHANNEL,
.trans_queue_depth = 1,
.flags = {},
};
auto err = rmt_new_tx_channel(&conf, &_channel);
if (err != ESP_OK) {
return err;
}
rmt_tx_event_callbacks_t callbacks_cfg = {};
callbacks_cfg.on_trans_done = txDoneCallback;
err = rmt_tx_register_event_callbacks(_channel, &callbacks_cfg, this);
if (err != ESP_OK) {
return err;
}
return rmt_enable(_channel);
}
esp_err_t RmtDriver::unregisterIsr() {
auto err = rmt_del_encoder(&_encoder.base);
if (err != ESP_OK) {
return err;
}
err = rmt_disable(_channel);
if (err != ESP_OK) {
return err;
}
return rmt_del_channel(_channel);
}
bool IRAM_ATTR RmtDriver::txDoneCallback(
rmt_channel_handle_t tx_chan, const rmt_tx_done_event_data_t* edata, void* user_ctx) {
auto* self = (RmtDriver*)user_ctx;
auto taskWoken = pdTRUE;
xSemaphoreGiveFromISR(self->_finishedFlag, &taskWoken);
return taskWoken == pdTRUE;
}
esp_err_t RmtDriver::transmit(const Rgb* buffer) {
rmt_encoder_reset(&_encoder.base);
rmt_transmit_config_t cfg = {};
return rmt_transmit(_channel, &_encoder.base, buffer, _count, &cfg);
}
};
#endif // !SMARTLEDS_NEW_RMT_DRIVER

View File

@@ -0,0 +1,91 @@
/********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#pragma once
#include "RmtDriver.h"
#if SMARTLEDS_NEW_RMT_DRIVER
#include <driver/rmt_tx.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <type_traits>
#include "Color.h"
#if !defined(CONFIG_RMT_ISR_IRAM_SAFE) && !defined(SMARTLEDS_DISABLE_IRAM_WARNING)
#warning "Please enable CONFIG_RMT_ISR_IRAM_SAFE IDF option." \
"without it, the IDF driver is not able to supply data fast enough."
#endif
namespace detail {
constexpr const int CHANNEL_COUNT = SOC_RMT_GROUPS * SOC_RMT_CHANNELS_PER_GROUP;
class RmtDriver;
// This is ridiculous
struct RmtEncoderWrapper {
struct rmt_encoder_t base;
struct rmt_encoder_t* bytes_encoder;
struct rmt_encoder_t* copy_encoder;
RmtDriver* driver;
rmt_symbol_word_t reset_code;
uint8_t buffer[SOC_RMT_MEM_WORDS_PER_CHANNEL / 8];
rmt_encode_state_t last_state;
size_t frame_idx;
uint8_t component_idx;
uint8_t buffer_len;
};
static_assert(std::is_standard_layout<RmtEncoderWrapper>::value == true);
class RmtDriver {
public:
RmtDriver(const LedType& timing, int count, int pin, int channel_num, SemaphoreHandle_t finishedFlag);
RmtDriver(const RmtDriver&) = delete;
esp_err_t init();
esp_err_t registerIsr(bool isFirstRegisteredChannel);
esp_err_t unregisterIsr();
esp_err_t transmit(const Rgb* buffer);
private:
static bool IRAM_ATTR txDoneCallback(
rmt_channel_handle_t tx_chan, const rmt_tx_done_event_data_t* edata, void* user_ctx);
const LedType& _timing;
int _count;
int _pin;
SemaphoreHandle_t _finishedFlag;
rmt_channel_handle_t _channel;
RmtEncoderWrapper _encoder;
};
};
#endif // !SMARTLEDS_NEW_RMT_DRIVER

View File

@@ -1,90 +1,35 @@
/********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#include "SmartLeds.h" #include "SmartLeds.h"
/* PlatformIO 6 (ESP IDF 5) does no longer allow access to RMTMEM,
see https://docs.espressif.com/projects/esp-idf/en/latest/esp32/migration-guides/release-5.x/5.0/peripherals.html?highlight=rmtmem#id5
As a dirty workaround, we copy the needed structures from rmt_struct.h
In the long run, this should be replaced! */
typedef struct rmt_item32_s {
union {
struct {
uint32_t duration0 :15;
uint32_t level0 :1;
uint32_t duration1 :15;
uint32_t level1 :1;
};
uint32_t val;
};
} rmt_item32_t;
//Allow access to RMT memory using RMTMEM.chan[0].data32[8]
typedef volatile struct rmt_mem_s {
struct {
rmt_item32_t data32[64];
} chan[8];
} rmt_mem_t;
extern rmt_mem_t RMTMEM;
IsrCore SmartLed::_interruptCore = CoreCurrent; IsrCore SmartLed::_interruptCore = CoreCurrent;
intr_handle_t SmartLed::_interruptHandle = NULL;
SmartLed*& IRAM_ATTR SmartLed::ledForChannel( int channel ) { SmartLed*& IRAM_ATTR SmartLed::ledForChannel(int channel) {
static SmartLed* table[8] = { nullptr }; static SmartLed* table[detail::CHANNEL_COUNT] = {};
assert( channel < 8 ); assert(channel < detail::CHANNEL_COUNT);
return table[ channel ]; return table[channel];
}
void IRAM_ATTR SmartLed::interruptHandler(void*) {
for (int channel = 0; channel != 8; channel++) {
auto self = ledForChannel( channel );
if ( RMT.int_st.val & (1 << (24 + channel ) ) ) { // tx_thr_event
if ( self )
self->copyRmtHalfBlock();
RMT.int_clr.val |= 1 << ( 24 + channel );
} else if ( RMT.int_st.val & ( 1 << (3 * channel ) ) ) { // tx_end
if ( self )
xSemaphoreGiveFromISR( self->_finishedFlag, nullptr );
RMT.int_clr.val |= 1 << ( 3 * channel );
}
}
}
void IRAM_ATTR SmartLed::copyRmtHalfBlock() {
int offset = detail::MAX_PULSES * _halfIdx;
_halfIdx = !_halfIdx;
int len = 3 - _componentPosition + 3 * ( _count - 1 );
len = std::min( len, detail::MAX_PULSES / 8 );
if ( !len ) {
for ( int i = 0; i < detail::MAX_PULSES; i++) {
RMTMEM.chan[ _channel].data32[i + offset ].val = 0;
}
}
int i;
for ( i = 0; i != len && _pixelPosition != _count; i++ ) {
uint8_t val = _buffer[ _pixelPosition ].getGrb( _componentPosition );
for ( int j = 0; j != 8; j++, val <<= 1 ) {
int bit = val >> 7;
int idx = i * 8 + offset + j;
RMTMEM.chan[ _channel ].data32[ idx ].val = _bitToRmt[ bit & 0x01 ].value;
}
if ( _pixelPosition == _count - 1 && _componentPosition == 2 ) {
RMTMEM.chan[ _channel ].data32[ i * 8 + offset + 7 ].duration1 =
_timing.TRS / ( detail::RMT_DURATION_NS * detail::DIVIDER );
}
_componentPosition++;
if ( _componentPosition == 3 ) {
_componentPosition = 0;
_pixelPosition++;
}
}
for ( i *= 8; i != detail::MAX_PULSES; i++ ) {
RMTMEM.chan[ _channel ].data32[ i + offset ].val = 0;
}
} }

View File

@@ -1,7 +1,30 @@
#pragma once /********************************************************************************
* https://github.com/RoboticsBrno/SmartLeds
*
* MIT License
*
* Copyright (c) 2017 RoboticsBrno (RobotikaBrno)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
#ifndef SMARTLEDS_H #pragma once
#define SMARTLEDS_H
/* /*
* A C++ driver for the WS2812 LEDs using the RMT peripheral on the ESP32. * A C++ driver for the WS2812 LEDs using the RMT peripheral on the ESP32.
@@ -31,305 +54,196 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
#include <memory>
#include <cassert> #include <cassert>
#include <cstring> #include <cstring>
#include <memory>
#include "esp_idf_version.h" #include <driver/gpio.h>
#if (ESP_IDF_VERSION_MAJOR >= 5) #include <driver/spi_master.h>
#include "soc/periph_defs.h" #include <esp_intr_alloc.h>
#include "esp_private/periph_ctrl.h" #include <esp_ipc.h>
#include "soc/gpio_sig_map.h" #include <freertos/FreeRTOS.h>
#include "soc/gpio_periph.h" #include <freertos/semphr.h>
#include "soc/io_mux_reg.h"
#include "esp_rom_gpio.h"
#define gpio_pad_select_gpio esp_rom_gpio_pad_select_gpio
#define gpio_matrix_in(a,b,c) esp_rom_gpio_connect_in_signal(a,b,c)
#define gpio_matrix_out(a,b,c,d) esp_rom_gpio_connect_out_signal(a,b,c,d)
#define ets_delay_us(a) esp_rom_delay_us(a)
#endif
#if defined ( ARDUINO )
extern "C" { // ...someone forgot to put in the includes...
#include "esp32-hal.h"
#include "esp_intr_alloc.h"
#include "esp_ipc.h"
#include "driver/gpio.h"
#include "driver/periph_ctrl.h"
#include "freertos/semphr.h"
#include "soc/rmt_struct.h"
#include <driver/spi_master.h>
#include "esp_idf_version.h"
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL( 4, 0, 0 )
#include "soc/dport_reg.h"
#endif
}
#elif defined ( ESP_PLATFORM )
extern "C" { // ...someone forgot to put in the includes...
#include <esp_intr_alloc.h>
#include <esp_ipc.h>
#include <driver/gpio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <soc/dport_reg.h>
#include <soc/gpio_sig_map.h>
#include <soc/rmt_struct.h>
#include <driver/spi_master.h>
}
#include <stdio.h>
#endif
#if (ESP_IDF_VERSION_MAJOR >= 4) && (ESP_IDF_VERSION_MINOR > 1)
#include "hal/gpio_ll.h"
#else
#include "soc/gpio_periph.h"
#define esp_rom_delay_us ets_delay_us
static inline int gpio_ll_get_level(gpio_dev_t *hw, int gpio_num)
{
if (gpio_num < 32) {
return (hw->in >> gpio_num) & 0x1;
} else {
return (hw->in1.data >> (gpio_num - 32)) & 0x1;
}
}
#endif
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
#if !(configENABLE_BACKWARD_COMPATIBILITY == 1)
#define xSemaphoreHandle SemaphoreHandle_t
#endif
#endif
#include "Color.h" #include "Color.h"
namespace detail { #include "RmtDriver.h"
struct TimingParams {
uint32_t T0H;
uint32_t T1H;
uint32_t T0L;
uint32_t T1L;
uint32_t TRS;
};
union RmtPulsePair {
struct {
int duration0:15;
int level0:1;
int duration1:15;
int level1:1;
};
uint32_t value;
};
static const int DIVIDER = 4; // 8 still seems to work, but timings become marginal
static const int MAX_PULSES = 32; // A channel has a 64 "pulse" buffer - we use half per pass
static const double RMT_DURATION_NS = 12.5; // minimum time of a single RMT duration based on clock ns
} // namespace detail
using LedType = detail::TimingParams; using LedType = detail::TimingParams;
static const LedType LED_WS2812 = { 350, 700, 800, 600, 50000 }; // Times are in nanoseconds,
static const LedType LED_WS2812B = { 400, 850, 850, 400, 50100 }; // The RMT driver runs at 20MHz, so minimal representable time is 50 nanoseconds
static const LedType LED_SK6812 = { 300, 600, 900, 600, 80000 }; static const LedType LED_WS2812 = { 350, 700, 800, 600, 50000 };
static const LedType LED_WS2813 = { 350, 800, 350, 350, 300000 }; // longer reset time because https://blog.adafruit.com/2017/05/03/psa-the-ws2812b-rgb-led-has-been-revised-will-require-code-tweak/
static const LedType LED_WS2812B = { 400, 800, 850, 450, 300000 }; // universal
static const LedType LED_WS2812B_NEWVARIANT = { 200, 750, 750, 200, 300000 };
static const LedType LED_WS2812B_OLDVARIANT = { 400, 800, 850, 450, 50000 };
// This is timing from datasheet, but does not seem to actually work - try LED_WS2812B
static const LedType LED_WS2812C = { 250, 550, 550, 250, 280000 };
static const LedType LED_SK6812 = { 300, 600, 900, 600, 80000 };
static const LedType LED_WS2813 = { 350, 800, 350, 350, 300000 };
// Single buffer == can't touch the Rgbs between show() and wait()
enum BufferType { SingleBuffer = 0, DoubleBuffer }; enum BufferType { SingleBuffer = 0, DoubleBuffer };
enum IsrCore { CoreFirst = 0, CoreSecond = 1, CoreCurrent = 2}; enum IsrCore { CoreFirst = 0, CoreSecond = 1, CoreCurrent = 2 };
class SmartLed { class SmartLed {
public: public:
friend class detail::RmtDriver;
// The RMT interrupt must not run on the same core as WiFi interrupts, otherwise SmartLeds // The RMT interrupt must not run on the same core as WiFi interrupts, otherwise SmartLeds
// can't fill the RMT buffer fast enough, resulting in rendering artifacts. // can't fill the RMT buffer fast enough, resulting in rendering artifacts.
// Usually, that means you have to set isrCore == CoreSecond. // Usually, that means you have to set isrCore == CoreSecond.
// //
// If you use anything other than CoreCurrent, the FreeRTOS scheduler MUST be already running, // If you use anything other than CoreCurrent, the FreeRTOS scheduler MUST be already running,
// so you can't use it if you define SmartLed as global variable. // so you can't use it if you define SmartLed as global variable.
SmartLed( const LedType& type, int count, int pin, int channel = 0, BufferType doubleBuffer = SingleBuffer, IsrCore isrCore = CoreCurrent) //
: _timing( type ), // Does nothing on chips that only have one core.
_channel( channel ), SmartLed(const LedType& type, int count, int pin, int channel = 0, BufferType doubleBuffer = DoubleBuffer,
_count( count ), IsrCore isrCore = CoreCurrent)
_firstBuffer( new Rgb[ count ] ), : _finishedFlag(xSemaphoreCreateBinary())
_secondBuffer( doubleBuffer ? new Rgb[ count ] : nullptr ), , _driver(type, count, pin, channel, _finishedFlag)
_finishedFlag( xSemaphoreCreateBinary() ) , _channel(channel)
{ , _count(count)
assert( channel >= 0 && channel < 8 ); , _firstBuffer(new Rgb[count])
assert( ledForChannel( channel ) == nullptr ); , _secondBuffer(doubleBuffer ? new Rgb[count] : nullptr) {
assert(channel >= 0 && channel < detail::CHANNEL_COUNT);
assert(ledForChannel(channel) == nullptr);
xSemaphoreGive( _finishedFlag ); xSemaphoreGive(_finishedFlag);
DPORT_SET_PERI_REG_MASK( DPORT_PERIP_CLK_EN_REG, DPORT_RMT_CLK_EN ); _driver.init();
DPORT_CLEAR_PERI_REG_MASK( DPORT_PERIP_RST_EN_REG, DPORT_RMT_RST );
PIN_FUNC_SELECT( GPIO_PIN_MUX_REG[ pin ], 2 ); #if !defined(SOC_CPU_CORES_NUM) || SOC_CPU_CORES_NUM > 1
gpio_set_direction( static_cast< gpio_num_t >( pin ), GPIO_MODE_OUTPUT ); if (!anyAlive() && isrCore != CoreCurrent) {
gpio_matrix_out( static_cast< gpio_num_t >( pin ), RMT_SIG_OUT0_IDX + _channel, 0, 0 );
initChannel( _channel );
RMT.tx_lim_ch[ _channel ].limit = detail::MAX_PULSES;
RMT.int_ena.val |= 1 << ( 24 + _channel );
RMT.int_ena.val |= 1 << ( 3 * _channel );
_bitToRmt[ 0 ].level0 = 1;
_bitToRmt[ 0 ].level1 = 0;
_bitToRmt[ 0 ].duration0 = _timing.T0H / ( detail::RMT_DURATION_NS * detail::DIVIDER );
_bitToRmt[ 0 ].duration1 = _timing.T0L / ( detail::RMT_DURATION_NS * detail::DIVIDER );
_bitToRmt[ 1 ].level0 = 1;
_bitToRmt[ 1 ].level1 = 0;
_bitToRmt[ 1 ].duration0 = _timing.T1H / ( detail::RMT_DURATION_NS * detail::DIVIDER );
_bitToRmt[ 1 ].duration1 = _timing.T1L / ( detail::RMT_DURATION_NS * detail::DIVIDER );
if ( !anyAlive() ) {
_interruptCore = isrCore; _interruptCore = isrCore;
if(isrCore != CoreCurrent) { ESP_ERROR_CHECK(esp_ipc_call_blocking(isrCore, registerInterrupt, (void*)this));
ESP_ERROR_CHECK(esp_ipc_call_blocking(isrCore, registerInterrupt, NULL)); } else
} else { #endif
registerInterrupt(NULL); {
} registerInterrupt((void*)this);
} }
ledForChannel( channel ) = this; ledForChannel(channel) = this;
} }
~SmartLed() { ~SmartLed() {
ledForChannel( _channel ) = nullptr; ledForChannel(_channel) = nullptr;
if ( !anyAlive() ) { #if !defined(SOC_CPU_CORES_NUM) || SOC_CPU_CORES_NUM > 1
if(_interruptCore != CoreCurrent) { if (!anyAlive() && _interruptCore != CoreCurrent) {
ESP_ERROR_CHECK(esp_ipc_call_blocking(_interruptCore, unregisterInterrupt, NULL)); ESP_ERROR_CHECK(esp_ipc_call_blocking(_interruptCore, unregisterInterrupt, (void*)this));
} else { } else
unregisterInterrupt(NULL); #endif
} {
unregisterInterrupt((void*)this);
} }
vSemaphoreDelete( _finishedFlag ); vSemaphoreDelete(_finishedFlag);
} }
Rgb& operator[]( int idx ) { Rgb& operator[](int idx) { return _firstBuffer[idx]; }
return _firstBuffer[ idx ];
}
const Rgb& operator[]( int idx ) const { const Rgb& operator[](int idx) const { return _firstBuffer[idx]; }
return _firstBuffer[ idx ];
}
void show() { esp_err_t show() {
_buffer = _firstBuffer.get(); esp_err_t err = startTransmission();
startTransmission();
swapBuffers(); swapBuffers();
return err;
} }
bool wait( TickType_t timeout = portMAX_DELAY ) { bool wait(TickType_t timeout = portMAX_DELAY) {
if( xSemaphoreTake( _finishedFlag, timeout ) == pdTRUE ) { if (xSemaphoreTake(_finishedFlag, timeout) == pdTRUE) {
xSemaphoreGive( _finishedFlag ); xSemaphoreGive(_finishedFlag);
return true; return true;
} }
return false; return false;
} }
int size() const { int size() const { return _count; }
return _count; int channel() const { return _channel; }
}
Rgb *begin() { return _firstBuffer.get(); } Rgb* begin() { return _firstBuffer.get(); }
const Rgb *begin() const { return _firstBuffer.get(); } const Rgb* begin() const { return _firstBuffer.get(); }
const Rgb *cbegin() const { return _firstBuffer.get(); } const Rgb* cbegin() const { return _firstBuffer.get(); }
Rgb *end() { return _firstBuffer.get() + _count; } Rgb* end() { return _firstBuffer.get() + _count; }
const Rgb *end() const { return _firstBuffer.get() + _count; } const Rgb* end() const { return _firstBuffer.get() + _count; }
const Rgb *cend() const { return _firstBuffer.get() + _count; } const Rgb* cend() const { return _firstBuffer.get() + _count; }
private: private:
static intr_handle_t _interruptHandle;
static IsrCore _interruptCore; static IsrCore _interruptCore;
static void initChannel( int channel ) { static void registerInterrupt(void* selfVoid) {
RMT.apb_conf.fifo_mask = 1; //enable memory access, instead of FIFO mode. auto* self = (SmartLed*)selfVoid;
RMT.apb_conf.mem_tx_wrap_en = 1; //wrap around when hitting end of buffer ESP_ERROR_CHECK(self->_driver.registerIsr(!anyAlive()));
RMT.conf_ch[ channel ].conf0.div_cnt = detail::DIVIDER;
RMT.conf_ch[ channel ].conf0.mem_size = 1;
RMT.conf_ch[ channel ].conf0.carrier_en = 0;
RMT.conf_ch[ channel ].conf0.carrier_out_lv = 1;
RMT.conf_ch[ channel ].conf0.mem_pd = 0;
RMT.conf_ch[ channel ].conf1.rx_en = 0;
RMT.conf_ch[ channel ].conf1.mem_owner = 0;
RMT.conf_ch[ channel ].conf1.tx_conti_mode = 0; //loop back mode.
RMT.conf_ch[ channel ].conf1.ref_always_on = 1; // use apb clock: 80M
RMT.conf_ch[ channel ].conf1.idle_out_en = 1;
RMT.conf_ch[ channel ].conf1.idle_out_lv = 0;
} }
static void registerInterrupt(void *) { static void unregisterInterrupt(void* selfVoid) {
ESP_ERROR_CHECK(esp_intr_alloc( ETS_RMT_INTR_SOURCE, 0, interruptHandler, nullptr, &_interruptHandle)); auto* self = (SmartLed*)selfVoid;
ESP_ERROR_CHECK(self->_driver.unregisterIsr());
} }
static void unregisterInterrupt(void*) { static SmartLed*& IRAM_ATTR ledForChannel(int channel);
esp_intr_free( _interruptHandle );
}
static SmartLed*& IRAM_ATTR ledForChannel( int channel );
static void IRAM_ATTR interruptHandler( void* );
void IRAM_ATTR copyRmtHalfBlock();
void swapBuffers() {
if ( _secondBuffer )
_firstBuffer.swap( _secondBuffer );
}
void startTransmission() {
// Invalid use of the library
if( xSemaphoreTake( _finishedFlag, 0 ) != pdTRUE )
abort();
_pixelPosition = _componentPosition = _halfIdx = 0;
copyRmtHalfBlock();
if ( _pixelPosition < _count )
copyRmtHalfBlock();
RMT.conf_ch[ _channel ].conf1.mem_rd_rst = 1;
RMT.conf_ch[ _channel ].conf1.tx_start = 1;
}
static bool anyAlive() { static bool anyAlive() {
for ( int i = 0; i != 8; i++ ) for (int i = 0; i != detail::CHANNEL_COUNT; i++)
if ( ledForChannel( i ) != nullptr ) return true; if (ledForChannel(i) != nullptr)
return true;
return false; return false;
} }
const LedType& _timing; void swapBuffers() {
if (_secondBuffer)
_firstBuffer.swap(_secondBuffer);
}
esp_err_t startTransmission() {
// Invalid use of the library, you must wait() fir previous frame to get processed first
if (xSemaphoreTake(_finishedFlag, 0) != pdTRUE)
abort();
auto err = _driver.transmit(_firstBuffer.get());
if (err != ESP_OK) {
return err;
}
return ESP_OK;
}
SemaphoreHandle_t _finishedFlag;
detail::RmtDriver _driver;
int _channel; int _channel;
detail::RmtPulsePair _bitToRmt[ 2 ];
int _count; int _count;
std::unique_ptr< Rgb[] > _firstBuffer; std::unique_ptr<Rgb[]> _firstBuffer;
std::unique_ptr< Rgb[] > _secondBuffer; std::unique_ptr<Rgb[]> _secondBuffer;
Rgb *_buffer;
xSemaphoreHandle _finishedFlag;
int _pixelPosition;
int _componentPosition;
int _halfIdx;
}; };
#if defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32C3)
#define _SMARTLEDS_SPI_HOST SPI2_HOST
#define _SMARTLEDS_SPI_DMA_CHAN SPI_DMA_CH_AUTO
#else
#define _SMARTLEDS_SPI_HOST HSPI_HOST
#define _SMARTLEDS_SPI_DMA_CHAN 1
#endif
class Apa102 { class Apa102 {
public: public:
struct ApaRgb { struct ApaRgb {
ApaRgb( uint8_t r = 0, uint8_t g = 0, uint32_t b = 0, uint32_t v = 0xFF ) ApaRgb(uint8_t r = 0, uint8_t g = 0, uint32_t b = 0, uint32_t v = 0xFF)
: v( 0xE0 | v ), b( b ), g( g ), r( r ) : v(0xE0 | v)
{} , b(b)
, g(g)
, r(r) {}
ApaRgb& operator=( const Rgb& o ) { ApaRgb& operator=(const Rgb& o) {
r = o.r; r = o.r;
g = o.g; g = o.g;
b = o.b; b = o.b;
return *this; return *this;
} }
ApaRgb& operator=( const Hsv& o ) { ApaRgb& operator=(const Hsv& o) {
*this = Rgb{ o }; *this = Rgb { o };
return *this; return *this;
} }
@@ -339,14 +253,14 @@ public:
static const int FINAL_FRAME_SIZE = 4; static const int FINAL_FRAME_SIZE = 4;
static const int TRANS_COUNT = 2 + 8; static const int TRANS_COUNT = 2 + 8;
Apa102( int count, int clkpin, int datapin, BufferType doubleBuffer = SingleBuffer ) Apa102(int count, int clkpin, int datapin, BufferType doubleBuffer = SingleBuffer, int clock_speed_hz = 1000000)
: _count( count ), : _count(count)
_firstBuffer( new ApaRgb[ count ] ), , _firstBuffer(new ApaRgb[count])
_secondBuffer( doubleBuffer ? new ApaRgb[ count ] : nullptr ), , _secondBuffer(doubleBuffer ? new ApaRgb[count] : nullptr)
_initFrame( 0 ) , _transCount(0)
{ , _initFrame(0) {
spi_bus_config_t buscfg; spi_bus_config_t buscfg;
memset( &buscfg, 0, sizeof( buscfg ) ); memset(&buscfg, 0, sizeof(buscfg));
buscfg.mosi_io_num = datapin; buscfg.mosi_io_num = datapin;
buscfg.miso_io_num = -1; buscfg.miso_io_num = -1;
buscfg.sclk_io_num = clkpin; buscfg.sclk_io_num = clkpin;
@@ -355,33 +269,29 @@ public:
buscfg.max_transfer_sz = 65535; buscfg.max_transfer_sz = 65535;
spi_device_interface_config_t devcfg; spi_device_interface_config_t devcfg;
memset( &devcfg, 0, sizeof( devcfg ) ); memset(&devcfg, 0, sizeof(devcfg));
devcfg.clock_speed_hz = 1000000; devcfg.clock_speed_hz = clock_speed_hz;
devcfg.mode = 0; devcfg.mode = 0;
devcfg.spics_io_num = -1; devcfg.spics_io_num = -1;
devcfg.queue_size = TRANS_COUNT; devcfg.queue_size = TRANS_COUNT;
devcfg.pre_cb = nullptr; devcfg.pre_cb = nullptr;
auto ret = spi_bus_initialize( HSPI_HOST, &buscfg, 1 ); auto ret = spi_bus_initialize(_SMARTLEDS_SPI_HOST, &buscfg, _SMARTLEDS_SPI_DMA_CHAN);
assert( ret == ESP_OK ); assert(ret == ESP_OK);
ret = spi_bus_add_device( HSPI_HOST, &devcfg, &_spi ); ret = spi_bus_add_device(_SMARTLEDS_SPI_HOST, &devcfg, &_spi);
assert( ret == ESP_OK ); assert(ret == ESP_OK);
std::fill_n( _finalFrame, FINAL_FRAME_SIZE, 0xFFFFFFFF ); std::fill_n(_finalFrame, FINAL_FRAME_SIZE, 0xFFFFFFFF);
} }
~Apa102() { ~Apa102() {
// ToDo // ToDo
} }
ApaRgb& operator[]( int idx ) { ApaRgb& operator[](int idx) { return _firstBuffer[idx]; }
return _firstBuffer[ idx ];
}
const ApaRgb& operator[]( int idx ) const { const ApaRgb& operator[](int idx) const { return _firstBuffer[idx]; }
return _firstBuffer[ idx ];
}
void show() { void show() {
_buffer = _firstBuffer.get(); _buffer = _firstBuffer.get();
@@ -390,93 +300,95 @@ public:
} }
void wait() { void wait() {
for ( int i = 0; i != _transCount; i++ ) { for (int i = 0; i != _transCount; i++) {
spi_transaction_t *t; spi_transaction_t* t;
spi_device_get_trans_result( _spi, &t, portMAX_DELAY ); spi_device_get_trans_result(_spi, &t, portMAX_DELAY);
} }
} }
private: private:
void swapBuffers() { void swapBuffers() {
if ( _secondBuffer ) if (_secondBuffer)
_firstBuffer.swap( _secondBuffer ); _firstBuffer.swap(_secondBuffer);
} }
void startTransmission() { void startTransmission() {
for ( int i = 0; i != TRANS_COUNT; i++ ) { for (int i = 0; i != TRANS_COUNT; i++) {
_transactions[ i ].cmd = 0; _transactions[i].cmd = 0;
_transactions[ i ].addr = 0; _transactions[i].addr = 0;
_transactions[ i ].flags = 0; _transactions[i].flags = 0;
_transactions[ i ].rxlength = 0; _transactions[i].rxlength = 0;
_transactions[ i ].rx_buffer = nullptr; _transactions[i].rx_buffer = nullptr;
} }
// Init frame // Init frame
_transactions[ 0 ].length = 32; _transactions[0].length = 32;
_transactions[ 0 ].tx_buffer = &_initFrame; _transactions[0].tx_buffer = &_initFrame;
spi_device_queue_trans( _spi, _transactions + 0, portMAX_DELAY ); spi_device_queue_trans(_spi, _transactions + 0, portMAX_DELAY);
// Data // Data
_transactions[ 1 ].length = 32 * _count; _transactions[1].length = 32 * _count;
_transactions[ 1 ].tx_buffer = _buffer; _transactions[1].tx_buffer = _buffer;
spi_device_queue_trans( _spi, _transactions + 1, portMAX_DELAY ); spi_device_queue_trans(_spi, _transactions + 1, portMAX_DELAY);
_transCount = 2; _transCount = 2;
// End frame // End frame
for ( int i = 0; i != 1 + _count / 32 / FINAL_FRAME_SIZE; i++ ) { for (int i = 0; i != 1 + _count / 32 / FINAL_FRAME_SIZE; i++) {
_transactions[ 2 + i ].length = 32 * FINAL_FRAME_SIZE; _transactions[2 + i].length = 32 * FINAL_FRAME_SIZE;
_transactions[ 2 + i ].tx_buffer = _finalFrame; _transactions[2 + i].tx_buffer = _finalFrame;
spi_device_queue_trans( _spi, _transactions + 2 + i, portMAX_DELAY ); spi_device_queue_trans(_spi, _transactions + 2 + i, portMAX_DELAY);
_transCount++; _transCount++;
} }
} }
spi_device_handle_t _spi; spi_device_handle_t _spi;
int _count; int _count;
std::unique_ptr< ApaRgb[] > _firstBuffer, _secondBuffer; std::unique_ptr<ApaRgb[]> _firstBuffer, _secondBuffer;
ApaRgb *_buffer; ApaRgb* _buffer;
spi_transaction_t _transactions[ TRANS_COUNT ]; spi_transaction_t _transactions[TRANS_COUNT];
int _transCount; int _transCount;
uint32_t _initFrame; uint32_t _initFrame;
uint32_t _finalFrame[ FINAL_FRAME_SIZE ]; uint32_t _finalFrame[FINAL_FRAME_SIZE];
}; };
class LDP8806 { class LDP8806 {
public: public:
struct LDP8806_GRB { struct LDP8806_GRB {
LDP8806_GRB( uint8_t g_7bit = 0, uint8_t r_7bit = 0, uint32_t b_7bit = 0 ) LDP8806_GRB(uint8_t g_7bit = 0, uint8_t r_7bit = 0, uint32_t b_7bit = 0)
: g( g_7bit ), r( r_7bit ), b( b_7bit ) : g(g_7bit)
{ , r(r_7bit)
} , b(b_7bit) {}
LDP8806_GRB& operator=( const Rgb& o ) { LDP8806_GRB& operator=(const Rgb& o) {
//Convert 8->7bit colour //Convert 8->7bit colour
r = ( o.r * 127 / 256 ) | 0x80; r = (o.r * 127 / 256) | 0x80;
g = ( o.g * 127 / 256 ) | 0x80; g = (o.g * 127 / 256) | 0x80;
b = ( o.b * 127 / 256 ) | 0x80; b = (o.b * 127 / 256) | 0x80;
return *this; return *this;
} }
LDP8806_GRB& operator=( const Hsv& o ) { LDP8806_GRB& operator=(const Hsv& o) {
*this = Rgb{ o }; *this = Rgb { o };
return *this; return *this;
} }
uint8_t g, r, b; uint8_t g, r, b;
}; };
static const int LED_FRAME_SIZE_BYTES = sizeof( LDP8806_GRB ); static const int LED_FRAME_SIZE_BYTES = sizeof(LDP8806_GRB);
static const int LATCH_FRAME_SIZE_BYTES = 3; static const int LATCH_FRAME_SIZE_BYTES = 3;
static const int TRANS_COUNT_MAX = 20;//Arbitrary, supports up to 600 LED static const int TRANS_COUNT_MAX = 20; //Arbitrary, supports up to 600 LED
LDP8806( int count, int clkpin, int datapin, BufferType doubleBuffer = SingleBuffer, uint32_t clock_speed_hz = 2000000 ) LDP8806(
: _count( count ), int count, int clkpin, int datapin, BufferType doubleBuffer = SingleBuffer, uint32_t clock_speed_hz = 2000000)
_firstBuffer( new LDP8806_GRB[ count ] ), : _count(count)
_secondBuffer( doubleBuffer ? new LDP8806_GRB[ count ] : nullptr ), , _firstBuffer(new LDP8806_GRB[count])
// one 'latch'/start-of-data mark frame for every 32 leds , _secondBuffer(doubleBuffer ? new LDP8806_GRB[count] : nullptr)
_latchFrames( ( count + 31 ) / 32 ) ,
{ // one 'latch'/start-of-data mark frame for every 32 leds
_latchFrames((count + 31) / 32) {
spi_bus_config_t buscfg; spi_bus_config_t buscfg;
memset( &buscfg, 0, sizeof( buscfg ) ); memset(&buscfg, 0, sizeof(buscfg));
buscfg.mosi_io_num = datapin; buscfg.mosi_io_num = datapin;
buscfg.miso_io_num = -1; buscfg.miso_io_num = -1;
buscfg.sclk_io_num = clkpin; buscfg.sclk_io_num = clkpin;
@@ -485,33 +397,29 @@ public:
buscfg.max_transfer_sz = 65535; buscfg.max_transfer_sz = 65535;
spi_device_interface_config_t devcfg; spi_device_interface_config_t devcfg;
memset( &devcfg, 0, sizeof( devcfg ) ); memset(&devcfg, 0, sizeof(devcfg));
devcfg.clock_speed_hz = clock_speed_hz; devcfg.clock_speed_hz = clock_speed_hz;
devcfg.mode = 0; devcfg.mode = 0;
devcfg.spics_io_num = -1; devcfg.spics_io_num = -1;
devcfg.queue_size = TRANS_COUNT_MAX; devcfg.queue_size = TRANS_COUNT_MAX;
devcfg.pre_cb = nullptr; devcfg.pre_cb = nullptr;
auto ret = spi_bus_initialize( HSPI_HOST, &buscfg, 1 ); auto ret = spi_bus_initialize(_SMARTLEDS_SPI_HOST, &buscfg, _SMARTLEDS_SPI_DMA_CHAN);
assert( ret == ESP_OK ); assert(ret == ESP_OK);
ret = spi_bus_add_device( HSPI_HOST, &devcfg, &_spi ); ret = spi_bus_add_device(_SMARTLEDS_SPI_HOST, &devcfg, &_spi);
assert( ret == ESP_OK ); assert(ret == ESP_OK);
std::fill_n( _latchBuffer, LATCH_FRAME_SIZE_BYTES, 0x0 ); std::fill_n(_latchBuffer, LATCH_FRAME_SIZE_BYTES, 0x0);
} }
~LDP8806() { ~LDP8806() {
// noop // noop
} }
LDP8806_GRB& operator[]( int idx ) { LDP8806_GRB& operator[](int idx) { return _firstBuffer[idx]; }
return _firstBuffer[ idx ];
}
const LDP8806_GRB& operator[]( int idx ) const { const LDP8806_GRB& operator[](int idx) const { return _firstBuffer[idx]; }
return _firstBuffer[ idx ];
}
void show() { void show() {
_buffer = _firstBuffer.get(); _buffer = _firstBuffer.get();
@@ -520,51 +428,50 @@ public:
} }
void wait() { void wait() {
while ( _transCount-- ) { while (_transCount--) {
spi_transaction_t *t; spi_transaction_t* t;
spi_device_get_trans_result( _spi, &t, portMAX_DELAY ); spi_device_get_trans_result(_spi, &t, portMAX_DELAY);
} }
} }
private: private:
void swapBuffers() { void swapBuffers() {
if ( _secondBuffer ) if (_secondBuffer)
_firstBuffer.swap( _secondBuffer ); _firstBuffer.swap(_secondBuffer);
} }
void startTransmission() { void startTransmission() {
_transCount = 0; _transCount = 0;
for ( int i = 0; i != TRANS_COUNT_MAX; i++ ) { for (int i = 0; i != TRANS_COUNT_MAX; i++) {
_transactions[ i ].cmd = 0; _transactions[i].cmd = 0;
_transactions[ i ].addr = 0; _transactions[i].addr = 0;
_transactions[ i ].flags = 0; _transactions[i].flags = 0;
_transactions[ i ].rxlength = 0; _transactions[i].rxlength = 0;
_transactions[ i ].rx_buffer = nullptr; _transactions[i].rx_buffer = nullptr;
} }
// LED Data // LED Data
_transactions[ 0 ].length = ( LED_FRAME_SIZE_BYTES * 8 ) * _count; _transactions[0].length = (LED_FRAME_SIZE_BYTES * 8) * _count;
_transactions[ 0 ].tx_buffer = _buffer; _transactions[0].tx_buffer = _buffer;
spi_device_queue_trans( _spi, _transactions + _transCount, portMAX_DELAY ); spi_device_queue_trans(_spi, _transactions + _transCount, portMAX_DELAY);
_transCount++; _transCount++;
// 'latch'/start-of-data marker frames // 'latch'/start-of-data marker frames
for ( int i = 0; i < _latchFrames; i++ ) { for (int i = 0; i < _latchFrames; i++) {
_transactions[ _transCount ].length = ( LATCH_FRAME_SIZE_BYTES * 8 ); _transactions[_transCount].length = (LATCH_FRAME_SIZE_BYTES * 8);
_transactions[ _transCount ].tx_buffer = _latchBuffer; _transactions[_transCount].tx_buffer = _latchBuffer;
spi_device_queue_trans( _spi, _transactions + _transCount, portMAX_DELAY ); spi_device_queue_trans(_spi, _transactions + _transCount, portMAX_DELAY);
_transCount++; _transCount++;
} }
} }
spi_device_handle_t _spi; spi_device_handle_t _spi;
int _count; int _count;
std::unique_ptr< LDP8806_GRB[] > _firstBuffer, _secondBuffer; std::unique_ptr<LDP8806_GRB[]> _firstBuffer, _secondBuffer;
LDP8806_GRB *_buffer; LDP8806_GRB* _buffer;
spi_transaction_t _transactions[ TRANS_COUNT_MAX ]; spi_transaction_t _transactions[TRANS_COUNT_MAX];
int _transCount; int _transCount;
int _latchFrames; int _latchFrames;
uint8_t _latchBuffer[ LATCH_FRAME_SIZE_BYTES ]; uint8_t _latchBuffer[LATCH_FRAME_SIZE_BYTES];
}; };
#endif //SMARTLEDS_H

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -15,49 +15,103 @@
#include "CImageBasis.h" #include "CImageBasis.h"
#include "../../include/defines.h" #include "../../include/defines.h"
class CCamera { typedef struct
protected: {
int ActualQuality; uint16_t CamSensor_id;
framesize_t ActualResolution;
int brightness, contrast, saturation;
bool isFixedExposure;
int waitbeforepicture_org;
int led_intensity = 4095;
void ledc_init(void); framesize_t ImageFrameSize = FRAMESIZE_VGA; // 0 - 10
bool CameraInitSuccessful = false; gainceiling_t ImageGainceiling; // Image gain (GAINCEILING_x2, x4, x8, x16, x32, x64 or x128)
bool demoMode = false;
bool loadNextDemoImage(camera_fb_t *fb); int ImageQuality; // 0 - 63
long GetFileSize(std::string filename); 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)
public: int ImageDenoiseLevel; // The OV2640 does not support it, OV3660 and OV5640 (0 to 8)
int image_height, image_width;
CCamera();
esp_err_t InitCam();
void LightOnOff(bool status); int ImageWidth;
void LEDOnOff(bool status); int ImageHeight;
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);
framesize_t TextToFramesize(const char * text); int ImageLedIntensity;
esp_err_t CaptureToFile(std::string nm, int delay = 0); bool ImageZoomEnabled;
esp_err_t CaptureToBasisImage(CImageBasis *_Image, int delay = 0); 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);
}; };
extern CCamera Camera; extern CCamera Camera;
#endif #endif

View File

@@ -0,0 +1,88 @@
// 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

@@ -0,0 +1,10 @@
#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

@@ -0,0 +1,151 @@
#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

@@ -0,0 +1,11 @@
#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

@@ -0,0 +1,66 @@
// 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

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

View File

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

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/richgel999/miniz/issues/145
- https://github.com/espressif/esptool/pull/500#issuecomment-574879468 - https://github.com/espressif/esptool/pull/500#issuecomment-574879468
For sumplicity we therefore use the release files as suggested in the readme. For simplicity we therefore use the release files as suggested in the readme.
Additionally we added the CMakeLists.txt and this readme. Additionally we added the CMakeLists.txt and this readme.

View File

@@ -6,11 +6,8 @@
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. CONDITIONS OF ANY KIND, either express or implied.
*/ */
#include "server_file.h" #include "server_file.h"
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <string> #include <string>
@@ -46,6 +43,7 @@ extern "C" {
#include "Helper.h" #include "Helper.h"
#include "miniz.h" #include "miniz.h"
#include "basic_auth.h"
static const char *TAG = "OTA FILE"; static const char *TAG = "OTA FILE";
@@ -57,20 +55,17 @@ struct file_server_data {
char scratch[SERVER_FILER_SCRATCH_BUFSIZE]; char scratch[SERVER_FILER_SCRATCH_BUFSIZE];
}; };
#include <iostream> #include <iostream>
#include <sys/types.h> #include <sys/types.h>
#include <dirent.h> #include <dirent.h>
using namespace std; using namespace std;
string SUFFIX_ZW = "_0xge"; string SUFFIX_ZW = "_tmp";
static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file); static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file);
static esp_err_t send_datafile(httpd_req_t *req, bool send_full_file); static esp_err_t send_datafile(httpd_req_t *req, bool send_full_file);
esp_err_t get_numbers_file_handler(httpd_req_t *req) esp_err_t get_numbers_file_handler(httpd_req_t *req)
{ {
std::string ret = flowctrl.getNumbersName(); std::string ret = flowctrl.getNumbersName();
@@ -86,7 +81,6 @@ esp_err_t get_numbers_file_handler(httpd_req_t *req)
return ESP_OK; return ESP_OK;
} }
esp_err_t get_data_file_handler(httpd_req_t *req) esp_err_t get_data_file_handler(httpd_req_t *req)
{ {
struct dirent *entry; struct dirent *entry;
@@ -130,7 +124,6 @@ esp_err_t get_data_file_handler(httpd_req_t *req)
return ESP_OK; return ESP_OK;
} }
esp_err_t get_tflite_file_handler(httpd_req_t *req) esp_err_t get_tflite_file_handler(httpd_req_t *req)
{ {
struct dirent *entry; struct dirent *entry;
@@ -174,12 +167,11 @@ esp_err_t get_tflite_file_handler(httpd_req_t *req)
return ESP_OK; return ESP_OK;
} }
/* Send HTTP response with a run-time generated html consisting of /* Send HTTP response with a run-time generated html consisting of
* a list of all files and folders under the requested path. * a list of all files and folders under the requested path.
* In case of SPIFFS this returns empty list when path is any * In case of SPIFFS this returns empty list when path is any
* string other than '/', since SPIFFS doesn't support directories */ * string other than '/', since SPIFFS doesn't support directories */
static esp_err_t http_resp_dir_html(httpd_req_t *req, const char *dirpath, const char* uripath, bool readonly) static esp_err_t http_resp_dir_html(httpd_req_t *req, const char *dirpath, const char *uripath, bool readonly)
{ {
char entrypath[FILE_PATH_MAX]; char entrypath[FILE_PATH_MAX];
char entrysize[16]; char entrysize[16];
@@ -191,82 +183,85 @@ static esp_err_t http_resp_dir_html(httpd_req_t *req, const char *dirpath, const
char dirpath_corrected[FILE_PATH_MAX]; char dirpath_corrected[FILE_PATH_MAX];
strcpy(dirpath_corrected, dirpath); strcpy(dirpath_corrected, dirpath);
file_server_data * server_data = (file_server_data *) req->user_ctx; file_server_data *server_data = (file_server_data *)req->user_ctx;
if ((strlen(dirpath_corrected)-1) > strlen(server_data->base_path)) // if dirpath is not mountpoint, the last "\" needs to be removed
dirpath_corrected[strlen(dirpath_corrected)-1] = '\0';
DIR *dir = opendir(dirpath_corrected); if ((strlen(dirpath_corrected) - 1) > strlen(server_data->base_path)) {
// if dirpath is not mountpoint, the last "\" needs to be removed
dirpath_corrected[strlen(dirpath_corrected) - 1] = '\0';
}
DIR *pdir = opendir(dirpath_corrected);
const size_t dirpath_len = strlen(dirpath); const size_t dirpath_len = strlen(dirpath);
ESP_LOGD(TAG, "Dirpath: <%s>, Pathlength: %d", dirpath, dirpath_len); ESP_LOGD(TAG, "Dirpath: <%s>, Pathlength: %d", dirpath, dirpath_len);
/* Retrieve the base path of file storage to construct the full path */ // Retrieve the base path of file storage to construct the full path
strlcpy(entrypath, dirpath, sizeof(entrypath)); strlcpy(entrypath, dirpath, sizeof(entrypath));
ESP_LOGD(TAG, "entrypath: <%s>", entrypath); ESP_LOGD(TAG, "entrypath: <%s>", entrypath);
if (!dir) { if (!pdir) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to stat dir: " + std::string(dirpath) + "!"); LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to stat dir: " + std::string(dirpath) + "!");
/* Respond with 404 Not Found */ // Respond with 404 Not Found
httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404()); httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404());
return ESP_FAIL; return ESP_FAIL;
} }
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
/* Send HTML file header */ // Send HTML file header
httpd_resp_sendstr_chunk(req, "<!DOCTYPE html><html><body>"); httpd_resp_sendstr_chunk(req, "<!DOCTYPE html><html lang=\"en\" xml:lang=\"en\"><head>");
httpd_resp_sendstr_chunk(req, "<link href=\"/file_server.css\" rel=\"stylesheet\">");
httpd_resp_sendstr_chunk(req, "<link href=\"/firework.css\" rel=\"stylesheet\">");
httpd_resp_sendstr_chunk(req, "<script type=\"text/javascript\" src=\"/jquery-3.6.0.min.js\"></script>");
httpd_resp_sendstr_chunk(req, "<script type=\"text/javascript\" src=\"/firework.js\"></script></head>");
///////////////////////////////////////////////// httpd_resp_sendstr_chunk(req, "<body>");
if (!readonly) {
FILE *fd = fopen("/sdcard/html/file_server.html", "r"); httpd_resp_sendstr_chunk(req, "<table class=\"fixed\" border=\"0\" width=100% style=\"font-family: arial\">");
char *chunk = ((struct file_server_data *)req->user_ctx)->scratch; httpd_resp_sendstr_chunk(req, "<tr><td style=\"vertical-align: top;width: 300px;\"><h2>Fileserver</h2></td>"
size_t chunksize; "<td rowspan=\"2\"><table border=\"0\" style=\"width:100%\"><tr><td style=\"width:80px\">"
do { "<label for=\"newfile\">Source</label></td><td colspan=\"2\">"
chunksize = fread(chunk, 1, SERVER_FILER_SCRATCH_BUFSIZE, fd); "<input id=\"newfile\" type=\"file\" onchange=\"setpath()\" style=\"width:100%;\"></td></tr>"
// ESP_LOGD(TAG, "Chunksize %d", chunksize); "<tr><td><label for=\"filepath\">Destination</label></td><td>"
if (chunksize > 0){ "<input id=\"filepath\" type=\"text\" style=\"width:94%;\"></td><td>"
if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK) { "<button id=\"upload\" type=\"button\" class=\"button\" onclick=\"upload()\">Upload</button></td></tr>"
fclose(fd); "</table></td></tr><tr></tr><tr><td colspan=\"2\">"
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "File sending failed!"); "<button style=\"font-size:16px; padding: 5px 10px\" id=\"dirup\" type=\"button\" onclick=\"dirup()\""
return ESP_FAIL; "disabled>&#129145; Directory up</button><span style=\"padding-left:15px\" id=\"currentpath\">"
} "</span></td></tr>");
} httpd_resp_sendstr_chunk(req, "</table>");
} while (chunksize != 0);
fclose(fd); httpd_resp_sendstr_chunk(req, "<script type=\"text/javascript\" src=\"/file_server.js\"></script>");
// ESP_LOGI(TAG, "File sending complete"); httpd_resp_sendstr_chunk(req, "<script type=\"text/javascript\">initFileServer();</script>");
}
///////////////////////////////
std::string _zw = std::string(dirpath); std::string _zw = std::string(dirpath);
_zw = _zw.substr(8, _zw.length() - 8); _zw = _zw.substr(8, _zw.length() - 8);
_zw = "/delete/" + _zw + "?task=deldircontent"; _zw = "/delete/" + _zw + "?task=deldircontent";
// Send file-list table definition and column labels
httpd_resp_sendstr_chunk(req, "<table id=\"files_table\">"
"<col width=\"800px\"><col width=\"300px\"><col width=\"300px\"><col width=\"100px\">"
"<thead><tr><th>Name</th><th>Type</th><th>Size</th>");
/* Send file-list table definition and column labels */
httpd_resp_sendstr_chunk(req,
"<table id=\"files_table\">"
"<col width=\"800px\" /><col width=\"300px\" /><col width=\"300px\" /><col width=\"100px\" />"
"<thead><tr><th>Name</th><th>Type</th><th>Size</th>");
if (!readonly) { if (!readonly) {
httpd_resp_sendstr_chunk(req, "<th>" httpd_resp_sendstr_chunk(req, "<th><form method=\"post\" action=\"");
"<form method=\"post\" action=\"");
httpd_resp_sendstr_chunk(req, _zw.c_str()); httpd_resp_sendstr_chunk(req, _zw.c_str());
httpd_resp_sendstr_chunk(req, httpd_resp_sendstr_chunk(req, "\"><button type=\"submit\">DELETE ALL!</button></form></th></tr>");
"\"><button type=\"submit\">DELETE ALL!</button></form>"
"</th></tr>");
} }
httpd_resp_sendstr_chunk(req, "</thead><tbody>\n"); httpd_resp_sendstr_chunk(req, "</thead><tbody>\n");
/* Iterate over all files / folders and fetch their names and sizes */ // Iterate over all files / folders and fetch their names and sizes
while ((entry = readdir(dir)) != NULL) { while ((entry = readdir(pdir)) != NULL) {
if (strcmp("wlan.ini", entry->d_name) != 0 ) // wlan.ini soll nicht angezeigt werden! // wlan.ini soll nicht angezeigt werden!
{ if (strcmp("wlan.ini", entry->d_name) != 0) {
entrytype = (entry->d_type == DT_DIR ? "directory" : "file"); entrytype = (entry->d_type == DT_DIR ? "directory" : "file");
strlcpy(entrypath + dirpath_len, entry->d_name, sizeof(entrypath) - dirpath_len); strlcpy(entrypath + dirpath_len, entry->d_name, sizeof(entrypath) - dirpath_len);
ESP_LOGD(TAG, "Entrypath: %s", entrypath); ESP_LOGD(TAG, "Entrypath: %s", entrypath);
if (stat(entrypath, &entry_stat) == -1) { if (stat(entrypath, &entry_stat) == -1) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to stat " + string(entrytype) + ": " + string(entry->d_name)); LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to stat " + std::string(entrytype) + ": " + std::string(entry->d_name));
continue; continue;
} }
@@ -282,22 +277,25 @@ static esp_err_t http_resp_dir_html(httpd_req_t *req, const char *dirpath, const
} }
} }
ESP_LOGI(TAG, "Found %s: %s (%s bytes)", entrytype, entry->d_name, entrysize); ESP_LOGD(TAG, "Found %s: %s (%s bytes)", entrytype, entry->d_name, entrysize);
/* Send chunk of HTML file containing table entries with file name and size */ // Send chunk of HTML file containing table entries with file name and size
httpd_resp_sendstr_chunk(req, "<tr><td><a href=\""); httpd_resp_sendstr_chunk(req, "<tr><td><a href=\"");
httpd_resp_sendstr_chunk(req, "/fileserver"); httpd_resp_sendstr_chunk(req, "/fileserver");
httpd_resp_sendstr_chunk(req, uripath); httpd_resp_sendstr_chunk(req, uripath);
httpd_resp_sendstr_chunk(req, entry->d_name); httpd_resp_sendstr_chunk(req, entry->d_name);
if (entry->d_type == DT_DIR) { if (entry->d_type == DT_DIR) {
httpd_resp_sendstr_chunk(req, "/"); httpd_resp_sendstr_chunk(req, "/");
} }
httpd_resp_sendstr_chunk(req, "\">"); httpd_resp_sendstr_chunk(req, "\">");
httpd_resp_sendstr_chunk(req, entry->d_name); httpd_resp_sendstr_chunk(req, entry->d_name);
httpd_resp_sendstr_chunk(req, "</a></td><td>"); httpd_resp_sendstr_chunk(req, "</a></td><td>");
httpd_resp_sendstr_chunk(req, entrytype); httpd_resp_sendstr_chunk(req, entrytype);
httpd_resp_sendstr_chunk(req, "</td><td>"); httpd_resp_sendstr_chunk(req, "</td><td>");
httpd_resp_sendstr_chunk(req, entrysize); httpd_resp_sendstr_chunk(req, entrysize);
if (!readonly) { if (!readonly) {
httpd_resp_sendstr_chunk(req, "</td><td>"); httpd_resp_sendstr_chunk(req, "</td><td>");
httpd_resp_sendstr_chunk(req, "<form method=\"post\" action=\"/delete"); httpd_resp_sendstr_chunk(req, "<form method=\"post\" action=\"/delete");
@@ -305,31 +303,28 @@ static esp_err_t http_resp_dir_html(httpd_req_t *req, const char *dirpath, const
httpd_resp_sendstr_chunk(req, entry->d_name); httpd_resp_sendstr_chunk(req, entry->d_name);
httpd_resp_sendstr_chunk(req, "\"><button type=\"submit\">Delete</button></form>"); httpd_resp_sendstr_chunk(req, "\"><button type=\"submit\">Delete</button></form>");
} }
httpd_resp_sendstr_chunk(req, "</td></tr>\n"); httpd_resp_sendstr_chunk(req, "</td></tr>\n");
} }
} }
closedir(dir);
/* Finish the file list table */ closedir(pdir);
// Finish the file list table
httpd_resp_sendstr_chunk(req, "</tbody></table>"); httpd_resp_sendstr_chunk(req, "</tbody></table>");
/* Send remaining chunk of HTML file to complete it */ // Send remaining chunk of HTML file to complete it
httpd_resp_sendstr_chunk(req, "</body></html>"); httpd_resp_sendstr_chunk(req, "</body></html>");
/* Send empty chunk to signal HTTP response completion */ // Send empty chunk to signal HTTP response completion
httpd_resp_sendstr_chunk(req, NULL); httpd_resp_sendstr_chunk(req, NULL);
return ESP_OK; return ESP_OK;
} }
/*
#define IS_FILE_EXT(filename, ext) \
(strcasecmp(&filename[strlen(filename) - sizeof(ext) + 1], ext) == 0)
*/
static esp_err_t logfileact_get_full_handler(httpd_req_t *req) { static esp_err_t logfileact_get_full_handler(httpd_req_t *req) {
return send_logfile(req, true); return send_logfile(req, true);
} }
static esp_err_t logfileact_get_last_part_handler(httpd_req_t *req) { static esp_err_t logfileact_get_last_part_handler(httpd_req_t *req) {
return send_logfile(req, false); return send_logfile(req, false);
} }
@@ -338,7 +333,6 @@ static esp_err_t datafileact_get_full_handler(httpd_req_t *req) {
return send_datafile(req, true); return send_datafile(req, true);
} }
static esp_err_t datafileact_get_last_part_handler(httpd_req_t *req) { static esp_err_t datafileact_get_last_part_handler(httpd_req_t *req) {
return send_datafile(req, false); return send_datafile(req, false);
} }
@@ -423,7 +417,6 @@ static esp_err_t send_datafile(httpd_req_t *req, bool send_full_file)
return ESP_OK; return ESP_OK;
} }
static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file) static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file)
{ {
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "log_get_last_part_handler"); LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "log_get_last_part_handler");
@@ -509,7 +502,6 @@ static esp_err_t send_logfile(httpd_req_t *req, bool send_full_file)
return ESP_OK; return ESP_OK;
} }
/* Handler to download a file kept on the server */ /* Handler to download a file kept on the server */
static esp_err_t download_get_handler(httpd_req_t *req) static esp_err_t download_get_handler(httpd_req_t *req)
{ {
@@ -527,7 +519,6 @@ static esp_err_t download_get_handler(httpd_req_t *req)
// filename = get_path_from_uri(filepath, ((struct file_server_data *)req->user_ctx)->base_path, // filename = get_path_from_uri(filepath, ((struct file_server_data *)req->user_ctx)->base_path,
// req->uri, sizeof(filepath)); // req->uri, sizeof(filepath));
if (!filename) { if (!filename) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Filename is too long"); LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Filename is too long");
/* Respond with 414 Error */ /* Respond with 414 Error */
@@ -758,7 +749,6 @@ static esp_err_t upload_post_handler(httpd_req_t *req)
httpd_resp_set_hdr(req, "Location", directory.c_str()); httpd_resp_set_hdr(req, "Location", directory.c_str());
httpd_resp_sendstr(req, "File uploaded successfully"); httpd_resp_sendstr(req, "File uploaded successfully");
return ESP_OK; return ESP_OK;
} }
@@ -769,7 +759,6 @@ static esp_err_t delete_post_handler(httpd_req_t *req)
char filepath[FILE_PATH_MAX]; char filepath[FILE_PATH_MAX];
struct stat file_stat; struct stat file_stat;
////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////
char _query[200]; char _query[200];
char _valuechar[30]; char _valuechar[30];
@@ -892,13 +881,11 @@ static esp_err_t delete_post_handler(httpd_req_t *req)
} }
} }
httpd_resp_set_hdr(req, "Location", directory.c_str()); httpd_resp_set_hdr(req, "Location", directory.c_str());
httpd_resp_sendstr(req, "File successfully deleted"); httpd_resp_sendstr(req, "File successfully deleted");
return ESP_OK; return ESP_OK;
} }
void delete_all_in_directory(std::string _directory) void delete_all_in_directory(std::string _directory)
{ {
struct dirent *entry; struct dirent *entry;
@@ -924,7 +911,7 @@ void delete_all_in_directory(std::string _directory)
closedir(dir); closedir(dir);
} }
std::string unzip_new(std::string _in_zip_file, std::string _target_zip, std::string _target_bin, std::string _main, bool _initial_setup) std::string unzip_new(std::string _in_zip_file, std::string _html_tmp, std::string _html_final, std::string _target_bin, std::string _main, bool _initial_setup)
{ {
int i, sort_iter; int i, sort_iter;
mz_bool status; mz_bool status;
@@ -1006,10 +993,15 @@ std::string unzip_new(std::string _in_zip_file, std::string _target_zip, std::st
} }
else else
{ {
zw = _target_zip + zw; zw = _html_tmp + zw;
} }
} }
// files in the html folder shall be redirected to the temporary html folder
if (zw.find(_html_final) == 0) {
FindReplace(zw, _html_final, _html_tmp);
}
string filename_zw = zw + SUFFIX_ZW; string filename_zw = zw + SUFFIX_ZW;
@@ -1136,8 +1128,6 @@ void unzip(std::string _in_zip_file, std::string _target_directory){
ESP_LOGD(TAG, "Success."); ESP_LOGD(TAG, "Success.");
} }
void register_server_file_uri(httpd_handle_t server, const char *base_path) void register_server_file_uri(httpd_handle_t server, const char *base_path)
{ {
static struct file_server_data *server_data = NULL; static struct file_server_data *server_data = NULL;
@@ -1163,8 +1153,6 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
strlcpy(server_data->base_path, base_path, strlcpy(server_data->base_path, base_path,
sizeof(server_data->base_path)); sizeof(server_data->base_path));
/* URI handler for getting uploaded files */ /* URI handler for getting uploaded files */
// char zw[sizeof(serverprefix)+1]; // char zw[sizeof(serverprefix)+1];
// strcpy(zw, serverprefix); // strcpy(zw, serverprefix);
@@ -1174,25 +1162,23 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_download = { httpd_uri_t file_download = {
.uri = "/fileserver*", // Match all URIs of type /path/to/file .uri = "/fileserver*", // Match all URIs of type /path/to/file
.method = HTTP_GET, .method = HTTP_GET,
.handler = download_get_handler, .handler = APPLY_BASIC_AUTH_FILTER(download_get_handler),
.user_ctx = server_data // Pass server data as context .user_ctx = server_data // Pass server data as context
}; };
httpd_register_uri_handler(server, &file_download); httpd_register_uri_handler(server, &file_download);
httpd_uri_t file_datafileact = { httpd_uri_t file_datafileact = {
.uri = "/datafileact", // Match all URIs of type /path/to/file .uri = "/datafileact", // Match all URIs of type /path/to/file
.method = HTTP_GET, .method = HTTP_GET,
.handler = datafileact_get_full_handler, .handler = APPLY_BASIC_AUTH_FILTER(datafileact_get_full_handler),
.user_ctx = server_data // Pass server data as context .user_ctx = server_data // Pass server data as context
}; };
httpd_register_uri_handler(server, &file_datafileact); httpd_register_uri_handler(server, &file_datafileact);
httpd_uri_t file_datafile_last_part_handle = { httpd_uri_t file_datafile_last_part_handle = {
.uri = "/data", // Match all URIs of type /path/to/file .uri = "/data", // Match all URIs of type /path/to/file
.method = HTTP_GET, .method = HTTP_GET,
.handler = datafileact_get_last_part_handler, .handler = APPLY_BASIC_AUTH_FILTER(datafileact_get_last_part_handler),
.user_ctx = server_data // Pass server data as context .user_ctx = server_data // Pass server data as context
}; };
httpd_register_uri_handler(server, &file_datafile_last_part_handle); httpd_register_uri_handler(server, &file_datafile_last_part_handle);
@@ -1200,26 +1186,24 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_logfileact = { httpd_uri_t file_logfileact = {
.uri = "/logfileact", // Match all URIs of type /path/to/file .uri = "/logfileact", // Match all URIs of type /path/to/file
.method = HTTP_GET, .method = HTTP_GET,
.handler = logfileact_get_full_handler, .handler = APPLY_BASIC_AUTH_FILTER(logfileact_get_full_handler),
.user_ctx = server_data // Pass server data as context .user_ctx = server_data // Pass server data as context
}; };
httpd_register_uri_handler(server, &file_logfileact); httpd_register_uri_handler(server, &file_logfileact);
httpd_uri_t file_logfile_last_part_handle = { httpd_uri_t file_logfile_last_part_handle = {
.uri = "/log", // Match all URIs of type /path/to/file .uri = "/log", // Match all URIs of type /path/to/file
.method = HTTP_GET, .method = HTTP_GET,
.handler = logfileact_get_last_part_handler, .handler = APPLY_BASIC_AUTH_FILTER(logfileact_get_last_part_handler),
.user_ctx = server_data // Pass server data as context .user_ctx = server_data // Pass server data as context
}; };
httpd_register_uri_handler(server, &file_logfile_last_part_handle); httpd_register_uri_handler(server, &file_logfile_last_part_handle);
/* URI handler for uploading files to server */ /* URI handler for uploading files to server */
httpd_uri_t file_upload = { httpd_uri_t file_upload = {
.uri = "/upload/*", // Match all URIs of type /upload/path/to/file .uri = "/upload/*", // Match all URIs of type /upload/path/to/file
.method = HTTP_POST, .method = HTTP_POST,
.handler = upload_post_handler, .handler = APPLY_BASIC_AUTH_FILTER(upload_post_handler),
.user_ctx = server_data // Pass server data as context .user_ctx = server_data // Pass server data as context
}; };
httpd_register_uri_handler(server, &file_upload); httpd_register_uri_handler(server, &file_upload);
@@ -1228,9 +1212,8 @@ void register_server_file_uri(httpd_handle_t server, const char *base_path)
httpd_uri_t file_delete = { httpd_uri_t file_delete = {
.uri = "/delete/*", // Match all URIs of type /delete/path/to/file .uri = "/delete/*", // Match all URIs of type /delete/path/to/file
.method = HTTP_POST, .method = HTTP_POST,
.handler = delete_post_handler, .handler = APPLY_BASIC_AUTH_FILTER(delete_post_handler),
.user_ctx = server_data // Pass server data as context .user_ctx = server_data // Pass server data as context
}; };
httpd_register_uri_handler(server, &file_delete); httpd_register_uri_handler(server, &file_delete);
} }

View File

@@ -9,7 +9,7 @@
void register_server_file_uri(httpd_handle_t server, const char *base_path); void register_server_file_uri(httpd_handle_t server, const char *base_path);
void unzip(std::string _in_zip_file, std::string _target_directory); void unzip(std::string _in_zip_file, std::string _target_directory);
std::string unzip_new(std::string _in_zip_file, std::string _target_zip, std::string _target_bin, std::string _main = "/sdcard/", bool _initial_setup = false); std::string unzip_new(std::string _in_zip_file, std::string _html_tmp, std::string _html_final, std::string _target_bin, std::string _main = "/sdcard/", bool _initial_setup = false);
void delete_all_in_directory(std::string _directory); void delete_all_in_directory(std::string _directory);

View File

@@ -16,77 +16,101 @@ extern "C" {
#include "esp_err.h" #include "esp_err.h"
#include "esp_log.h" #include "esp_log.h"
#include "Helper.h" #include "Helper.h"
#include "esp_http_server.h" #include "esp_http_server.h"
#include "../../include/defines.h" #include "../../include/defines.h"
static const char *TAG = "SERVER HELP"; static const char *TAG = "SERVER HELP";
char scratch[SERVER_HELPER_SCRATCH_BUFSIZE]; char scratch[SERVER_HELPER_SCRATCH_BUFSIZE];
bool endsWith(std::string const &str, std::string const &suffix)
bool endsWith(std::string const &str, std::string const &suffix) { {
if (str.length() < suffix.length()) { if (str.length() < suffix.length()) {
return false; return false;
} }
return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0; return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
} }
esp_err_t send_file(httpd_req_t *req, std::string filename) esp_err_t send_file(httpd_req_t *req, std::string filename)
{ {
std::string _filename_old = filename;
struct stat file_stat;
bool _gz_file_exists = false;
ESP_LOGD(TAG, "old filename: %s", filename.c_str());
std::string _filename_temp = std::string(filename) + ".gz";
// Checks whether the file is available as .gz
if (stat(_filename_temp.c_str(), &file_stat) == 0) {
filename = _filename_temp;
ESP_LOGD(TAG, "new filename: %s", filename.c_str());
_gz_file_exists = true;
}
FILE *fd = fopen(filename.c_str(), "r"); FILE *fd = fopen(filename.c_str(), "r");
if (!fd) { if (!fd) {
ESP_LOGE(TAG, "Failed to read file: %s", filename.c_str()); ESP_LOGE(TAG, "Failed to read file: %s", filename.c_str());
/* Respond with 404 Error */ /* Respond with 404 Error */
httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404()); httpd_resp_send_err(req, HTTPD_404_NOT_FOUND, get404());
return ESP_FAIL; return ESP_FAIL;
} }
ESP_LOGD(TAG, "Sending file: %s ...", filename.c_str()); ESP_LOGD(TAG, "Sending file: %s ...", filename.c_str());
// httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
/* For all files with the following file extention tell /* For all files with the following file extention tell the webbrowser to cache them for 12h */
the webbrowser to cache them for 24h */
if (endsWith(filename, ".html") || if (endsWith(filename, ".html") ||
endsWith(filename, ".htm") || endsWith(filename, ".htm") ||
endsWith(filename, ".xml") ||
endsWith(filename, ".css") || endsWith(filename, ".css") ||
endsWith(filename, ".js") || endsWith(filename, ".js") ||
endsWith(filename, ".map") || endsWith(filename, ".map") ||
endsWith(filename, ".jpg") || endsWith(filename, ".jpg") ||
endsWith(filename, ".jpeg") || endsWith(filename, ".jpeg") ||
endsWith(filename, ".ico") || endsWith(filename, ".ico") ||
endsWith(filename, ".png")) { endsWith(filename, ".png") ||
endsWith(filename, ".gif") ||
if (filename == "/sdcard/html/setup.html") { // endsWith(filename, ".zip") ||
endsWith(filename, ".gz")) {
if (filename == "/sdcard/html/setup.html") {
httpd_resp_set_hdr(req, "Clear-Site-Data", "\"*\""); httpd_resp_set_hdr(req, "Clear-Site-Data", "\"*\"");
set_content_type_from_file(req, filename.c_str());
}
else if (_gz_file_exists) {
httpd_resp_set_hdr(req, "Cache-Control", "max-age=43200");
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
set_content_type_from_file(req, _filename_old.c_str());
} }
else { else {
httpd_resp_set_hdr(req, "Cache-Control", "max-age=86400"); httpd_resp_set_hdr(req, "Cache-Control", "max-age=43200");
set_content_type_from_file(req, filename.c_str());
} }
} }
else {
set_content_type_from_file(req, filename.c_str()); set_content_type_from_file(req, filename.c_str());
}
/* Retrieve the pointer to scratch buffer for temporary storage */ /* Retrieve the pointer to scratch buffer for temporary storage */
char *chunk = scratch; char *chunk = scratch;
size_t chunksize; size_t chunksize;
do {
do {
/* Read file in chunks into the scratch buffer */ /* Read file in chunks into the scratch buffer */
chunksize = fread(chunk, 1, SERVER_HELPER_SCRATCH_BUFSIZE, fd); chunksize = fread(chunk, 1, SERVER_HELPER_SCRATCH_BUFSIZE, fd);
/* Send the buffer contents as HTTP response chunk */ /* Send the buffer contents as HTTP response chunk */
if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK) { if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK) {
fclose(fd); fclose(fd);
ESP_LOGE(TAG, "File sending failed!"); ESP_LOGE(TAG, "File sending failed!");
/* Abort sending file */ /* Abort sending file */
httpd_resp_sendstr_chunk(req, NULL); httpd_resp_sendstr_chunk(req, NULL);
/* Respond with 500 Internal Server Error */ /* Respond with 500 Internal Server Error */
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file"); httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to send file");
return ESP_FAIL; return ESP_FAIL;
} }
@@ -95,13 +119,11 @@ esp_err_t send_file(httpd_req_t *req, std::string filename)
/* Close file after sending complete */ /* Close file after sending complete */
fclose(fd); fclose(fd);
ESP_LOGD(TAG, "File sending complete"); ESP_LOGD(TAG, "File sending complete");
return ESP_OK; return ESP_OK;
} }
/* Copies the full path into destination buffer and returns /* Copies the full path into destination buffer and returns
* pointer to path (skipping the preceding base path) */ * pointer to path (skipping the preceding base path) */
const char* get_path_from_uri(char *dest, const char *base_path, const char *uri, size_t destsize) const char* get_path_from_uri(char *dest, const char *base_path, const char *uri, size_t destsize)
@@ -131,25 +153,49 @@ const char* get_path_from_uri(char *dest, const char *base_path, const char *uri
return dest + base_pathlen; return dest + base_pathlen;
} }
/* Set HTTP response content type according to file extension */ /* Set HTTP response content type according to file extension */
esp_err_t set_content_type_from_file(httpd_req_t *req, const char *filename) esp_err_t set_content_type_from_file(httpd_req_t *req, const char *filename)
{ {
if (IS_FILE_EXT(filename, ".pdf")) { if (IS_FILE_EXT(filename, ".pdf")) {
return httpd_resp_set_type(req, "application/pdf"); return httpd_resp_set_type(req, "application/x-pdf");
} else if (IS_FILE_EXT(filename, ".html")) { }
else if (IS_FILE_EXT(filename, ".htm")) {
return httpd_resp_set_type(req, "text/html"); return httpd_resp_set_type(req, "text/html");
} else if (IS_FILE_EXT(filename, ".jpeg")) { }
else if (IS_FILE_EXT(filename, ".html")) {
return httpd_resp_set_type(req, "text/html");
}
else if (IS_FILE_EXT(filename, ".jpeg")) {
return httpd_resp_set_type(req, "image/jpeg"); return httpd_resp_set_type(req, "image/jpeg");
} else if (IS_FILE_EXT(filename, ".jpg")) { }
else if (IS_FILE_EXT(filename, ".jpg")) {
return httpd_resp_set_type(req, "image/jpeg"); return httpd_resp_set_type(req, "image/jpeg");
} else if (IS_FILE_EXT(filename, ".ico")) { }
else if (IS_FILE_EXT(filename, ".gif")) {
return httpd_resp_set_type(req, "image/gif");
}
else if (IS_FILE_EXT(filename, ".png")) {
return httpd_resp_set_type(req, "image/png");
}
else if (IS_FILE_EXT(filename, ".ico")) {
return httpd_resp_set_type(req, "image/x-icon"); return httpd_resp_set_type(req, "image/x-icon");
} else if (IS_FILE_EXT(filename, ".js")) { }
return httpd_resp_set_type(req, "text/javascript"); else if (IS_FILE_EXT(filename, ".js")) {
} else if (IS_FILE_EXT(filename, ".css")) { return httpd_resp_set_type(req, "application/javascript");
}
else if (IS_FILE_EXT(filename, ".css")) {
return httpd_resp_set_type(req, "text/css"); return httpd_resp_set_type(req, "text/css");
} }
else if (IS_FILE_EXT(filename, ".xml")) {
return httpd_resp_set_type(req, "text/xml");
}
else if (IS_FILE_EXT(filename, ".zip")) {
return httpd_resp_set_type(req, "application/x-zip");
}
else if (IS_FILE_EXT(filename, ".gz")) {
return httpd_resp_set_type(req, "application/x-gzip");
}
/* This is a limited set only */ /* This is a limited set only */
/* For any other type always set as plain text */ /* For any other type always set as plain text */
return httpd_resp_set_type(req, "text/plain"); return httpd_resp_set_type(req, "text/plain");

View File

@@ -42,6 +42,7 @@ https://docs.espressif.com/projects/esp-idf/en/latest/esp32/migration-guides/rel
#include "Helper.h" #include "Helper.h"
#include "statusled.h" #include "statusled.h"
#include "basic_auth.h"
#include "../../include/defines.h" #include "../../include/defines.h"
/*an ota data write buffer ready to write to the flash*/ /*an ota data write buffer ready to write to the flash*/
@@ -75,17 +76,32 @@ void task_do_Update_ZIP(void *pvParameter)
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "File: " + _file_name_update + " Filetype: " + filetype); LogFile.WriteToFile(ESP_LOG_INFO, TAG, "File: " + _file_name_update + " Filetype: " + filetype);
if (filetype == "ZIP") if (filetype == "ZIP")
{ {
std::string in, out, outbin, zw, retfirmware; std::string in, outHtml, outHtmlTmp, outHtmlOld, outbin, zw, retfirmware;
out = "/sdcard/html"; outHtml = "/sdcard/html";
outHtmlTmp = "/sdcard/html_tmp";
outHtmlOld = "/sdcard/html_old";
outbin = "/sdcard/firmware"; outbin = "/sdcard/firmware";
retfirmware = unzip_new(_file_name_update, out+"/", outbin+"/", "/sdcard/", initial_setup); /* Remove the old and tmp html folder in case they still exist */
removeFolder(outHtmlTmp.c_str(), TAG);
removeFolder(outHtmlOld.c_str(), TAG);
/* Extract the ZIP file. The content of the html folder gets extracted to the temporar folder html-temp. */
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Extracting ZIP file " + _file_name_update + "...");
retfirmware = unzip_new(_file_name_update, outHtmlTmp+"/", outHtml+"/", outbin+"/", "/sdcard/", initial_setup);
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Files unzipped."); LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Files unzipped.");
/* ZIP file got extracted, replace the old html folder with the new one */
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Renaming folder " + outHtml + " to " + outHtmlOld + "...");
::rename(outHtml.c_str(), outHtmlOld.c_str());
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Renaming folder " + outHtmlTmp + " to " + outHtml + "...");
::rename(outHtmlTmp.c_str(), outHtml.c_str());
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Deleting folder " + outHtmlOld + "...");
removeFolder(outHtmlOld.c_str(), TAG);
if (retfirmware.length() > 0) if (retfirmware.length() > 0)
{ {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Found firmware.bin"); LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Found firmware.bin");
@@ -433,7 +449,6 @@ esp_err_t handler_ota_update(httpd_req_t *req)
return ESP_OK; return ESP_OK;
} }
if ((filetype == "TFLITE") || (filetype == "TFL")) if ((filetype == "TFLITE") || (filetype == "TFL"))
{ {
std::string out = "/sdcard/config/" + getFileFullFileName(fn); std::string out = "/sdcard/config/" + getFileFullFileName(fn);
@@ -690,13 +705,13 @@ void register_server_ota_sdcard_uri(httpd_handle_t server)
httpd_uri_t camuri = { }; httpd_uri_t camuri = { };
camuri.method = HTTP_GET; camuri.method = HTTP_GET;
camuri.uri = "/ota"; camuri.uri = "/ota";
camuri.handler = handler_ota_update; camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_ota_update);
camuri.user_ctx = (void*) "Do OTA"; camuri.user_ctx = (void*) "Do OTA";
httpd_register_uri_handler(server, &camuri); httpd_register_uri_handler(server, &camuri);
camuri.method = HTTP_GET; camuri.method = HTTP_GET;
camuri.uri = "/reboot"; camuri.uri = "/reboot";
camuri.handler = handler_reboot; camuri.handler = APPLY_BASIC_AUTH_FILTER(handler_reboot);
camuri.user_ctx = (void*) "Reboot"; camuri.user_ctx = (void*) "Reboot";
httpd_register_uri_handler(server, &camuri); 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} idf_component_register(SRCS ${app_sources}
INCLUDE_DIRS "." INCLUDE_DIRS "."
REQUIRES esp_timer esp_wifi jomjol_tfliteclass jomjol_helper jomjol_controlcamera jomjol_mqtt jomjol_influxdb jomjol_fileserver_ota jomjol_image_proc jomjol_wlan) 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)

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -11,10 +11,10 @@ enum t_CNNType {
AutoDetect, AutoDetect,
Analogue, Analogue,
Analogue100, Analogue100,
Digital, Digit,
DigitalHyprid10, DigitHyprid10,
DoubleHyprid10, DoubleHyprid10,
Digital100, Digit100,
None None
}; };
@@ -26,15 +26,6 @@ protected:
std::vector<general*> GENERAL; std::vector<general*> GENERAL;
float CNNGoodThreshold; float CNNGoodThreshold;
//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; string cnnmodelfile;
int modelxsize, modelysize, modelchannel; int modelxsize, modelysize, modelchannel;
bool isLogImageSelect; bool isLogImageSelect;
@@ -44,8 +35,8 @@ protected:
bool SaveAllFiles; bool SaveAllFiles;
int PointerEvalAnalogNew(float zahl, int numeral_preceder); int PointerEvalAnalogNew(float zahl, int numeral_preceder);
int PointerEvalAnalogToDigitNew(float zahl, float numeral_preceder, int eval_predecessors, float analogDigitalTransitionStart); 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 analogDigitalTransitionStart=9.2); int PointerEvalHybridNew(float zahl, float number_of_predecessors, int eval_predecessors, bool Analog_Predecessors = false, float AnalogToDigitTransitionStart=9.2);
@@ -61,7 +52,7 @@ public:
bool doFlow(string time); bool doFlow(string time);
string getHTMLSingleStep(string host); string getHTMLSingleStep(string host);
string getReadout(int _analog, bool _extendedResolution = false, int prev = -1, float _before_narrow_Analog = -1, float analogDigitalTransitionStart=9.2); string getReadout(int _analog, bool _extendedResolution = false, int prev = -1, float _before_narrow_Analog = -1, float AnalogToDigitTransitionStart=9.2);
string getReadoutRawString(int _analog); string getReadoutRawString(int _analog);

File diff suppressed because it is too large Load Diff

View File

@@ -17,6 +17,9 @@
#include "ClassFlowInfluxDB.h" #include "ClassFlowInfluxDB.h"
#include "ClassFlowInfluxDBv2.h" #include "ClassFlowInfluxDBv2.h"
#endif //ENABLE_INFLUXDB #endif //ENABLE_INFLUXDB
#ifdef ENABLE_WEBHOOK
#include "ClassFlowWebhook.h"
#endif //ENABLE_WEBHOOK
#include "ClassFlowCNNGeneral.h" #include "ClassFlowCNNGeneral.h"
class ClassFlowControll : class ClassFlowControll :
@@ -52,12 +55,13 @@ public:
string GetPrevalue(std::string _number = ""); string GetPrevalue(std::string _number = "");
bool ReadParameter(FILE* pfile, string& aktparamgraph); bool ReadParameter(FILE* pfile, string& aktparamgraph);
string getJSON(); string getJSON();
const std::vector<NumberPost*> &getNumbers();
string getNumbersName(); string getNumbersName();
string TranslateAktstatus(std::string _input); string TranslateAktstatus(std::string _input);
#ifdef ALGROI_LOAD_FROM_MEM_AS_JPG #ifdef ALGROI_LOAD_FROM_MEM_AS_JPG
void DigitalDrawROI(CImageBasis *_zw); void DigitDrawROI(CImageBasis *_zw);
void AnalogDrawROI(CImageBasis *_zw); void AnalogDrawROI(CImageBasis *_zw);
#endif #endif
@@ -73,10 +77,10 @@ public:
std::string* getActStatus(); std::string* getActStatus();
void setActStatus(std::string _aktstatus); void setActStatus(std::string _aktstatus);
std::vector<HTMLInfo*> GetAllDigital(); std::vector<HTMLInfo*> GetAllDigit();
std::vector<HTMLInfo*> GetAllAnalog(); std::vector<HTMLInfo*> GetAllAnalog();
t_CNNType GetTypeDigital(); t_CNNType GetTypeDigit();
t_CNNType GetTypeAnalog(); t_CNNType GetTypeAnalog();
#ifdef ENABLE_MQTT #ifdef ENABLE_MQTT

View File

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

View File

@@ -117,7 +117,12 @@ bool ClassFlowInfluxDB::ReadParameter(FILE* pfile, string& aktparamgraph)
{ {
// ESP_LOGD(TAG, "Init InfluxDB with uri: %s, measurement: %s, user: %s, password: %s", uri.c_str(), measurement.c_str(), user.c_str(), password.c_str()); // ESP_LOGD(TAG, "Init InfluxDB with uri: %s, measurement: %s, user: %s, password: %s", uri.c_str(), measurement.c_str(), user.c_str(), password.c_str());
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init InfluxDB with uri: " + uri + ", user: " + user + ", password: " + password); LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init InfluxDB with uri: " + uri + ", user: " + user + ", password: " + password);
InfluxDBInit(uri, database, user, password);
/////////////////////// NEW //////////////////////////
// InfluxDBInit(uri, database, user, password);
influxDB.InfluxDBInitV1(uri, database, user, password);
/////////////////////// NEW //////////////////////////
InfluxDBenable = true; InfluxDBenable = true;
} else { } else {
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "InfluxDB init skipped as we are missing some parameters"); LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "InfluxDB init skipped as we are missing some parameters");
@@ -169,7 +174,12 @@ bool ClassFlowInfluxDB::doFlow(string zwtime)
} }
if (result.length() > 0) if (result.length() > 0)
InfluxDBPublish(measurement, namenumber, result, timeutc); //////////////////////// NEW //////////////////////////
// InfluxDBPublish(measurement, namenumber, result, timeutc);
influxDB.InfluxDBPublish(measurement, namenumber, result, timeutc);
//////////////////////// NEW //////////////////////////
} }
} }

View File

@@ -8,6 +8,7 @@
#include "ClassFlow.h" #include "ClassFlow.h"
#include "ClassFlowPostProcessing.h" #include "ClassFlowPostProcessing.h"
#include "interface_influxdb.h"
#include <string> #include <string>
@@ -21,6 +22,8 @@ protected:
std::string user, password; std::string user, password;
bool InfluxDBenable; bool InfluxDBenable;
InfluxDB influxDB;
void SetInitialParameter(void); void SetInitialParameter(void);
void handleFieldname(string _decsep, string _value); void handleFieldname(string _decsep, string _value);

View File

@@ -123,7 +123,14 @@ bool ClassFlowInfluxDBv2::ReadParameter(FILE* pfile, string& aktparamgraph)
{ {
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init InfluxDB with uri: " + uri + ", org: " + dborg + ", token: *****"); LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init InfluxDB with uri: " + uri + ", org: " + dborg + ", token: *****");
// printf("vor V2 Init\n"); // printf("vor V2 Init\n");
InfluxDB_V2_Init(uri, bucket, dborg, dbtoken);
////////////////////////////////////////// NEW ////////////////////////////////////////////
// InfluxDB_V2_Init(uri, bucket, dborg, dbtoken);
// InfluxDB_V2_Init(uri, bucket, dborg, dbtoken);
influxdb.InfluxDBInitV2(uri, bucket, dborg, dbtoken);
////////////////////////////////////////// NEW ////////////////////////////////////////////
// printf("nach V2 Init\n"); // printf("nach V2 Init\n");
InfluxDBenable = true; InfluxDBenable = true;
} else { } else {
@@ -232,7 +239,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()); 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) if (result.length() > 0)
InfluxDB_V2_Publish(measurement, namenumber, result, resulttimeutc); influxdb.InfluxDBPublish(measurement, namenumber, result, resulttimeutc);
// InfluxDB_V2_Publish(measurement, namenumber, result, resulttimeutc);
} }
} }

View File

@@ -9,6 +9,8 @@
#include "ClassFlowPostProcessing.h" #include "ClassFlowPostProcessing.h"
#include "interface_influxdb.h"
#include <string> #include <string>
class ClassFlowInfluxDBv2 : class ClassFlowInfluxDBv2 :
@@ -21,6 +23,8 @@ protected:
ClassFlowPostProcessing* flowpostprocessing; ClassFlowPostProcessing* flowpostprocessing;
bool InfluxDBenable; bool InfluxDBenable;
InfluxDB influxdb;
void SetInitialParameter(void); void SetInitialParameter(void);
void handleFieldname(string _decsep, string _value); void handleFieldname(string _decsep, string _value);

View File

@@ -40,6 +40,7 @@ void ClassFlowMQTT::SetInitialParameter(void)
caCertFilename = ""; caCertFilename = "";
clientCertFilename = ""; clientCertFilename = "";
clientKeyFilename = ""; clientKeyFilename = "";
validateServerCert = true;
clientname = wlan_config.hostname; clientname = wlan_config.hostname;
OldValue = ""; OldValue = "";
@@ -51,6 +52,7 @@ void ClassFlowMQTT::SetInitialParameter(void)
ListFlowControll = NULL; ListFlowControll = NULL;
disabled = false; disabled = false;
keepAlive = 25*60; keepAlive = 25*60;
domoticzintopic = "";
} }
ClassFlowMQTT::ClassFlowMQTT() ClassFlowMQTT::ClassFlowMQTT()
@@ -105,43 +107,46 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph)) while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
{ {
splitted = ZerlegeZeile(aktparamgraph); splitted = ZerlegeZeile(aktparamgraph);
if ((toUpper(splitted[0]) == "CACERT") && (splitted.size() > 1)) std::string _param = GetParameterName(splitted[0]);
if ((toUpper(_param) == "CACERT") && (splitted.size() > 1))
{ {
this->caCertFilename = splitted[1]; this->caCertFilename = "/sdcard" + splitted[1];
} }
if ((toUpper(splitted[0]) == "CLIENTCERT") && (splitted.size() > 1)) if ((toUpper(_param) == "VALIDATESERVERCERT") && (splitted.size() > 1))
{ {
this->clientCertFilename = splitted[1]; validateServerCert = alphanumericToBoolean(splitted[1]);
} }
if ((toUpper(splitted[0]) == "CLIENTKEY") && (splitted.size() > 1)) if ((toUpper(_param) == "CLIENTCERT") && (splitted.size() > 1))
{ {
this->clientKeyFilename = splitted[1]; this->clientCertFilename = "/sdcard" + splitted[1];
} }
if ((toUpper(splitted[0]) == "USER") && (splitted.size() > 1)) if ((toUpper(_param) == "CLIENTKEY") && (splitted.size() > 1))
{
this->clientKeyFilename = "/sdcard" + splitted[1];
}
if ((toUpper(_param) == "USER") && (splitted.size() > 1))
{ {
this->user = splitted[1]; this->user = splitted[1];
} }
if ((toUpper(splitted[0]) == "PASSWORD") && (splitted.size() > 1)) if ((toUpper(_param) == "PASSWORD") && (splitted.size() > 1))
{ {
this->password = splitted[1]; this->password = splitted[1];
} }
if ((toUpper(splitted[0]) == "URI") && (splitted.size() > 1)) if ((toUpper(_param) == "URI") && (splitted.size() > 1))
{ {
this->uri = splitted[1]; this->uri = splitted[1];
} }
if ((toUpper(splitted[0]) == "RETAINMESSAGES") && (splitted.size() > 1)) if ((toUpper(_param) == "RETAINMESSAGES") && (splitted.size() > 1))
{ {
if (toUpper(splitted[1]) == "TRUE") { SetRetainFlag = alphanumericToBoolean(splitted[1]);
SetRetainFlag = true; setMqtt_Server_Retain(SetRetainFlag);
setMqtt_Server_Retain(SetRetainFlag);
}
} }
if ((toUpper(splitted[0]) == "HOMEASSISTANTDISCOVERY") && (splitted.size() > 1)) if ((toUpper(_param) == "HOMEASSISTANTDISCOVERY") && (splitted.size() > 1))
{ {
if (toUpper(splitted[1]) == "TRUE") if (toUpper(splitted[1]) == "TRUE")
SetHomeassistantDiscoveryEnabled(true); SetHomeassistantDiscoveryEnabled(true);
} }
if ((toUpper(splitted[0]) == "METERTYPE") && (splitted.size() > 1)) { if ((toUpper(_param) == "METERTYPE") && (splitted.size() > 1)) {
/* Use meter type for the device class /* 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 */ 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") { if (toUpper(splitted[1]) == "WATER_M3") {
@@ -151,7 +156,7 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
mqttServer_setMeterType("water", "L", "h", "L/h"); mqttServer_setMeterType("water", "L", "h", "L/h");
} }
else if (toUpper(splitted[1]) == "WATER_FT3") { else if (toUpper(splitted[1]) == "WATER_FT3") {
mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // Minutes mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // m = Minutes
} }
else if (toUpper(splitted[1]) == "WATER_GAL") { else if (toUpper(splitted[1]) == "WATER_GAL") {
mqttServer_setMeterType("water", "gal", "h", "gal/h"); mqttServer_setMeterType("water", "gal", "h", "gal/h");
@@ -160,7 +165,7 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
mqttServer_setMeterType("gas", "", "h", "m³/h"); mqttServer_setMeterType("gas", "", "h", "m³/h");
} }
else if (toUpper(splitted[1]) == "GAS_FT3") { else if (toUpper(splitted[1]) == "GAS_FT3") {
mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // Minutes mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // m = Minutes
} }
else if (toUpper(splitted[1]) == "ENERGY_WH") { else if (toUpper(splitted[1]) == "ENERGY_WH") {
mqttServer_setMeterType("energy", "Wh", "h", "W"); mqttServer_setMeterType("energy", "Wh", "h", "W");
@@ -174,17 +179,37 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
else if (toUpper(splitted[1]) == "ENERGY_GJ") { else if (toUpper(splitted[1]) == "ENERGY_GJ") {
mqttServer_setMeterType("energy", "GJ", "h", "GJ/h"); mqttServer_setMeterType("energy", "GJ", "h", "GJ/h");
} }
else if (toUpper(splitted[1]) == "TEMPERATURE_C") {
mqttServer_setMeterType("temperature", "°C", "m", "°C/m"); // m = Minutes
}
else if (toUpper(splitted[1]) == "TEMPERATURE_F") {
mqttServer_setMeterType("temperature", "°F", "m", "°F/m"); // m = Minutes
}
else if (toUpper(splitted[1]) == "TEMPERATURE_K") {
mqttServer_setMeterType("temperature", "K", "m", "K/m"); // m = Minutes
}
} }
if ((toUpper(splitted[0]) == "CLIENTID") && (splitted.size() > 1)) if ((toUpper(_param) == "CLIENTID") && (splitted.size() > 1))
{ {
this->clientname = splitted[1]; this->clientname = splitted[1];
} }
if (((toUpper(splitted[0]) == "TOPIC") || (toUpper(splitted[0]) == "MAINTOPIC")) && (splitted.size() > 1)) if (((toUpper(_param) == "TOPIC") || (toUpper(splitted[0]) == "MAINTOPIC")) && (splitted.size() > 1))
{ {
maintopic = splitted[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: /* Note:
@@ -193,6 +218,7 @@ bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
* To work around this, we delay the start and trigger it from ClassFlowControll::ReadParameter() */ * To work around this, we delay the start and trigger it from ClassFlowControll::ReadParameter() */
mqttServer_setMainTopic(maintopic); mqttServer_setMainTopic(maintopic);
mqttServer_setDmoticzInTopic(domoticzintopic);
return true; return true;
} }
@@ -210,8 +236,8 @@ bool ClassFlowMQTT::Start(float AutoInterval)
mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval); mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, LWT_TOPIC, LWT_CONNECTED, bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, domoticzintopic, LWT_TOPIC, LWT_CONNECTED,
LWT_DISCONNECTED, caCertFilename, clientCertFilename, clientKeyFilename, LWT_DISCONNECTED, caCertFilename, validateServerCert, clientCertFilename, clientKeyFilename,
keepAlive, SetRetainFlag, (void *)&GotConnected); keepAlive, SetRetainFlag, (void *)&GotConnected);
if (!MQTTConfigCheck) { if (!MQTTConfigCheck) {
@@ -235,6 +261,8 @@ bool ClassFlowMQTT::doFlow(string zwtime)
std::string resultchangabs = ""; std::string resultchangabs = "";
string zw = ""; string zw = "";
string namenumber = ""; string namenumber = "";
string domoticzpayload = "";
string DomoticzIdx = "";
int qos = 1; int qos = 1;
/* Send the the Homeassistant Discovery and the Static Topics in case they where scheduled */ /* Send the the Homeassistant Discovery and the Static Topics in case they where scheduled */
@@ -258,16 +286,20 @@ bool ClassFlowMQTT::doFlow(string zwtime)
resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
resulttimestamp = (*NUMBERS)[i]->timeStamp; resulttimestamp = (*NUMBERS)[i]->timeStamp;
DomoticzIdx = (*NUMBERS)[i]->DomoticzIdx;
domoticzpayload = "{\"command\":\"udevice\",\"idx\":" + DomoticzIdx + ",\"svalue\":\""+ result + "\"}";
namenumber = (*NUMBERS)[i]->name; namenumber = (*NUMBERS)[i]->name;
if (namenumber == "default") if (namenumber == "default")
namenumber = maintopic + "/"; namenumber = maintopic + "/";
else else
namenumber = maintopic + "/" + namenumber + "/"; 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); success |= MQTTPublish(namenumber + "value", result, qos, SetRetainFlag);
if (resulterror.length() > 0) if (resulterror.length() > 0)
success |= MQTTPublish(namenumber + "error", resulterror, qos, SetRetainFlag); success |= MQTTPublish(namenumber + "error", resulterror, qos, SetRetainFlag);
@@ -286,7 +318,7 @@ bool ClassFlowMQTT::doFlow(string zwtime)
if (resultchangabs.length() > 0) { if (resultchangabs.length() > 0) {
success |= MQTTPublish(namenumber + "changeabsolut", resultchangabs, qos, SetRetainFlag); // Legacy API success |= MQTTPublish(namenumber + "changeabsolut", resultchangabs, qos, SetRetainFlag); // Legacy API
success |= MQTTPublish(namenumber + "rate_per_digitalization_round", resultchangabs, qos, SetRetainFlag); success |= MQTTPublish(namenumber + "rate_per_digitization_round", resultchangabs, qos, SetRetainFlag);
} }
if (resultraw.length() > 0) if (resultraw.length() > 0)
@@ -325,6 +357,26 @@ bool ClassFlowMQTT::doFlow(string zwtime)
return true; 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
#endif //ENABLE_MQTT

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,9 +1,15 @@
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include "ClassFlowTakeImage.h" #include "ClassFlowTakeImage.h"
#include "Helper.h" #include "Helper.h"
#include "ClassLogFile.h" #include "ClassLogFile.h"
#include "CImageBasis.h" #include "CImageBasis.h"
#include "ClassControllCamera.h" #include "ClassControllCamera.h"
#include "MainFlowControl.h"
#include "esp_wifi.h" #include "esp_wifi.h"
#include "esp_log.h" #include "esp_log.h"
@@ -12,14 +18,14 @@
#include <time.h> #include <time.h>
// #define DEBUG_DETAIL_ON // #define DEBUG_DETAIL_ON
// #define WIFITURNOFF // #define WIFITURNOFF
static const char* TAG = "TAKEIMAGE"; static const char *TAG = "TAKEIMAGE";
esp_err_t ClassFlowTakeImage::camera_capture(){ esp_err_t ClassFlowTakeImage::camera_capture(void)
string nm = namerawimage; {
string nm = namerawimage;
Camera.CaptureToFile(nm); Camera.CaptureToFile(nm);
time(&TimeImageTaken); time(&TimeImageTaken);
localtime(&TimeImageTaken); localtime(&TimeImageTaken);
@@ -30,150 +36,500 @@ esp_err_t ClassFlowTakeImage::camera_capture(){
void ClassFlowTakeImage::takePictureWithFlash(int flash_duration) void ClassFlowTakeImage::takePictureWithFlash(int flash_duration)
{ {
// in case the image is flipped, it must be reset here // // in case the image is flipped, it must be reset here //
rawImage->width = image_width; rawImage->width = CCstatus.ImageWidth;
rawImage->height = image_height; rawImage->height = CCstatus.ImageHeight;
/////////////////////////////////////////////////////////////////////////////////////
ESP_LOGD(TAG, "flash_duration: %d", flash_duration); ESP_LOGD(TAG, "flash_duration: %d", flash_duration);
Camera.CaptureToBasisImage(rawImage, flash_duration); Camera.CaptureToBasisImage(rawImage, flash_duration);
time(&TimeImageTaken); time(&TimeImageTaken);
localtime(&TimeImageTaken); localtime(&TimeImageTaken);
if (SaveAllFiles) rawImage->SaveToFile(namerawimage); if (CCstatus.SaveAllFiles)
{
rawImage->SaveToFile(namerawimage);
}
} }
void ClassFlowTakeImage::SetInitialParameter(void) void ClassFlowTakeImage::SetInitialParameter(void)
{ {
waitbeforepicture = 5;
isImageSize = false;
ImageQuality = -1;
TimeImageTaken = 0; TimeImageTaken = 0;
ImageQuality = 5;
rawImage = NULL; rawImage = NULL;
ImageSize = FRAMESIZE_VGA;
SaveAllFiles = false;
disabled = false; disabled = false;
FixedExposure = false;
namerawimage = "/sdcard/img_tmp/raw.jpg"; 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
ClassFlowTakeImage::ClassFlowTakeImage(std::vector<ClassFlow*>* lfc) : ClassFlowImage(lfc, TAG) 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:
CCstatus.ImageGainceiling = GAINCEILING_4X;
break;
case 2:
CCstatus.ImageGainceiling = GAINCEILING_8X;
break;
case 3:
CCstatus.ImageGainceiling = GAINCEILING_16X;
break;
case 4:
CCstatus.ImageGainceiling = GAINCEILING_32X;
break;
case 5:
CCstatus.ImageGainceiling = GAINCEILING_64X;
break;
case 6:
CCstatus.ImageGainceiling = GAINCEILING_128X;
break;
default:
CCstatus.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);
CCstatus.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);
CCstatus.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)
{ {
imagesLocation = "/log/source"; imagesLocation = "/log/source";
imagesRetention = 5; imagesRetention = 5;
SetInitialParameter(); 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 ClassFlowTakeImage::getHTMLSingleStep(string host)
{ {
string result; string result;
@@ -181,74 +537,79 @@ string ClassFlowTakeImage::getHTMLSingleStep(string host)
return result; return result;
} }
// wird bei jeder Auswertrunde aufgerufen
bool ClassFlowTakeImage::doFlow(string zwtime) bool ClassFlowTakeImage::doFlow(string zwtime)
{ {
psram_init_shared_memory_for_take_image_step(); psram_init_shared_memory_for_take_image_step();
string logPath = CreateLogFolder(zwtime); string logPath = CreateLogFolder(zwtime);
int flash_duration = (int) (waitbeforepicture * 1000); int flash_duration = (int)(CCstatus.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 #ifdef WIFITURNOFF
esp_wifi_stop(); // to save power usage and esp_wifi_stop(); // to save power usage and
#endif #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;
}
takePictureWithFlash(flash_duration); takePictureWithFlash(flash_duration);
#ifdef WIFITURNOFF #ifdef WIFITURNOFF
esp_wifi_start(); esp_wifi_start();
#endif #endif
#ifdef DEBUG_DETAIL_ON
#ifdef DEBUG_DETAIL_ON LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After takePictureWithFlash");
LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After takePictureWithFlash"); #endif
#endif
LogImage(logPath, "raw", NULL, NULL, zwtime, rawImage); LogImage(logPath, "raw", NULL, NULL, zwtime, rawImage);
RemoveOldLogs(); RemoveOldLogs();
#ifdef DEBUG_DETAIL_ON #ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After RemoveOldLogs"); LogFile.WriteHeapInfo("ClassFlowTakeImage::doFlow - After RemoveOldLogs");
#endif #endif
psram_deinit_shared_memory_for_take_image_step(); psram_deinit_shared_memory_for_take_image_step();
return true; return true;
} }
esp_err_t ClassFlowTakeImage::SendRawJPG(httpd_req_t *req) esp_err_t ClassFlowTakeImage::SendRawJPG(httpd_req_t *req)
{ {
int flash_duration = (int) (waitbeforepicture * 1000); int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
time(&TimeImageTaken); time(&TimeImageTaken);
localtime(&TimeImageTaken); localtime(&TimeImageTaken);
return Camera.CaptureToHTTP(req, flash_duration); return Camera.CaptureToHTTP(req, flash_duration);
} }
ImageData *ClassFlowTakeImage::SendRawImage(void)
ImageData* ClassFlowTakeImage::SendRawImage()
{ {
CImageBasis *zw = new CImageBasis("SendRawImage", rawImage); CImageBasis *zw = new CImageBasis("SendRawImage", rawImage);
ImageData *id; ImageData *id;
int flash_duration = (int) (waitbeforepicture * 1000); int flash_duration = (int)(CCstatus.WaitBeforePicture * 1000);
Camera.CaptureToBasisImage(zw, flash_duration); Camera.CaptureToBasisImage(zw, flash_duration);
time(&TimeImageTaken); time(&TimeImageTaken);
localtime(&TimeImageTaken); localtime(&TimeImageTaken);
id = zw->writeToMemoryAsJPG(); id = zw->writeToMemoryAsJPG();
delete zw; delete zw;
return id; return id;
} }
time_t ClassFlowTakeImage::getTimeImageTaken() time_t ClassFlowTakeImage::getTimeImageTaken(void)
{ {
return TimeImageTaken; return TimeImageTaken;
} }
@@ -257,4 +618,3 @@ ClassFlowTakeImage::~ClassFlowTakeImage(void)
{ {
delete rawImage; delete rawImage;
} }

View File

@@ -9,47 +9,32 @@
#include <string> #include <string>
class ClassFlowTakeImage : class ClassFlowTakeImage : public ClassFlowImage
public ClassFlowImage
{ {
protected: protected:
float waitbeforepicture;
float waitbeforepicture_store;
framesize_t ImageSize;
bool isImageSize;
int ImageQuality;
time_t TimeImageTaken; time_t TimeImageTaken;
string namerawimage; 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 takePictureWithFlash(int flash_duration);
void SetInitialParameter(void);
void SetInitialParameter(void);
public: public:
CImageBasis *rawImage; 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); bool doFlow(string time);
string getHTMLSingleStep(string host); string getHTMLSingleStep(string host);
time_t getTimeImageTaken(); time_t getTimeImageTaken(void);
string name(){return "ClassFlowTakeImage";}; string name() { return "ClassFlowTakeImage"; };
ImageData* SendRawImage(); ImageData *SendRawImage(void);
esp_err_t SendRawJPG(httpd_req_t *req); esp_err_t SendRawJPG(httpd_req_t *req);
~ClassFlowTakeImage(void); ~ClassFlowTakeImage(void);
}; };
#endif // CLASSFFLOWTAKEIMAGE_H
#endif //CLASSFFLOWTAKEIMAGE_H

View File

@@ -0,0 +1,171 @@
#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

@@ -0,0 +1,43 @@
#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,26 +9,83 @@
#include <esp_http_server.h> #include <esp_http_server.h>
#include "CImageBasis.h" #include "CImageBasis.h"
#include "ClassFlowControll.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; 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 register_server_main_flow_task_uri(httpd_handle_t server);
void CheckIsPlannedReboot(); void CheckIsPlannedReboot(void);
bool getIsPlannedReboot(); bool getIsPlannedReboot(void);
void InitializeFlowTask(); void InitializeFlowTask(void);
void DeleteMainFlowTask(); void DeleteMainFlowTask(void);
bool isSetupModusActive(); bool isSetupModusActive(void);
int getCountFlowRounds(); int getCountFlowRounds(void);
#ifdef ENABLE_MQTT #ifdef ENABLE_MQTT
esp_err_t MQTTCtrlFlowStart(std::string _topic); esp_err_t MQTTCtrlFlowStart(std::string _topic);
#endif //ENABLE_MQTT #endif // ENABLE_MQTT
esp_err_t GetRawJPG(httpd_req_t *req); esp_err_t GetRawJPG(httpd_req_t *req);
esp_err_t GetJPG(std::string _filename, httpd_req_t *req); esp_err_t GetJPG(std::string _filename, httpd_req_t *req);
#endif //MAINFLOWCONTROL_H #endif // MAINFLOWCONTROL_H

File diff suppressed because it is too large Load Diff

View File

@@ -21,7 +21,6 @@ bool RenameFile(string from, string to);
bool MakeDir(std::string _what); bool MakeDir(std::string _what);
bool FileExists(string filename); bool FileExists(string filename);
string RundeOutput(double _in, int _anzNachkomma); string RundeOutput(double _in, int _anzNachkomma);
size_t findDelimiterPos(string input, string delimiter); size_t findDelimiterPos(string input, string delimiter);
@@ -33,7 +32,6 @@ string getFileType(string filename);
string getFileFullFileName(string filename); string getFileFullFileName(string filename);
string getDirectory(string filename); string getDirectory(string filename);
int mkdir_r(const char *dir, const mode_t mode); int mkdir_r(const char *dir, const mode_t mode);
int removeFolder(const char* folderPath, const char* logTag); int removeFolder(const char* folderPath, const char* logTag);
@@ -42,6 +40,7 @@ string toUpper(string in);
float temperatureRead(); float temperatureRead();
std::string intToHexString(int _valueInt);
time_t addDays(time_t startTime, int days); time_t addDays(time_t startTime, int days);
void memCopyGen(uint8_t* _source, uint8_t* _target, int _size); void memCopyGen(uint8_t* _source, uint8_t* _target, int _size);
@@ -68,7 +67,6 @@ string getSDCardSectorSize();
string getMac(void); string getMac(void);
/* Error bit fields /* Error bit fields
One bit per error One bit per error
Make sure it matches https://jomjol.github.io/AI-on-the-edge-device-docs/Error-Codes */ Make sure it matches https://jomjol.github.io/AI-on-the-edge-device-docs/Error-Codes */
@@ -98,8 +96,18 @@ const char* get404(void);
std::string UrlDecode(const std::string& value); 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 replaceString(std::string& s, std::string const& toReplace, std::string const& replaceWith, bool logIt); 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 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 #endif //HELPER_H

View File

@@ -120,15 +120,15 @@ void psram_free_shared_temp_image_memory(void) {
/******************************************************************* /*******************************************************************
* Memory used in Digitalization Steps * Memory used in Digitization Steps
* During this step we only use the shared part of the PSRAM for the * During this step we only use the shared part of the PSRAM for the
* Tensor Arena and one of the Models. * Tensor Arena and one of the Models.
* The shared memory is large enough for the largest model and the * The shared memory is large enough for the largest model and the
* Tensor Arena. Therefore we do not need to monitor the usage. * Tensor Arena. Therefore we do not need to monitor the usage.
*******************************************************************/ *******************************************************************/
void *psram_get_shared_tensor_arena_memory(void) { void *psram_get_shared_tensor_arena_memory(void) {
if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitalization_Model")) { if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitization_Model")) {
sharedMemoryInUseFor = "Digitalization_Tensor"; sharedMemoryInUseFor = "Digitization_Tensor";
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Tensor Arena (" + std::to_string(TENSOR_ARENA_SIZE) + " bytes, use shared memory in PSRAM)..."); 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 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) { void *psram_get_shared_model_memory(void) {
if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitalization_Tensor")) { if ((sharedMemoryInUseFor == "") || (sharedMemoryInUseFor == "Digitization_Tensor")) {
sharedMemoryInUseFor = "Digitalization_Model"; sharedMemoryInUseFor = "Digitization_Model";
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Model memory (" + std::to_string(MAX_MODEL_SIZE) + " bytes, use shared memory in PSRAM)..."); 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 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_reserve_shared_tmp_image_memory(void);
void psram_free_shared_temp_image_memory(void); void psram_free_shared_temp_image_memory(void);
/* Memory used in Digitalization Steps */ /* Memory used in Digitization Steps */
void *psram_get_shared_tensor_arena_memory(void); void *psram_get_shared_tensor_arena_memory(void);
void *psram_get_shared_model_memory(void); void *psram_get_shared_model_memory(void);
void psram_free_shared_tensor_arena_and_model_memory(void); void psram_free_shared_tensor_arena_and_model_memory(void);

View File

@@ -69,7 +69,6 @@ int SDCardCheckRW(void)
return 0; return 0;
} }
bool SDCardCheckFolderFilePresence() bool SDCardCheckFolderFilePresence()
{ {
struct stat sb; struct stat sb;
@@ -125,25 +124,25 @@ bool SDCardCheckFolderFilePresence()
} }
/* check if file exists: index.html */ /* check if file exists: index.html */
if (stat("/sdcard/html/index.html", &sb) != 0) { if ((stat("/sdcard/html/index.html", &sb) != 0) && (stat("/sdcard/html/index.html.gz", &sb) != 0)) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Folder/file check: File /html/index.html not found"); LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Folder/file check: File /html/index.html not found");
bRetval = false; bRetval = false;
} }
/* check if file exists: ota.html */ /* check if file exists: ota.html */
if (stat("/sdcard/html/ota_page.html", &sb) != 0) { if ((stat("/sdcard/html/ota_page.html", &sb) != 0) && (stat("/sdcard/html/ota_page.html.gz", &sb) != 0)) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Folder/file check: File /html/ota.html not found"); LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Folder/file check: File /html/ota.html not found");
bRetval = false; bRetval = false;
} }
/* check if file exists: log.html */ /* check if file exists: log.html */
if (stat("/sdcard/html/log.html", &sb) != 0) { if ((stat("/sdcard/html/log.html", &sb) != 0) && (stat("/sdcard/html/log.html.gz", &sb) != 0)) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Folder/file check: File /html/log.html not found"); LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Folder/file check: File /html/log.html not found");
bRetval = false; bRetval = false;
} }
/* check if file exists: common.js */ /* check if file exists: common.js */
if (stat("/sdcard/html/common.js", &sb) != 0) { if ((stat("/sdcard/html/common.js", &sb) != 0) && (stat("/sdcard/html/common.js.gz", &sb) != 0)) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Folder/file check: File /html/common.js not found"); LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Folder/file check: File /html/common.js not found");
bRetval = false; bRetval = false;
} }
@@ -154,8 +153,9 @@ bool SDCardCheckFolderFilePresence()
bRetval = false; bRetval = false;
} }
if (bRetval) if (bRetval) {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Folder/file presence check successful"); LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Folder/file presence check successful");
}
return bRetval; return bRetval;
} }

View File

@@ -35,15 +35,15 @@ static const char* TAG = "sdcard_init";
} \ } \
} while(0) } while(0)
typedef struct vfs_fat_sd_ctx_t { typedef struct mh_vfs_fat_sd_ctx_t {
BYTE pdrv; //Drive number that is mounted BYTE pdrv; //Drive number that is mounted
esp_vfs_fat_mount_config_t mount_config; //Mount configuration esp_vfs_fat_mount_config_t mount_config; //Mount configuration
FATFS *fs; //FAT structure pointer that is registered FATFS *fs; //FAT structure pointer that is registered
sdmmc_card_t *card; //Card info sdmmc_card_t *card; //Card info
char *base_path; //Path where partition is registered char *base_path; //Path where partition is registered
} vfs_fat_sd_ctx_t; } mh_vfs_fat_sd_ctx_t;
static vfs_fat_sd_ctx_t *s_ctx[FF_VOLUMES] = {}; 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 `s_saved_ctx_id` is only used by `esp_vfs_fat_sdmmc_unmount`, which is deprecated.
@@ -185,14 +185,9 @@ BYTE ff_diskio_get_pdrv_card_mh(const sdmmc_card_t* card)
return 0xff; return 0xff;
} }
static bool s_get_context_id_by_card_mh(const sdmmc_card_t *card, uint32_t *out_id) static bool s_get_context_id_by_card_mh(const sdmmc_card_t *card, uint32_t *out_id)
{ {
vfs_fat_sd_ctx_t *p_ctx = NULL; mh_vfs_fat_sd_ctx_t *p_ctx = NULL;
for (int i = 0; i < FF_VOLUMES; i++) { for (int i = 0; i < FF_VOLUMES; i++) {
p_ctx = s_ctx[i]; p_ctx = s_ctx[i];
if (p_ctx) { if (p_ctx) {
@@ -378,7 +373,7 @@ static esp_err_t init_sdmmc_host_mh(int slot, const void *slot_config, int *out_
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 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; esp_err_t err;
vfs_fat_sd_ctx_t *ctx = NULL; mh_vfs_fat_sd_ctx_t *ctx = NULL;
uint32_t ctx_id = FF_VOLUMES; uint32_t ctx_id = FF_VOLUMES;
FATFS *fs = NULL; FATFS *fs = NULL;
int card_handle = -1; //uninitialized int card_handle = -1; //uninitialized
@@ -419,7 +414,7 @@ esp_err_t esp_vfs_fat_sdmmc_mount_mh(const char* base_path, const sdmmc_host_t*
s_saved_ctx_id = 0; s_saved_ctx_id = 0;
} }
ctx = calloc(sizeof(vfs_fat_sd_ctx_t), 1); ctx = calloc(sizeof(mh_vfs_fat_sd_ctx_t), 1);
if (!ctx) { if (!ctx) {
CHECK_EXECUTE_RESULT(ESP_ERR_NO_MEM, "no mem"); CHECK_EXECUTE_RESULT(ESP_ERR_NO_MEM, "no mem");
@@ -462,7 +457,7 @@ esp_err_t esp_vfs_fat_sdspi_mount_mh(const char* base_path, const sdmmc_host_t*
{ {
const sdmmc_host_t* host_config = host_config_input; const sdmmc_host_t* host_config = host_config_input;
esp_err_t err; esp_err_t err;
vfs_fat_sd_ctx_t *ctx = NULL; mh_vfs_fat_sd_ctx_t *ctx = NULL;
uint32_t ctx_id = FF_VOLUMES; uint32_t ctx_id = FF_VOLUMES;
FATFS *fs = NULL; FATFS *fs = NULL;
int card_handle = -1; //uninitialized int card_handle = -1; //uninitialized
@@ -514,7 +509,7 @@ esp_err_t esp_vfs_fat_sdspi_mount_mh(const char* base_path, const sdmmc_host_t*
s_saved_ctx_id = 0; s_saved_ctx_id = 0;
} }
ctx = calloc(sizeof(vfs_fat_sd_ctx_t), 1); ctx = calloc(sizeof(mh_vfs_fat_sd_ctx_t), 1);
if (!ctx) { if (!ctx) {
CHECK_EXECUTE_RESULT(ESP_ERR_NO_MEM, "no mem"); CHECK_EXECUTE_RESULT(ESP_ERR_NO_MEM, "no mem");

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); //free_psram_heap(std::string(TAG) + "->rgb_image (LoadFromMemory)", rgb_image);
} }
rgb_image = stbi_load_from_memory(_buffer, len, &width, &height, &channels, 3); rgb_image = stbi_load_from_memory(_buffer, len, &width, &height, &channels, STBI_rgb);
bpp = channels; bpp = channels;
ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels); ESP_LOGD(TAG, "Image loaded from memory: %d, %d, %d", width, height, channels);
@@ -459,6 +459,44 @@ 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) CImageBasis::CImageBasis(string _name, CImageBasis *_copyfrom)
{ {
name = _name; name = _name;
@@ -598,6 +636,20 @@ 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] void CImageBasis::Contrast(float _contrast) //input range [-100..100]
{ {
stbi_uc* p_source; stbi_uc* p_source;

View File

@@ -56,6 +56,7 @@ class CImageBasis
void drawEllipse(int x1, int y1, int radx, int rady, int r, int g, int b, int thickness = 1); 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 setPixelColor(int x, int y, int r, int g, int b);
void Negative(void);
void Contrast(float _contrast); void Contrast(float _contrast);
bool ImageOkay(); bool ImageOkay();
bool CopyFromMemory(uint8_t* _source, int _size); bool CopyFromMemory(uint8_t* _source, int _size);
@@ -74,6 +75,7 @@ class CImageBasis
void Resize(int _new_dx, int _new_dy); void Resize(int _new_dx, int _new_dy);
void Resize(int _new_dx, int _new_dy, CImageBasis *_target); 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); void LoadFromMemory(stbi_uc *_buffer, int len);

View File

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

View File

@@ -8,95 +8,35 @@
#include "time_sntp.h" #include "time_sntp.h"
#include "../../include/defines.h" #include "../../include/defines.h"
static const char *TAG = "INFLUXDB"; static const char *TAG = "INFLUXDB";
std::string _influxDBURI; /**
std::string _influxDBDatabase; * @brief Buffer to store the HTTP response.
std::string _influxDBUser; *
std::string _influxDBPassword; * This character array is used to store the output of an HTTP response.
* The size of the buffer is defined by the constant MAX_HTTP_OUTPUT_BUFFER.
std::string _influxDB_V2_URI; */
std::string _influxDB_V2_Bucket; char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
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)
{
_influxDB_V2_URI = _uri;
_influxDB_V2_Bucket = _bucket;
_influxDB_V2_Org = _org;
_influxDB_V2_Token = _token;
}
void InfluxDB_V2_Publish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC)
{
char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
esp_http_client_config_t http_config = {
.user_agent = "ESP32 Meter reader",
.method = HTTP_METHOD_POST,
.event_handler = http_event_handler,
.buffer_size = MAX_HTTP_OUTPUT_BUFFER,
.user_data = response_buffer
};
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "InfluxDB_V2_Publish - Key: " + _key + ", Content: " + _content + ", timeUTC: " + std::to_string(_timeUTC));
std::string payload;
char nowTimestamp[21];
if (_timeUTC > 0)
{
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Timestamp (UTC): " + std::to_string(_timeUTC));
sprintf(nowTimestamp,"%ld000000000", _timeUTC); // UTC
payload = _measurement + " " + _key + "=" + _content + " " + nowTimestamp;
}
else
{
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "no timestamp given");
payload = _measurement + " " + _key + "=" + _content;
}
payload.shrink_to_fit();
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;
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
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "API URI: " + apiURI);
esp_http_client_handle_t http_client = esp_http_client_init(&http_config);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "client is initialized");
esp_http_client_set_header(http_client, "Content-Type", "text/plain");
std::string _zw = "Token " + _influxDB_V2_Token;
// LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Tokenheader: %s\n", _zw.c_str());
esp_http_client_set_header(http_client, "Authorization", _zw.c_str());
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "header is set");
ESP_ERROR_CHECK(esp_http_client_set_post_field(http_client, payload.c_str(), payload.length()));
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "post payload is set");
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_DEBUG, TAG, "HTTP request failed");
}
esp_http_client_cleanup(http_client);
}
/**
* @brief HTTP event handler callback function.
*
* This function handles various HTTP client events and logs appropriate messages.
*
* @param evt Pointer to the HTTP client event structure.
* @return esp_err_t ESP_OK on success.
*
* Event types handled:
* - HTTP_EVENT_ERROR: Logs an error message when an HTTP error is encountered.
* - HTTP_EVENT_ON_CONNECTED: Logs a message when the HTTP client successfully connects.
* - HTTP_EVENT_HEADERS_SENT: Logs a message when all request headers are sent.
* - HTTP_EVENT_ON_HEADER: Logs the received header key and value.
* - HTTP_EVENT_ON_DATA: Logs the length of the received data.
* - HTTP_EVENT_ON_FINISH: Logs a message when the HTTP client finishes the request.
* - HTTP_EVENT_DISCONNECTED: Logs a message when the HTTP client disconnects.
* - HTTP_EVENT_REDIRECT: Logs a message when an HTTP redirect occurs.
*/
static esp_err_t http_event_handler(esp_http_client_event_t *evt) static esp_err_t http_event_handler(esp_http_client_event_t *evt)
{ {
switch(evt->event_id) switch(evt->event_id)
@@ -130,25 +70,123 @@ static esp_err_t http_event_handler(esp_http_client_event_t *evt)
return ESP_OK; return ESP_OK;
} }
void InfluxDBPublish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC) {
char response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
esp_http_client_config_t http_config = {
.user_agent = "ESP32 Meter reader",
.method = HTTP_METHOD_POST,
.event_handler = http_event_handler,
.buffer_size = MAX_HTTP_OUTPUT_BUFFER,
.user_data = response_buffer
};
if (_influxDBUser.length() && _influxDBPassword.length()){
http_config.username = _influxDBUser.c_str(); /**
http_config.password = _influxDBPassword.c_str(); * @brief Initializes the InfluxDB connection with version 1 settings.
http_config.auth_type = HTTP_AUTH_TYPE_BASIC; *
* This function sets up the connection parameters for InfluxDB version 1.
*
* @param _influxDBURI The URI of the InfluxDB server.
* @param _database The name of the database to connect to.
* @param _user The username for authentication.
* @param _password The password for authentication.
*/
void InfluxDB::InfluxDBInitV1(std::string _influxDBURI, std::string _database, std::string _user, std::string _password) {
version = INFLUXDB_V1;
influxDBURI = _influxDBURI;
database = _database;
user = _user;
password = _password;
}
/**
* @brief Initializes the InfluxDB client with version 2 settings.
*
* This function sets up the InfluxDB client to use InfluxDB version 2 by
* configuring the URI, bucket, organization, and token.
*
* @param _influxDBURI The URI of the InfluxDB server.
* @param _bucket The bucket name to store data in.
* @param _org The organization name associated with the bucket.
* @param _token The authentication token for accessing the InfluxDB server.
*/
void InfluxDB::InfluxDBInitV2(std::string _influxDBURI, std::string _bucket, std::string _org, std::string _token) {
version = INFLUXDB_V2;
influxDBURI = _influxDBURI;
bucket = _bucket;
org = _org;
token = _token;
}
/**
* @brief Establishes an HTTP connection to the InfluxDB server.
*
* This function configures and initializes an HTTP client to connect to the InfluxDB server.
* It sets up the necessary parameters such as the URL, event handler, buffer size, and user data.
* Depending on the InfluxDB version, it also configures the authentication type and credentials.
*
* @note This function destroys any existing HTTP client before initializing a new one.
*
* @param None
* @return None
*/
void InfluxDB::connectHTTP() {
esp_http_client_config_t config = {};
config.url = influxDBURI.c_str();
config.event_handler = http_event_handler;
config.buffer_size = MAX_HTTP_OUTPUT_BUFFER;
config.user_data = response_buffer;
switch (version) {
case INFLUXDB_V1:
config.auth_type = HTTP_AUTH_TYPE_BASIC;
config.username = user.c_str();
config.password = password.c_str();
break;
case INFLUXDB_V2:
break;
} }
InfluxDBdestroy();
httpClient = esp_http_client_init(&config);
if (!httpClient) {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to initialize HTTP client");
} else {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "HTTP client initialized successfully");
}
}
/**
* @brief Destroys the InfluxDB instance by cleaning up the HTTP client.
*
* This function checks if the HTTP client is initialized. If it is, it cleans up the HTTP client
* and logs the cleanup action. The HTTP client pointer is then set to NULL.
*/
void InfluxDB::InfluxDBdestroy() {
if (httpClient) {
esp_http_client_cleanup(httpClient);
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "HTTP client cleaned up");
httpClient = NULL;
}
}
/**
* @brief Publishes data to an InfluxDB instance.
*
* This function sends a measurement, key, and content to an InfluxDB server.
* It supports both InfluxDB v1 and v2 APIs.
*
* @param _measurement The measurement name to publish.
* @param _key The key associated with the measurement.
* @param _content The content or value to publish.
* @param _timeUTC The timestamp in UTC. If greater than 0, it will be included in the payload.
*
* The function logs the process and handles HTTP communication with the InfluxDB server.
* It constructs the appropriate API URI based on the InfluxDB version and sends the data
* using an HTTP POST request.
*/
void InfluxDB::InfluxDBPublish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC) {
std::string apiURI;
std::string payload; std::string payload;
char nowTimestamp[21]; char nowTimestamp[21];
connectHTTP();
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 + ", timeUTC: " + std::to_string(_timeUTC));
if (_timeUTC > 0) if (_timeUTC > 0)
@@ -164,50 +202,47 @@ void InfluxDBPublish(std::string _measurement, std::string _key, std::string _co
} }
payload.shrink_to_fit(); payload.shrink_to_fit();
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "sending line to influxdb:" + payload); LogFile.WriteToFile(ESP_LOG_INFO, TAG, "sending line to influxdb:" + payload);
esp_err_t err;
// use the default retention policy of the bucket switch (version) {
std::string apiURI = _influxDBURI + "/write?db=" + _influxDBDatabase; case INFLUXDB_V1:
// std::string apiURI = _influxDBURI + "/api/v2/write?bucket=" + _influxDBDatabase + "/"; apiURI = influxDBURI + "/write?db=" + database;
apiURI.shrink_to_fit();
apiURI.shrink_to_fit(); esp_http_client_set_url(httpClient, apiURI.c_str());
http_config.url = apiURI.c_str(); esp_http_client_set_method(httpClient, HTTP_METHOD_POST);
esp_http_client_set_header(httpClient, "Content-Type", "text/plain");
esp_http_client_set_post_field(httpClient, payload.c_str(), payload.length());
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "API URI: " + apiURI); err = esp_http_client_perform(httpClient);
if (err == ESP_OK) {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Data published successfully: " + payload);
} else {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to publish data: " + std::string(esp_err_to_name(err)));
}
break;
esp_http_client_handle_t http_client = esp_http_client_init(&http_config); case INFLUXDB_V2:
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "client is initialized"); apiURI = influxDBURI + "/api/v2/write?org=" + org + "&bucket=" + bucket;
apiURI.shrink_to_fit();
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "apiURI: " + apiURI);
esp_http_client_set_header(http_client, "Content-Type", "text/plain"); esp_http_client_set_url(httpClient, apiURI.c_str());
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "header is set"); esp_http_client_set_method(httpClient, HTTP_METHOD_POST);
esp_http_client_set_header(httpClient, "Content-Type", "text/plain");
ESP_ERROR_CHECK(esp_http_client_set_post_field(http_client, payload.c_str(), payload.length())); std::string _zw = "Token " + token;
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "post payload is set"); esp_http_client_set_header(httpClient, "Authorization", _zw.c_str());
esp_http_client_set_post_field(httpClient, payload.c_str(), payload.length());
esp_err_t err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_perform(http_client)); err = ESP_ERROR_CHECK_WITHOUT_ABORT(esp_http_client_perform(httpClient));
if (err == ESP_OK) {
if( err == ESP_OK ) { LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Data published successfully: " + payload);
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP request was performed"); } else {
int status_code = esp_http_client_get_status_code(http_client); LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Failed to publish data: " + std::string(esp_err_to_name(err)));
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP status code" + std::to_string(status_code)); }
} else { break;
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "HTTP request failed");
} }
esp_http_client_cleanup(http_client);
}
void InfluxDBInit(std::string _uri, std::string _database, std::string _user, std::string _password){
_influxDBURI = _uri;
_influxDBDatabase = _database;
_influxDBUser = _user;
_influxDBPassword = _password;
}
void InfluxDBdestroy() {
} }
#endif //ENABLE_INFLUXDB #endif //ENABLE_INFLUXDB

View File

@@ -8,17 +8,106 @@
#include <map> #include <map>
#include <functional> #include <functional>
// 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);
// Interface to InfluxDB v2.x #include <string>
void InfluxDB_V2_Init(std::string _uri, std::string _bucket, std::string _org, std::string _token); #include "esp_http_client.h"
void InfluxDB_V2_Publish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC); #include "esp_log.h"
enum InfluxDBVersion {
INFLUXDB_V1,
INFLUXDB_V2
};
/**
* @class InfluxDB
* @brief A class to handle connections and data publishing to InfluxDB servers.
*
* This class supports both InfluxDB v1.x and v2.x versions. It provides methods to initialize
* the connection parameters, publish data, and destroy the connection.
*
* @private
* @var std::string influxDBURI
* URI for the InfluxDB server.
*
* @var std::string database
* Database name for InfluxDB v1.x.
*
* @var std::string user
* Username for InfluxDB v1.x.
*
* @var std::string password
* Password for InfluxDB v1.x.
*
* @var std::string bucket
* Bucket name for InfluxDB v2.x.
*
* @var std::string org
* Organization name for InfluxDB v2.x.
*
* @var std::string token
* Token for InfluxDB v2.x.
*
* @var InfluxDBVersion version
* Version of the InfluxDB server (v1.x or v2.x).
*
* @var esp_http_client_handle_t httpClient
* HTTP client handle for making requests to the InfluxDB server.
*
* @var void connectHTTP()
* Establishes an HTTP connection to the InfluxDB server.
*
* @public
* @fn void InfluxDBInitV1(std::string _influxDBURI, std::string _database, std::string _user, std::string _password)
* Initializes the connection parameters for InfluxDB v1.x.
*
* @fn void InfluxDBInitV2(std::string _influxDBURI, std::string _bucket, std::string _org, std::string _token)
* Initializes the connection parameters for InfluxDB v2.x.
*
* @fn void InfluxDBdestroy()
* Destroys the InfluxDB connection.
*
* @fn void InfluxDBPublish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC)
* Publishes data to the InfluxDB server.
*
* @param _measurement The measurement name.
* @param _key The key for the data point.
* @param _content The content or value of the data point.
* @param _timeUTC The timestamp in UTC for the data point.
*/
class InfluxDB {
private:
// Information for InfluxDB v1.x
std::string influxDBURI = "";
// Information for InfluxDB v1.x
std::string database = "";
std::string user = "";
std::string password = "";
// Information for InfluxDB v2.x
std::string bucket = "";
std::string org = "";
std::string token = "";
InfluxDBVersion version;
esp_http_client_handle_t httpClient = NULL;
void connectHTTP();
public:
// Initialize the InfluxDB connection parameters
void InfluxDBInitV1(std::string _influxDBURI, std::string _database, std::string _user, std::string _password);
void InfluxDBInitV2(std::string _influxDBURI, std::string _bucket, std::string _org, std::string _token);
// Destroy the InfluxDB connection
void InfluxDBdestroy();
// Publish data to the InfluxDB server
void InfluxDBPublish(std::string _measurement, std::string _key, std::string _content, long int _timeUTC);
};
void InfluxDBdestroy();
#endif //INTERFACE_INFLUXDB_H #endif //INTERFACE_INFLUXDB_H
#endif //ENABLE_INFLUXDB #endif //ENABLE_INFLUXDB

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 _digital, 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 _digit, std::string _analog)
{ {
ESP_LOGD(TAG, "Start WriteToData"); ESP_LOGD(TAG, "Start WriteToData");
time_t rawtime; time_t rawtime;
@@ -67,7 +67,7 @@ void ClassLogFile::WriteToData(std::string _timestamp, std::string _name, std::s
fputs(_ReturnChangeAbsolute.c_str(), pFile); fputs(_ReturnChangeAbsolute.c_str(), pFile);
fputs(",", pFile); fputs(",", pFile);
fputs(_ErrorMessageText.c_str(), pFile); fputs(_ErrorMessageText.c_str(), pFile);
fputs(_digital.c_str(), pFile); fputs(_digit.c_str(), pFile);
fputs(_analog.c_str(), pFile); fputs(_analog.c_str(), pFile);
fputs("\n", pFile); fputs("\n", pFile);

View File

@@ -39,8 +39,8 @@ public:
void RemoveOldLogFile(); void RemoveOldLogFile();
void RemoveOldDataLog(); void RemoveOldDataLog();
// void WriteToData(std::string _ReturnRawValue, std::string _ReturnValue, std::string _ReturnPreValue, std::string _ErrorMessageText, std::string _digital, std::string _analog); // 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 _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 _digit, std::string _analog);
std::string GetCurrentFileName(); std::string GetCurrentFileName();

View File

@@ -16,7 +16,6 @@
#include "esp_timer.h" #include "esp_timer.h"
#endif #endif
static const char *TAG = "MQTT IF"; static const char *TAG = "MQTT IF";
std::map<std::string, std::function<void()>>* connectFunktionMap = NULL; std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
@@ -34,13 +33,13 @@ bool mqtt_initialized = false;
bool mqtt_connected = false; bool mqtt_connected = false;
esp_mqtt_client_handle_t client = NULL; esp_mqtt_client_handle_t client = NULL;
std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic; std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic, domoticz_in_topic;
std::string caCert, clientCert, clientKey; std::string caCert, clientCert, clientKey;
bool validateServerCert = true;
int keepalive; int keepalive;
bool SetRetainFlag; bool SetRetainFlag;
void (*callbackOnConnected)(std::string, bool) = NULL; void (*callbackOnConnected)(std::string, bool) = NULL;
bool MQTTPublish(std::string _key, std::string _content, int qos, bool retained_flag) bool MQTTPublish(std::string _key, std::string _content, int qos, bool retained_flag)
{ {
if (!mqtt_enabled) { // MQTT sevice not started / configured (MQTT_Init not called before) if (!mqtt_enabled) { // MQTT sevice not started / configured (MQTT_Init not called before)
@@ -95,7 +94,6 @@ bool MQTTPublish(std::string _key, std::string _content, int qos, bool retained_
} }
} }
static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) { static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
std::string topic = ""; std::string topic = "";
switch (event->event_id) { switch (event->event_id) {
@@ -197,16 +195,14 @@ static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
return ESP_OK; return ESP_OK;
} }
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) { static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, (int)event_id); ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, (int)event_id);
mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data); mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
} }
bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password, bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected, 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 _cacertfilename, bool _validateServerCert, std::string _clientcertfilename, std::string _clientkeyfilename,
int _keepalive, bool _SetRetainFlag, void *_callbackOnConnected) { int _keepalive, bool _SetRetainFlag, void *_callbackOnConnected) {
if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0)) if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0))
{ {
@@ -222,27 +218,48 @@ bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _us
keepalive = _keepalive; keepalive = _keepalive;
SetRetainFlag = _SetRetainFlag; SetRetainFlag = _SetRetainFlag;
maintopic = _maintopic; maintopic = _maintopic;
domoticz_in_topic = _domoticz_in_topic;
callbackOnConnected = ( void (*)(std::string, bool) )(_callbackOnConnected); callbackOnConnected = ( void (*)(std::string, bool) )(_callbackOnConnected);
if (_clientcertfilename.length() && _clientkeyfilename.length()){ if (_clientcertfilename.length() && _clientkeyfilename.length()) {
std::ifstream cert_ifs(_clientcertfilename); std::ifstream cert_ifs(_clientcertfilename);
std::string cert_content((std::istreambuf_iterator<char>(cert_ifs)), (std::istreambuf_iterator<char>())); if (cert_ifs.is_open()) {
clientCert = cert_content; std::string cert_content((std::istreambuf_iterator<char>(cert_ifs)), (std::istreambuf_iterator<char>()));
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using clientCert: " + _clientcertfilename); clientCert = cert_content;
cert_ifs.close();
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using clientCert: " + _clientcertfilename);
}
else {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "could not open clientCert: " + _clientcertfilename);
}
std::ifstream key_ifs(_clientkeyfilename); std::ifstream key_ifs(_clientkeyfilename);
std::string key_content((std::istreambuf_iterator<char>(key_ifs)), (std::istreambuf_iterator<char>())); if (key_ifs.is_open()) {
clientKey = key_content; std::string key_content((std::istreambuf_iterator<char>(key_ifs)), (std::istreambuf_iterator<char>()));
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using clientKey: " + _clientkeyfilename); clientKey = key_content;
key_ifs.close();
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using clientKey: " + _clientkeyfilename);
}
else {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "could not open clientKey: " + _clientkeyfilename);
}
} }
if (_cacertfilename.length() ){ if (_cacertfilename.length()) {
std::ifstream ifs(_cacertfilename); std::ifstream ca_ifs(_cacertfilename);
std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); if (ca_ifs.is_open()) {
caCert = content; std::string content((std::istreambuf_iterator<char>(ca_ifs)), (std::istreambuf_iterator<char>()));
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using caCert: " + _cacertfilename); caCert = content;
ca_ifs.close();
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using caCert: " + _cacertfilename);
}
else {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "could not open caCert: " + _cacertfilename);
}
} }
validateServerCert = _validateServerCert;
if (_user.length() && _password.length()){ if (_user.length() && _password.length()){
user = _user; user = _user;
password = _password; password = _password;
@@ -260,7 +277,6 @@ bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _us
return true; return true;
} }
int MQTT_Init() { int MQTT_Init() {
if (mqtt_initialized) { if (mqtt_initialized) {
return 0; return 0;
@@ -294,18 +310,21 @@ int MQTT_Init() {
mqtt_cfg.session.last_will.msg = lwt_disconnected.c_str(); mqtt_cfg.session.last_will.msg = lwt_disconnected.c_str();
mqtt_cfg.session.last_will.msg_len = (int)(lwt_disconnected.length()); mqtt_cfg.session.last_will.msg_len = (int)(lwt_disconnected.length());
mqtt_cfg.session.keepalive = keepalive; mqtt_cfg.session.keepalive = keepalive;
mqtt_cfg.buffer.size = 1536; // size of MQTT send/receive buffer (Default: 1024) mqtt_cfg.buffer.size = 2048; // size of MQTT send/receive buffer
if (caCert.length()){ if (caCert.length()) {
mqtt_cfg.broker.verification.certificate = caCert.c_str(); mqtt_cfg.broker.verification.certificate = caCert.c_str();
mqtt_cfg.broker.verification.certificate_len = caCert.length() + 1; mqtt_cfg.broker.verification.certificate_len = caCert.length() + 1;
mqtt_cfg.broker.verification.skip_cert_common_name_check = true;
// Skip any validation of server certificate CN field, this reduces the
// security of TLS and makes the *MQTT* client susceptible to MITM attacks
mqtt_cfg.broker.verification.skip_cert_common_name_check = !validateServerCert;
} }
if (clientCert.length() && clientKey.length()){ if (clientCert.length() && clientKey.length()) {
mqtt_cfg.credentials.authentication.certificate = clientCert.c_str(); mqtt_cfg.credentials.authentication.certificate = clientCert.c_str();
mqtt_cfg.credentials.authentication.certificate_len = clientCert.length() + 1; mqtt_cfg.credentials.authentication.certificate_len = clientCert.length() + 1;
mqtt_cfg.credentials.authentication.key = clientKey.c_str(); mqtt_cfg.credentials.authentication.key = clientKey.c_str();
mqtt_cfg.credentials.authentication.key_len = clientKey.length() + 1; mqtt_cfg.credentials.authentication.key_len = clientKey.length() + 1;
} }
@@ -355,7 +374,6 @@ int MQTT_Init() {
} }
void MQTTdestroy_client(bool _disable = false) { void MQTTdestroy_client(bool _disable = false) {
if (client) { if (client) {
if (mqtt_connected) { if (mqtt_connected) {
@@ -373,32 +391,22 @@ void MQTTdestroy_client(bool _disable = false) {
mqtt_configOK = false; mqtt_configOK = false;
} }
bool getMQTTisEnabled() { bool getMQTTisEnabled() {
return mqtt_enabled; return mqtt_enabled;
} }
bool getMQTTisConnected() { bool getMQTTisConnected() {
return mqtt_connected; return mqtt_connected;
} }
bool mqtt_handler_flow_start(std::string _topic, char* _data, int _data_len) 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); ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
if (_data_len > 0) { MQTTCtrlFlowStart(_topic);
MQTTCtrlFlowStart(_topic);
}
else {
LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_flow_start: handler called, but no data");
}
return ESP_OK; return ESP_OK;
} }
bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len) bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len)
{ {
//ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data); //ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
@@ -434,7 +442,6 @@ bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len)
return ESP_FAIL; return ESP_FAIL;
} }
void MQTTconnected(){ void MQTTconnected(){
if (mqtt_connected) { if (mqtt_connected) {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker"); LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker");
@@ -469,7 +476,6 @@ void MQTTconnected(){
} }
} }
void MQTTregisterConnectFunction(std::string name, std::function<void()> func){ void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str()); ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str());
if (connectFunktionMap == NULL) { if (connectFunktionMap == NULL) {
@@ -488,7 +494,6 @@ void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
} }
} }
void MQTTunregisterConnectFunction(std::string name){ void MQTTunregisterConnectFunction(std::string name){
ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str()); ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str());
if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) { if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
@@ -496,7 +501,6 @@ void MQTTunregisterConnectFunction(std::string name){
} }
} }
void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){ void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
ESP_LOGD(TAG, "registerSubscribeFunction %s", topic.c_str()); ESP_LOGD(TAG, "registerSubscribeFunction %s", topic.c_str());
if (subscribeFunktionMap == NULL) { if (subscribeFunktionMap == NULL) {
@@ -511,7 +515,6 @@ void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::st
(*subscribeFunktionMap)[topic] = func; (*subscribeFunktionMap)[topic] = func;
} }
void MQTTdestroySubscribeFunction(){ void MQTTdestroySubscribeFunction(){
if (subscribeFunktionMap != NULL) { if (subscribeFunktionMap != NULL) {
if (mqtt_connected) { if (mqtt_connected) {

View File

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

View File

@@ -12,6 +12,7 @@
#include "interface_mqtt.h" #include "interface_mqtt.h"
#include "time_sntp.h" #include "time_sntp.h"
#include "../../include/defines.h" #include "../../include/defines.h"
#include "basic_auth.h"
@@ -21,6 +22,7 @@ static const char *TAG = "MQTT SERVER";
extern const char* libfive_git_version(void); extern const char* libfive_git_version(void);
extern const char* libfive_git_revision(void); extern const char* libfive_git_revision(void);
extern const char* libfive_git_branch(void); extern const char* libfive_git_branch(void);
extern std::string getFwVersion(void);
std::vector<NumberPost*>* NUMBERS; std::vector<NumberPost*>* NUMBERS;
bool HomeassistantDiscovery = false; bool HomeassistantDiscovery = false;
@@ -31,10 +33,11 @@ std::string rateUnit = "Unit/Minute";
float roundInterval; // Minutes float roundInterval; // Minutes
int keepAlive = 0; // Seconds int keepAlive = 0; // Seconds
bool retainFlag; bool retainFlag;
static std::string maintopic; static std::string maintopic, domoticzintopic;
bool sendingOf_DiscoveryAndStaticTopics_scheduled = true; // Set it to true to make sure it gets sent at least once after startup 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) { void mqttServer_setParameter(std::vector<NumberPost*>* _NUMBERS, int _keepAlive, float _roundInterval) {
NUMBERS = _NUMBERS; NUMBERS = _NUMBERS;
keepAlive = _keepAlive; keepAlive = _keepAlive;
@@ -48,6 +51,15 @@ void mqttServer_setMeterType(std::string _meterType, std::string _valueUnit, std
rateUnit = _rateUnit; 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, 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, std::string name, std::string icon, std::string unit, std::string deviceClass, std::string stateClass, std::string entityCategory,
int qos) { int qos) {
@@ -68,11 +80,21 @@ bool sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
name = group + " " + name; name = group + " " + name;
} }
if (field == "problem") { // Special binary sensor which is based on error topic /**
topicFull = "homeassistant/binary_sensor/" + maintopic + "/" + configTopic + "/config"; * 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";
} }
else { else {
topicFull = "homeassistant/sensor/" + maintopic + "/" + configTopic + "/config"; topicFull = "homeassistant/sensor/" + node_id + "/" + configTopic + "/config";
} }
/* See https://www.home-assistant.io/docs/mqtt/discovery/ */ /* See https://www.home-assistant.io/docs/mqtt/discovery/ */
@@ -84,7 +106,7 @@ bool sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
"\"icon\": \"mdi:" + icon + "\","; "\"icon\": \"mdi:" + icon + "\",";
if (group != "") { if (group != "") {
if (field == "problem") { // Special binary sensor which is based on error topic if (field == "problem") { // Special case: Binary sensor which is based on error topic
payload += "\"state_topic\": \"~/" + group + "/error\","; payload += "\"state_topic\": \"~/" + group + "/error\",";
payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\","; payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\",";
} }
@@ -93,10 +115,13 @@ bool sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
} }
} }
else { else {
if (field == "problem") { // Special binary sensor which is based on error topic if (field == "problem") { // Special case: Binary sensor which is based on error topic
payload += "\"state_topic\": \"~/error\","; payload += "\"state_topic\": \"~/error\",";
payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\","; 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 { else {
payload += "\"state_topic\": \"~/" + field + "\","; payload += "\"state_topic\": \"~/" + field + "\",";
} }
@@ -151,6 +176,7 @@ bool MQTThomeassistantDiscovery(int qos) {
// Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category // 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("", "uptime", "Uptime", "clock-time-eight-outline", "s", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "MAC", "MAC Address", "network-outline", "", "", "", "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("", "hostname", "Hostname", "network-outline", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "freeMem", "Free Memory", "memory", "B", "", "measurement", "diagnostic", qos); allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "freeMem", "Free Memory", "memory", "B", "", "measurement", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "wifiRSSI", "Wi-Fi RSSI", "wifi", "dBm", "signal_strength", "", "diagnostic", qos); allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "wifiRSSI", "Wi-Fi RSSI", "wifi", "dBm", "signal_strength", "", "diagnostic", qos);
@@ -158,6 +184,7 @@ bool MQTThomeassistantDiscovery(int qos) {
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "interval", "Interval", "clock-time-eight-outline", "min", "" , "measurement", "diagnostic", qos); allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "interval", "Interval", "clock-time-eight-outline", "min", "" , "measurement", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "IP", "IP", "network-outline", "", "", "", "diagnostic", qos); allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "IP", "IP", "network-outline", "", "", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "status", "Status", "list-status", "", "", "", "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) { for (int i = 0; i < (*NUMBERS).size(); ++i) {
@@ -166,14 +193,26 @@ bool MQTThomeassistantDiscovery(int qos) {
group = ""; 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 // Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "value", "Value", "gauge", valueUnit, meterType, "total_increasing", "", qos); 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", "", "", "", "diagnostic", qos); allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "raw", "Raw Value", "raw", valueUnit, meterType, "measurement", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "error", "Error", "alert-circle-outline", "", "", "", "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_digitalization_round */ /* Not announcing "rate" as it is better to use rate_per_time_unit resp. rate_per_digitization_round */
// allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate", "Rate (Unit/Minute)", "swap-vertical", "", "", "", ""); // Legacy, always Unit per Minute // 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, "", "measurement", "", qos); allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_time_unit", "Rate (" + rateUnit + ")", "swap-vertical", rateUnit, rate_device_class, "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, "rate_per_digitization_round", "Change since last Digitization 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, "timestamp", "Timestamp", "clock-time-eight-outline", "", "timestamp", "", "diagnostic", qos);
allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "json", "JSON", "code-json", "", "", "", "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 allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "problem", "Problem", "alert-outline", "", "problem", "", "", qos); // Special binary sensor which is based on error topic
@@ -244,6 +283,7 @@ bool publishStaticData(int qos) {
int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL); 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 + "/" + "MAC", getMac(), qos, retainFlag);
allSendsSuccessed |= MQTTPublish(maintopic + "/" + "IP", *getIPAddress(), qos, retainFlag); allSendsSuccessed |= MQTTPublish(maintopic + "/" + "IP", *getIPAddress(), qos, retainFlag);
allSendsSuccessed |= MQTTPublish(maintopic + "/" + "hostname", wlan_config.hostname, qos, retainFlag); allSendsSuccessed |= MQTTPublish(maintopic + "/" + "hostname", wlan_config.hostname, qos, retainFlag);
@@ -308,7 +348,7 @@ void register_server_mqtt_uri(httpd_handle_t server) {
uri.method = HTTP_GET; uri.method = HTTP_GET;
uri.uri = "/mqtt_publish_discovery"; uri.uri = "/mqtt_publish_discovery";
uri.handler = scheduleSendingDiscovery_and_static_Topics; uri.handler = APPLY_BASIC_AUTH_FILTER(scheduleSendingDiscovery_and_static_Topics);
uri.user_ctx = (void*) ""; uri.user_ctx = (void*) "";
httpd_register_uri_handler(server, &uri); httpd_register_uri_handler(server, &uri);
} }
@@ -336,4 +376,9 @@ std::string mqttServer_getMainTopic() {
return maintopic; return maintopic;
} }
void mqttServer_setDmoticzInTopic( std::string _domoticzintopic) {
domoticzintopic = _domoticzintopic;
}
#endif //ENABLE_MQTT #endif //ENABLE_MQTT

View File

@@ -12,6 +12,9 @@ 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 mqttServer_setMeterType(std::string meterType, std::string valueUnit, std::string timeUnit,std::string rateUnit);
void setMqtt_Server_Retain(bool SetRetainFlag); void setMqtt_Server_Retain(bool SetRetainFlag);
void mqttServer_setMainTopic( std::string maintopic); void mqttServer_setMainTopic( std::string maintopic);
void mqttServer_setDmoticzInTopic( std::string domoticzintopic);
std::string mqttServer_getMainTopic(); std::string mqttServer_getMainTopic();
void register_server_mqtt_uri(httpd_handle_t server); void register_server_mqtt_uri(httpd_handle_t server);
@@ -22,6 +25,7 @@ std::string getTimeUnit(void);
void GotConnected(std::string maintopic, bool SetRetainFlag); void GotConnected(std::string maintopic, bool SetRetainFlag);
esp_err_t sendDiscovery_and_static_Topics(void); esp_err_t sendDiscovery_and_static_Topics(void);
std::string createNodeId(std::string &topic);
#endif //SERVERMQTT_H #endif //SERVERMQTT_H
#endif //ENABLE_MQTT #endif //ENABLE_MQTT

View File

@@ -206,6 +206,7 @@ bool CTfLiteClass::MakeAllocate()
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::MakeAllocate"); LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "CTfLiteClass::MakeAllocate");
this->interpreter = new tflite::MicroInterpreter(this->model, resolver, this->tensor_arena, this->kTensorArenaSize); 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!");
if (this->interpreter) if (this->interpreter)
{ {
@@ -245,9 +246,18 @@ void CTfLiteClass::GetInputTensorSize()
long CTfLiteClass::GetFileSize(std::string filename) long CTfLiteClass::GetFileSize(std::string filename)
{ {
struct stat stat_buf; struct stat stat_buf;
long rc = stat(filename.c_str(), &stat_buf); long rc = -1;
return rc == 0 ? stat_buf.st_size : -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;
} }
@@ -269,25 +279,33 @@ bool CTfLiteClass::ReadFileToModel(std::string _fn)
LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Loading Model " + _fn + " /size: " + std::to_string(size) + " bytes..."); LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Loading Model " + _fn + " /size: " + std::to_string(size) + " bytes...");
#ifdef DEBUG_DETAIL_ON #ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile start"); LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile start");
#endif #endif
modelfile = (unsigned char*)psram_get_shared_model_memory(); modelfile = (unsigned char*)psram_get_shared_model_memory();
if(modelfile != NULL) if (modelfile != NULL)
{ {
FILE* f = fopen(_fn.c_str(), "rb"); // previously only "r FILE *pFile = fopen(_fn.c_str(), "rb"); // previously only "rb
fread(modelfile, 1, size, f);
fclose(f); if (pFile != NULL)
{
fread(modelfile, 1, size, pFile);
fclose(pFile);
#ifdef DEBUG_DETAIL_ON #ifdef DEBUG_DETAIL_ON
LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile successful"); LogFile.WriteHeapInfo("CTLiteClass::Alloc modelfile successful");
#endif #endif
return true; return true;
} }
else
{
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Model does not exist");
return false;
}
}
else else
{ {
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Can't allocate enough memory: " + std::to_string(size)); LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "CTfLiteClass::ReadFileToModel: Can't allocate enough memory: " + std::to_string(size));

View File

@@ -0,0 +1,7 @@
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

@@ -0,0 +1,170 @@
#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

@@ -0,0 +1,17 @@
#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

@@ -0,0 +1,107 @@
#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

@@ -0,0 +1,8 @@
#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,6 +49,9 @@
#define ets_delay_us(a) esp_rom_delay_us(a) #define ets_delay_us(a) esp_rom_delay_us(a)
#endif #endif
#include "../esp-protocols/components/mdns/include/mdns.h"
static const char *TAG = "WIFI"; static const char *TAG = "WIFI";
static bool APWithBetterRSSI = false; static bool APWithBetterRSSI = false;
@@ -480,7 +483,8 @@ static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_
if (WIFIReconnectCnt >= 10) { if (WIFIReconnectCnt >= 10) {
WIFIReconnectCnt = 0; WIFIReconnectCnt = 0;
LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Disconnected, multiple reconnect attempts failed (" + LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Disconnected, multiple reconnect attempts failed (" +
std::to_string(disconn->reason) + "), still retrying..."); std::to_string(disconn->reason) + "), retrying after 5s");
vTaskDelay(5000 / portTICK_PERIOD_MS); // Delay between the reconnections
} }
} }
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED) else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED)
@@ -656,6 +660,14 @@ esp_err_t wifi_init_sta(void)
else { else {
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Set hostname to: " + wlan_config.hostname); 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"); LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init successful");

View File

@@ -145,6 +145,29 @@ int LoadWlanFromFile(std::string fn)
wlan_config.dns = tmp; wlan_config.dns = tmp;
LogFile.WriteToFile(ESP_LOG_INFO, TAG, "DNS: " + wlan_config.dns); 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)) #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")){ else if ((splitted.size() > 1) && (toUpper(splitted[0]) == "RSSITHRESHOLD")){
tmp = trim(splitted[1]); tmp = trim(splitted[1]);

View File

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

View File

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

View File

@@ -0,0 +1,43 @@
#include "openmetrics.h"
/**
* create a singe metric from the given input
**/
std::string createMetric(const std::string &metricName, const std::string &help, const std::string &type, const std::string &value)
{
return "# HELP " + metricName + " " + help + "\n" +
"# TYPE " + metricName + " " + type + "\n" +
metricName + " " + value + "\n";
}
/**
* Generate the MetricFamily from all available sequences
* @returns the string containing the text wire format of the MetricFamily
**/
std::string createSequenceMetrics(std::string prefix, const std::vector<NumberPost *> &numbers)
{
std::string res;
for (const auto &number : numbers)
{
// only valid data is reported (https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#missing-data)
if (number->ReturnValue.length() > 0)
{
auto label = number->name;
// except newline, double quote, and backslash (https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#abnf)
// to keep it simple, these characters are just removed from the label
replaceAll(label, "\\", "");
replaceAll(label, "\"", "");
replaceAll(label, "\n", "");
res += prefix + "_flow_value{sequence=\"" + label + "\"} " + number->ReturnValue + "\n";
}
}
// prepend metadata if a valid metric was created
if (res.length() > 0)
{
res = "# HELP " + prefix + "_flow_value current value of meter readout\n# TYPE " + prefix + "_flow_value gauge\n" + res;
}
return res;
}

View File

@@ -0,0 +1,15 @@
#pragma once
#ifndef OPENMETRICS_H
#define OPENMETRICS_H
#include <string>
#include <fstream>
#include <vector>
#include "ClassFlowDefineTypes.h"
std::string createMetric(const std::string &metricName, const std::string &help, const std::string &type, const std::string &value);
std::string createSequenceMetrics(std::string prefix, const std::vector<NumberPost *> &numbers);
#endif // OPENMETRICS_H

View File

@@ -1,3 +1,15 @@
manifest_hash: 63f5c6c9f0bcebc7b9ca12d2aa8b26b2c5f5218d377dc4b2375d9b9ca1df7815 dependencies:
espressif/esp-nn:
component_hash: f6f2851ce82137a66e4265071c9b852bbe0130b882a18dea9f03faea7bf1295a
source:
service_url: https://api.components.espressif.com/
type: service
version: 1.1.0
idf:
component_hash: null
source:
type: idf
version: 5.3.1
manifest_hash: f88c9e5c2d75a9d5d6968fc67a90ef0cd7146dd6a3905a79c4dfcfc3b4fe6731
target: esp32 target: esp32
version: 1.0.0 version: 1.0.0

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