Compare commits

..
Author SHA1 Message Date
ESPEasy release bot 33281c08c2 automatically updated release notes for mega-20181007 2018-10-07 04:00:09 +02:00
Gijs NoorlanderandGitHub 461aee26ad Merge pull request #1861 from TD-er/feature/debug_esp32_wrover_kit
Move stack to user memory space and close file handles + Add WROVER dev kit debug support
2018-10-06 23:19:18 +02:00
Gijs NoorlanderandGitHub 2b0b14b2e8 Merge pull request #1853 from blenk92/XSS
Fix XSS-Vulnerabilites on wifi configuration pages
2018-10-06 22:56:47 +02:00
Gijs NoorlanderandGitHub b7404666b1 Merge pull request #1851 from blenk92/mega
Force slash to be converted in htmlEscape
2018-10-06 22:56:37 +02:00
Gijs NoorlanderandGitHub da25aa87dd Merge pull request #1733 from giig1967g/new/invertvalue
Add four new TOGGLE commands
2018-10-06 22:55:57 +02:00
TD-er 10a1e634e2 [SPIFFS] Make sure to close open files on SPIFFS 2018-10-06 22:36:41 +02:00
TD-er 83f86449b9 [Stack] Move Arduino 'cont' stack into user RAM
As suggested [here](https://github.com/letscontrolit/ESPEasy/pull/1858#issuecomment-427578956) the previous used flag may also enable WPS.
So I used [this suggestion](https://github.com/esp8266/Arduino/issues/5148#issuecomment-424334261) to only re-allocate the stack at link time.
2018-10-06 20:01:39 +02:00
TD-er eee337d3e3 [ESP32] Allow Wrover dev kit to be used for PIO debug
Initial setup to be able to debug ESP32 Wrover dev kit from within Visual Studio Code + PIO plus.
2018-10-06 18:31:17 +02:00
ESPEasy release bot c549ecd329 automatically updated release notes for mega-20181006 2018-10-06 04:00:13 +02:00
Gijs NoorlanderandGitHub d9e682668d Merge pull request #1858 from TD-er/bugfix/increase_stack_5k
[Stack] Increase stack to 5k and reduce stack allocations in rules
2018-10-06 00:57:31 +02:00
TD-er e38072ac24 [Build flags] Remove NO_EXTRA_4K_HEAP
Core is now set to 2.4.1 again, so this flag is not needed anymore.
Also not sure if it did fix something in 2.4.2 core.
2018-10-06 00:53:53 +02:00
TD-er 6aebeba5dc [WiFi] Add delay to connection attempts in ControllerSettings
As suggested by @s0170071 [here](https://github.com/letscontrolit/ESPEasy/issues/1774#issuecomment-425038026)
2018-10-06 00:50:43 +02:00
TD-er da01c8f469 [Stack] Increase stack to 5k and reduce stack allocations in rules
Removed some unneeded stack allocations of 240 bytes in the rules processing.

Also gave the `process_system_event_queue()` a bit more priority to make sure it will be looked at at least once every 500 msec.
2018-10-05 00:52:22 +02:00
ESPEasy release bot b3b68856f0 automatically updated release notes for mega-20181004 2018-10-04 04:00:08 +02:00
Max bec5cb5334 Fix XSS-Vulnerabilites on wifi configuration pages
Add escaping of wifi network names that can be discovered using the search
functionality of for instantce the /setup page. As these names are also used
inside an html tag, a stronger html encoding variant has been added.
2018-10-04 03:19:09 +02:00
Gijs NoorlanderandGitHub bda6011390 Merge pull request #1852 from TD-er/bugfix/wificlient_timeout
[#1830] WiFi client timeout & back to core 2.4.1
2018-10-04 00:56:09 +02:00
Gijs NoorlanderandGitHub f3fdb93a52 Merge pull request #1831 from JojoS62/mega
[P013_HCSR04] added error checking and logging
2018-10-04 00:54:02 +02:00
Gijs NoorlanderandGitHub 200b060b15 Merge pull request #1846 from thomastech/mega
Update _P075_Nextion.ino
2018-10-04 00:51:44 +02:00
Gijs NoorlanderandGitHub ff41cb2f94 Merge pull request #1849 from uzi18/patch9
- partial fix for #1723
2018-10-04 00:51:03 +02:00
TD-er c134eb6d13 [Core 2.4.1] Move back to core 2.4.1 from 2.4.2
PlatformIO `espressif8266@1.7.3` instead of `espressif8266@1.8.0`
2.4.2 has a lot of improvements like 4k of extra free memory.
But also the number of hardware watchdog reboots has increased a lot and the PWM related code no longer seems to work on 2.4.2
So for now, back to 2.4.1 library.
2018-10-04 00:24:28 +02:00
TD-er f9e2a211e1 [WiFiClient] Set timeout and make it configurable for controllers
The default timeout for wificlient is 1000 msec. This may cause all kind of strange effects when the node is being blocked for so long.
2018-10-04 00:21:00 +02:00
Max bd3d3f66f4 Force slash to be converted in htmlEscape
According to the owasp XSS prevention cheat sheet it is also necessary to encode / as it may helps to end html entities
(Source https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content)
2018-10-03 23:58:24 +02:00
Bartlomiej Zimon 3bad683211 - partial fix for #1723 2018-10-03 21:13:56 +00:00
TD-er 68f6e913a2 [sendHttp] #1830 Set timeout and early exit on timeout reached
See #1830
2018-10-03 23:10:47 +02:00
Plebs 96420faa2f added "mcpgpiotoggle" command 2018-10-03 22:07:42 +02:00
ThomasandGitHub 8eea77e4ed Update _P075_Nextion.ino (#1)
Added DEBUG_LOG define to reduce info log messages and prevent serial log flooding.
Added SendStatus() to post log message on browser to acknowledge HTTP write.
Added reserve() to minimize string memory allocations.
2018-10-03 09:02:02 -07:00
JojoS62 3d1f723787 Merge branch 'mega' of https://github.com/letscontrolit/ESPEasy into mega 2018-10-03 15:27:40 +02:00
JojoS62 5d459003e4 fixed 'unused variable' warning 2018-10-03 15:19:19 +02:00
JojoS62 ad208c357c code clean up
added default for filter size = 5.
clode clieanup: using constants, read setting into local vars for better readability,
2018-10-03 14:33:17 +02:00
ESPEasy release bot b1c777e6fd automatically updated release notes for mega-20181003 2018-10-03 04:00:18 +02:00
JojoS62 f5ab15c255 max distance depends on measurement unit
setting is in user units, ping function needs cm. Conversion added.
added unit to log output.
2018-10-02 17:41:23 +02:00
JojoS62 001ec6dcd2 added more settings: unit, filtertype and size
Measuring unit can be changed bewtween metric/imperial
Filtertype can none or median. If median a filtersize can be set.
Meauring value time to distance conversion now as float division, resulting in a higher resolution output.
2018-10-02 17:00:22 +02:00
JojoS62 15e5edccd8 added float calculation for time to distance conversion
returns higher resolution, especially for measuring in inches the integer resolution was low.
2018-10-02 16:57:33 +02:00
Gijs NoorlanderandGitHub 651353cc99 Merge pull request #1842 from crankyoldgit/patch-2
Acknowledge credit & origin of code used in _P016IR.ino
2018-10-02 13:41:35 +02:00
Gijs NoorlanderandGitHub 85f97551c5 Merge pull request #1841 from crankyoldgit/patch-1
Acknowledge credit & origin of code used in IRTX
2018-10-02 13:41:23 +02:00
David ConranandGitHub 6a158f68f5 Acknowledge credit & origin of code used in _P016IR.ino
FYI @TD-er

Ref: https://github.com/letscontrolit/ESPEasy/pull/1645#issuecomment-422253497
2018-10-02 21:36:18 +10:00
David ConranandGitHub 1933714de5 Acknowledge credit & origin of code used in IRTX
FYI @TD-er

Ref: https://github.com/letscontrolit/ESPEasy/pull/1645#issuecomment-422253497
2018-10-02 21:29:57 +10:00
ESPEasy release bot 545117ddf7 automatically updated release notes for mega-20181002 2018-10-02 04:00:29 +02:00
Gijs NoorlanderandGitHub 8eb479c411 Merge pull request #1837 from TD-er/bugfix/schedule_commands_yield
[Stack] Report stack usage on ESP32 and increase stack for ESP8266normal
2018-10-01 23:27:07 +02:00
TD-er b39f51ca3c [Stack] Report stack usage on ESP32 and increase stack for ESP8266normal
Stack usage on ESP32 is querying current stack, not statistics per RTOS task.
2018-10-01 22:15:32 +02:00
Gijs NoorlanderandGitHub 4511e08d3c Merge pull request #1805 from giig1967g/new/parse
split parseTemplate function
2018-10-01 17:12:21 +02:00
Gijs NoorlanderandGitHub 086e836956 Merge pull request #1836 from TD-er/feature/esp32_pio_1_4_0
[ESP32] Update to platform espressif32@1.4.0
2018-10-01 17:10:45 +02:00
Gijs NoorlanderandGitHub 3e20f617ea Merge pull request #1827 from TD-er/bugfix/DTH_Si7021_reading_stability
[#1798] Bugfix Sonoff Si7021 stability
2018-10-01 17:10:23 +02:00
TD-er 8d9aacb6a4 [ESP32] Update to PIO espressif32@1.4.0
[ESP32 IDF 3.1](https://github.com/espressif/esp-idf/releases/tag/v3.1)
[ESP32 PIO 1.4.0](https://github.com/platformio/platform-espressif32/releases/tag/v1.4.0)
2018-10-01 16:34:21 +02:00
TD-er 0670fa98a6 [ESP32] Add default partition table for reference 2018-10-01 16:32:20 +02:00
ESPEasy release bot 2b3d1517c9 automatically updated release notes for mega-20181001 2018-10-01 13:13:13 +02:00
Gijs NoorlanderandGitHub 0be79759d1 Merge pull request #1834 from TD-er/bugfix/detect_large_stack_allocs
[Stack] Move Arduino stack back to top of System stack instead of overlap
2018-10-01 01:25:38 +02:00
TD-er d47bede215 [Stack] Revert move Settings from stack to heap
Apparently the settings are allocated on the system stack and not on the Arduino stack.
This means it takes a lot of ram when allocated on the heap. So move it back to the system stack.
2018-10-01 00:51:04 +02:00
TD-er 2988a244b2 [Stack] Check if a block sent to save on SPIFFS is stack allocated 2018-10-01 00:42:01 +02:00
TD-er 8d87dc0175 [Heap] Use NO_EXTRA_4K_HEAP to get old stack address space
Originally the Arduino stack was placed on top of the system stack.
But since the system stack is mostly empty, it was decided to shift the Arduino stack to overlap the system stack to save an extra 4k of memory.

However, since a lot of Watchdog timer reboots are reported lately, this optimisation will now be reverted to see if it will improve stability.
This will use about 4k more RAM.
2018-10-01 00:40:55 +02:00
Gijs NoorlanderandGitHub 21c86e666a Merge pull request #1829 from TD-er/feature/1824_stack_stats
[#1824] Show stack size on main page
2018-09-30 19:37:16 +02:00
JojoS e6fdd3380a added error checking and logging
there were several errors that all resulted in a distance value reading of 0. Added an errorState that is printed to the log and helps troubleshooting.
Max. Distance checking can be turned off by setting max distance to 0 cm. If max. distance is used, exceeding the range will return a distance of 0 cm and print this to the log.
2018-09-30 15:23:36 +02:00
TD-er e04f71ab47 [#1824] Show stack size on main page
See #1824
2018-09-30 09:32:01 +02:00
ESPEasy release bot 90ae0720cf automatically updated release notes for mega-20180930 2018-09-30 04:00:24 +02:00
TD-er c8ecd8d374 [#1798] Bugfix Sonoff Si7021 stability
See #1798
2018-09-29 22:50:24 +02:00
Gijs NoorlanderandGitHub 7a451dd672 Merge pull request #1825 from TD-er/bugfix/proper_default_settings
Bugfix/proper default settings
2018-09-29 15:39:21 +02:00
Gijs NoorlanderandGitHub b06f6aa360 Merge pull request #1823 from JojoS62/mega
minor change: unit was missing for threshold in 'state' mode
2018-09-29 15:06:36 +02:00
TD-er 6b67415c71 [Defaults] Other default initializations 2018-09-29 15:05:10 +02:00
JojoS b095465d3a minor change: unit was missing for threshold in 'state' mode 2018-09-29 14:09:03 +02:00
Gijs NoorlanderandGitHub 81a5d911ba Merge pull request #1809 from JojoS62/mega
fixed distance reading
2018-09-29 13:38:44 +02:00
TD-er 48060d8d99 [Default Settings] Properly clear settings when reset to default 2018-09-29 12:40:29 +02:00
JojoS d303fa023f changed implementation to use shared_ptr instead of helper structure
this makes it easier to use this as a template for other sensors. No additional helper class/structure is needed.
2018-09-29 11:58:57 +02:00
JojoS 29b0cc1b32 removed sensordefs helper structure
to simplify the code
2018-09-27 22:00:01 +02:00
JojoS 584abd1e75 on INIT, delete sensordef before adding new 2018-09-27 14:19:54 +02:00
JojoS b4d8be0e59 fixed distance reading
the P_013_sensordef object was created on the stack and the destructor was called after leaving the PLUGIN_INIT. That deleted the included NewPingESP8266 object and using this object failed.
2018-09-27 11:56:31 +02:00
ESPEasy release bot 30f5c5cb7d automatically updated release notes for mega-20180927 2018-09-27 04:00:17 +02:00
Plebs 6e7286c6fb split parseTemplate function
simplifying code
2018-09-26 23:40:01 +02:00
Gijs NoorlanderandGitHub ae1db543ce Merge pull request #1804 from TD-er/bugfix/ESP32_partition_build
[ESP32] Split new partition layout to separate build
2018-09-26 22:52:30 +02:00
TD-er 947e1e0343 [Build] Add esp32test_1M8_partition build and warning on ESP32 partition 2018-09-26 22:49:30 +02:00
TD-er 0578d720f4 [ESP32] Split new partition layout to separate build
See "ESP32 not start after last upgrade" #1802
2018-09-26 21:55:02 +02:00
Gijs NoorlanderandGitHub 211d79bbd5 Merge pull request #1792 from TD-er/feature/ESP32_partition_table
[ESP32] Change partition size (will clear all settings) and add plugins
2018-09-26 09:05:44 +02:00
TD-er 91c5d60af9 [Info] Add board name to the sysinfo page. 2018-09-25 00:19:17 +02:00
TD-er 0d9bc8027d [ESP32] RTOS move handle_schedule() to core1 and increase stack
Enable RTOS flag in advanced settings (and reboot) to create separate threads on the 2nd ESP32 core, which will handle the scheduler.
This lowers stack usage and CPU load.
Also the ESP will no longer crash when saving large settings like for the Framed OLED plugin.
2018-09-25 00:18:46 +02:00
TD-er bd2bdab95c [Stack] Move Settings from stack to heap 2018-09-24 22:08:02 +02:00
TD-er c4f98fbc8e [Travis] Uninitialized variable in P073_7DGT 2018-09-24 20:13:24 +02:00
ESPEasy release bot b332a513b5 automatically updated release notes for mega-20180924 2018-09-24 04:00:20 +02:00
TD-er e36bb714f1 [ESP32] Change partition size (will clear all settings) and add plugins
The last update to > 0.12 increased the binary size a lot. This is mainly due to the added BLE support.
This makes it almost impossible to use the default partition table layout.

This changes the app partitions to 1.8 MB and reduces the SPIFFS to 320 k.
Changing the partition table will clear all settings, so make a backup of the settings.

Also added all plugins that would compile (not tested) for ESP32.

Known issue:
ESP32 might crash due to stack overflow when saving settings of plugins. (e.g. OLED framed plugin)
2018-09-24 00:23:45 +02:00
Gijs NoorlanderandGitHub 6e1cde343f Merge pull request #1791 from TD-er/bugfix/ESP32_I2C
[ESP32] Fix I2C handling to allow I2C devices to work
2018-09-23 22:14:43 +02:00
TD-er cce9ddd2dc [ESP32] Fix I2C handling to allow I2C devices to work
See this issue: [I2C repeated start broken](https://github.com/platformio/platform-espressif32/issues/126)
2018-09-23 21:17:55 +02:00
Gijs NoorlanderandGitHub 51be17a436 Merge pull request #1780 from clumsy-stefan/sensor_type_change
Change type of sensor for MCP and PCF devices
2018-09-23 20:18:38 +02:00
Gijs NoorlanderandGitHub 66d27a6697 Merge pull request #1776 from beigenmann/mega
Fix platformio
2018-09-23 20:17:33 +02:00
Gijs NoorlanderandGitHub a033e458fb Merge pull request #1782 from TD-er/bugfix/MQTT_reconnect_name
[MQTT] Work around for lost MQTT connection
2018-09-23 20:17:07 +02:00
Gijs NoorlanderandGitHub 494436bbff Merge pull request #1789 from sakinit/ESP32-to-core_esp32_1_3_0
ESP32: change to platform version core_esp32_1_3_0
2018-09-23 20:16:52 +02:00
sakinit 23bacd0762 change to platform version core_esp32_1_3_0 2018-09-23 17:49:47 +02:00
ESPEasy release bot f131254853 automatically updated release notes for mega-20180923 2018-09-23 04:00:12 +02:00
TD-er 657d15d962 [MQTT] Work around for lost MQTT connection
Maybe a fix for #1525
Meant to be a fix for #1530

It looks like the MQTT broker is refusing to accept a new connection from a specific client ID, as long as the broker thinks a client with that ID is still connected.
This work around adds the number of wifi reconnects to the clientID, to make the ID unique when a reconnect has to be made.
2018-09-23 00:54:55 +02:00
Gijs NoorlanderandGitHub 60910da48d Merge pull request #1749 from sakinit/ESP32-P1WifiGateway-updates
Esp32 p1 wifi gateway updates
2018-09-22 20:59:32 +02:00
Gijs NoorlanderandGitHub 6cee2d0f32 Merge pull request #1779 from TD-er/bugfix/BME280_slow_reading
[BME280] Fix slow reading of BME280 causing watchdog resets
2018-09-22 20:45:20 +02:00
stefan 533cb88a64 Change type of sensor for MCP and PCF devices
MCP and PCF devices should be of type SWNSOR_TYPE_SWITCH instead of SENSOR_TYPE_SINGLE so that the controllers can identify them correctly as switches (for GPIO related functions)
2018-09-22 20:41:53 +02:00
TD-er ffa32fe851 [BME280] Fix slow reading of BME280 causing watchdog resets
The plugin still had some delay and an active polling to see if the reading was ready.
This  took more than 1.5 sec per reading, which could trigger a Watchdog reset.
2018-09-22 20:34:56 +02:00
Gijs NoorlanderandGitHub b900cc9389 Merge pull request #1777 from TD-er/bugfix/MQTTimport
[MQTT import] Fix crash at boot when plugin is enabled
2018-09-22 19:13:25 +02:00
TD-er 8e11c19af6 [MQTT import] Fix crash at boot when plugin is enabled
See #1722
Inspired by [this comment](https://github.com/letscontrolit/ESPEasy/issues/1722#issuecomment-422191721) of @kainhofer
2018-09-22 16:39:16 +02:00
Benno Eigenmann f33ca6df78 Fix platformio 2018-09-22 15:57:09 +02:00
ESPEasy release bot 194a230d20 automatically updated release notes for mega-20180922 2018-09-22 04:00:22 +02:00
Gijs NoorlanderandGitHub 7a5a432016 Merge pull request #1773 from TD-er/reapply_reverts
Reapply reverts
2018-09-22 02:04:30 +02:00
TD-er 07511fe144 Revert "Revert "Fix elseif & Add if-elseif-else nesting levels""
This reverts commit a4fe8d42d2.
2018-09-21 22:15:13 +02:00
Gijs Noorlander 9a390136f9 Revert "Revert "Added 2 new operators in Calculate() function""
This reverts commit fa42cadfa1.
2018-09-21 22:14:30 +02:00
Gijs NoorlanderandGitHub 27a03f166a Merge pull request #1770 from TD-er/bugfix/revert_disable_command_scheduler_0915
Revert "[Scheduler] Disable command scheduler"
2018-09-21 22:10:50 +02:00
TD-er 0a63aeb8f0 Revert "[Scheduler] Disable command scheduler"
This reverts commit 38af765935.
2018-09-20 23:20:19 +02:00
sakinit 22c10ac615 ESP32 platform updated to 1.2.0; Webserver replaced by platform one 2018-09-16 16:44:25 +02:00
ESPEasy release bot ac83cfa249 automatically updated release notes for mega-20180916 2018-09-16 04:00:11 +02:00
Gijs NoorlanderandGitHub 6ef0c08bc4 Merge pull request #1754 from TD-er/bugfix/backgroundtasks_rules
[HW Watchdog] Backgroundtasks instead of yield during rules handling
2018-09-16 01:19:47 +02:00
TD-er 1ee965067d [HW Watchdog] Backgroundtasks instead of yield during rules handling 2018-09-16 01:19:14 +02:00
Gijs NoorlanderandGitHub e46a873fce Merge pull request #1753 from letscontrolit/revert-1641-mega
Revert "Fix elseif & Add if-elseif-else nesting levels"
2018-09-16 01:15:04 +02:00
Gijs NoorlanderandGitHub 784e956c96 Merge pull request #1752 from letscontrolit/revert-1742-new/not
Revert "Added 2 new operators in Calculate() function"
2018-09-16 01:14:32 +02:00
Gijs NoorlanderandGitHub b6eebb330a Added warning to release notes 20180915 2018-09-16 01:13:49 +02:00
Gijs NoorlanderandGitHub a4fe8d42d2 Revert "Fix elseif & Add if-elseif-else nesting levels" 2018-09-16 01:08:42 +02:00
Gijs NoorlanderandGitHub fa42cadfa1 Revert "Added 2 new operators in Calculate() function" 2018-09-16 01:04:37 +02:00
sakinit 17dc6fa859 Reverted Webserver change 2018-09-15 16:22:58 +02:00
sakinit 1432726dec ESP32: Split webserver spiffs filelist into pages 2018-09-15 12:14:33 +02:00
sakinit 7ba6ffa407 Fix ESP32 stack overflow in addPinSelect when called from P1WifiGateway
In addFormPinSelect move local variables from the stack to the heap
because when it is called from the P1WifiGateway there is not enough
stack space resulting in a stack overflow.
2018-09-15 12:14:27 +02:00
sakinit ab555e4d6b ESP32 build issues fixed
- Compiler issue of comment within comment
 - ESP32Webserver renamed to Webserver in ESP32 Arduino library
2018-09-15 12:14:22 +02:00
ESPEasy release bot d4259f4e23 automatically updated release notes for mega-20180915 2018-09-15 04:00:15 +02:00
Gijs NoorlanderandGitHub aef45c06f6 Merge pull request #1747 from TD-er/bugfix/sunrise
[#1698] Incorrect sunrise value southern hemisphere
2018-09-15 00:19:42 +02:00
Gijs NoorlanderandGitHub 828f9e6a30 Merge pull request #1746 from TD-er/feature/hostname_settings
Validate settings + hostname format option
2018-09-15 00:14:30 +02:00
TD-er e79d778cf4 [#1698] Incorrect sunrise value southern hemisphere
See #1698
2018-09-15 00:10:45 +02:00
TD-er 965eb2d994 [#1713] Make hostname-unitnumber optional & validate settings
See #1713
Also added validation check for some values in the settings at load/save of settings.
This could be extended later on for task settings.
2018-09-14 23:44:58 +02:00
Gijs NoorlanderandGitHub 657fccf49f Merge pull request #1641 from svmac/mega
Fix elseif & Add if-elseif-else nesting levels
2018-09-14 23:27:00 +02:00
Gijs NoorlanderandGitHub 228b41a1ac Merge pull request #1742 from giig1967g/new/not
Added 2 new operators in Calculate() function
2018-09-14 23:26:25 +02:00
Gijs NoorlanderandGitHub 3bba294eb7 Merge pull request #1745 from TD-er/bugfix/commands_not_using_scheduler
[Scheduler] Disable command scheduler
2018-09-14 23:22:21 +02:00
TD-er 0254181b3e [Controller settings] Validate settings on load/save
Make sure new values are set to proper defaults and within valid range.
2018-09-14 22:54:23 +02:00
Gijs NoorlanderandGitHub 3b67282abb Merge branch 'mega' into mega 2018-09-14 21:26:21 +02:00
TD-er 38af765935 [Scheduler] Disable command scheduler
For now the commands will no longer use the scheduler.
Commands running asynchronous is causing too much issues.
2018-09-14 21:23:09 +02:00
Plebs ff180b085c Added 2 new operators in Calculate
hi,
added 2 new operators for calculations:

!: Logical NOT:
returns 1 if operand is = 0
returns 0 if operand is != 0

%: MOD:
converts operands in integers and calculates the remainder of the division
2018-09-14 16:44:11 +02:00
ESPEasy release bot e0785eb796 automatically updated release notes for mega-20180914 2018-09-14 04:00:17 +02:00
Gijs NoorlanderandGitHub 75a83787a4 Merge pull request #1740 from TD-er/bugfix/disable_failing_plugin
[CrashRecover] Disable failing step based on failed boot count
2018-09-14 00:18:48 +02:00
Gijs NoorlanderandGitHub 65bea6343c Merge pull request #1734 from giig1967g/new/eventvalue
adding more parameters to EVENT
2018-09-14 00:15:41 +02:00
Gijs NoorlanderandGitHub 6fe61411a0 Added PayPal link 2018-09-14 00:10:48 +02:00
Gijs NoorlanderandGitHub 4552e91022 Merge pull request #1731 from giig1967g/new/calculate
Use parameters inside rules when calling commands
2018-09-14 00:06:13 +02:00
Gijs NoorlanderandGitHub cc94d70e6c Merge pull request #1730 from sakinit/feature-webserver-spiffs-filelist-multiple-pages
Feature: Split webserver spiffs filelist into pages
2018-09-13 23:50:11 +02:00
Gijs NoorlanderandGitHub 2435078f76 Merge pull request #1732 from TD-er/feature/flash_tools
[Flash tools] Add blank files and README.txt to dist folder
2018-09-13 23:49:43 +02:00
Gijs NoorlanderandGitHub dd2cd50d4b Merge pull request #1738 from giddyhup/mega
Fix IR plugin passing received code
2018-09-13 23:48:46 +02:00
TD-er fe38eb629d [CrashRecover] Disable failing step based on failed boot count
When the node gets locked in a boot loop, the only recovery is to erase it and start all over.
This fix will count the number of failed boots and above a certain threshold it will start disabling plugin, then controller and then notification.

Only one will be disabled at once, so the user can see which one is giving issues.
The disabled state will not be saved, so make sure to save the failing part when it is accessible again.
2018-09-13 23:44:24 +02:00
Plebs e961507456 added %eventvalue4% 2018-09-13 19:14:13 +02:00
Plebs e5ee5644bf final version with '=' sign as a prefix to identify the formula in rules 2018-09-12 22:48:44 +02:00
Gijs NoorlanderandGitHub ac6d85e214 Merge branch 'mega' into mega 2018-09-12 21:54:50 +02:00
Markus Gloede 39c2d54aee Fix IR plugin passing received code 2018-09-12 21:09:05 +02:00
Plebs 68efd5ff9e adding more parameters to EVENT
Hi,
adding the possibility to have 3 parameters when calling an event:
event,eventname=p1,p2,p3

The variable name are:
param 1: %eventvalue% or %eventvalue1%
param 2: %eventvalue2%
param 3: %eventvalue3%
2018-09-11 17:38:47 +02:00
Plebs 627f516f85 fixed calls to F-macro 2018-09-11 16:03:35 +02:00
Plebs a45fadf42e fixed ESP32 compatibility issue 2018-09-11 14:38:14 +02:00
Plebs 2ae52b849c few changes
optimized the call to CALCULATE only when needed and description of error codes.
2018-09-11 13:10:00 +02:00
Plebs 639685ea0d fixed float to int conversion 2018-09-11 10:16:44 +02:00
Plebs 867209de6d Add three new TOGGLE commands
Added three new commands to toggle the pins from 0 to 1 or viceversa and to toggle the task value:

Command: taskvaluetoggle
P001: gpiotoggle
P019:pcfgpiotoggle
2018-09-11 00:38:55 +02:00
TD-er 1d8b6d346b [Flash tools] Add blank files and README.txt 2018-09-10 23:02:38 +02:00
Plebs 2a5ac327d3 Use parameters inside rules when calling commands
Hi,
here is a PR for using parameters when calling commands from inside the rules.

The scope is to be able to use formulas instead of an integer when calling a command inside the rules.

Example:
taskvalueset,1,%eventvalue%+65,[Relay1#r1]+1

Usage could be:

Assuming you have a PCF8574 with ports from 65 to 72.

You can write a rule:

on turnOnRelay do
  pcfgpio,%eventvalue%+64,0
endon

And to turn on port65, the rule can be called like this:

event,turnOn=1
2018-09-10 22:59:50 +02:00
sakinit 886101d4d4 Feature: Split webserver spiffs filelist into pages 2018-09-10 17:37:05 +02:00
ESPEasy release bot 8fc6486855 automatically updated release notes for mega-20180910 2018-09-10 04:00:23 +02:00
Gijs NoorlanderandGitHub eeb1cc71b3 Merge pull request #1728 from TD-er/bugfix/command_send_http
Bugfix/command SendToHTTP  & Domoticz IDX > 9999
2018-09-10 01:02:58 +02:00
TD-er 13837830e8 [Domoticz IDX] Allow for IDX of > 9999 2018-09-09 23:00:16 +02:00
Gijs NoorlanderandGitHub f86ff46a82 Merge pull request #1727 from sakinit/P1WifiGatewayModuleBufSize
Reduced buffer size to prevent stack overflow
2018-09-09 22:53:23 +02:00
TD-er e901bc957a [HTTP] Command SendToHttp cannot connect
Incorrect check for return value.
As suggested via the [forum](https://www.letscontrolit.com/forum/viewtopic.php?f=6&t=5794&p=31203#p31181)
2018-09-09 21:58:14 +02:00
sakinit e7e10c5305 Reduced buffer size to prevent stack overflow 2018-09-09 19:54:23 +02:00
ESPEasy release bot 466ddfbe88 automatically updated release notes for mega-20180909 2018-09-09 04:00:14 +02:00
Gijs NoorlanderandGitHub c8f02d2a4c Merge pull request #1721 from TD-er/bugfix/wifi_connection_slow_server
[#1720] WiFi read all lines from slow servers
2018-09-08 23:14:33 +02:00
TD-er af1d9b38c9 [Serial log] Use buffer to prevent Serial buffer to overflow
Write the log lines to a std::deque and write that buffer to the serial port without overflow of the Serial buffer.
This flushing is done during background task.
2018-09-08 20:48:29 +02:00
Gijs NoorlanderandGitHub 7294217489 Revert [WDT] Add watchdog feed to backgroundtasks()
See comment: https://github.com/letscontrolit/ESPEasy/issues/1722#issuecomment-419659193
2018-09-08 20:31:16 +02:00
TD-er 208fa8a3aa [ESP32] Fix Build, ESP32 doesn't have the availableForWrite 2018-09-08 18:24:48 +02:00
TD-er b3b8eff127 [Serial Log] Limit serial log to prevent buffer overflow
As suggested here: https://github.com/letscontrolit/ESPEasy/issues/1625#issuecomment-411558353 by @thomastech
2018-09-08 16:19:58 +02:00
TD-er c6a90ab2d0 Add forward declaration for void backgroundtasks() 2018-09-08 16:00:06 +02:00
TD-er e7d28e8576 [#1720] WiFi read all lines from slow servers
See #1720
2018-09-08 15:20:39 +02:00
svmac 5511ee9f38 fix mistake 2018-08-15 05:22:27 +02:00
svmac 427a22d23b some code optimization 2018-08-15 04:54:29 +02:00
svmac d271898968 reenabled code about ! 2018-08-14 03:52:29 +02:00
svmac 4051f0bd2e Fix elseif & Add if-elseif-else nesting levels
- The implementation of elseif is not correct. See this example:

Rule:
On SYSVAL do
if %syssec% < 10
publish %sysname%/IP,%ip%
elseif %syssec% < 20
publish %sysname%/Uptime/min,%uptime%
elseif %syssec% < 30
publish %sysname%/Systime/time,%systime%
elseif %syssec% < 40
publish %sysname%/RSSI/dB,%rssi%
elseif %syssec% < 50
publish %sysname%/Sunrise/time,%sunrise%
else
publish %sysname%/Sunset/time,%sunset-30m%
endif
endon

Result:
109360661 : EVENT: SYSVAL
109360668 : [if 11 < 10]=false
109360675 : [elseif 11 < 20]=true //THIS IS CORRECT
109360677 : ACT : publish Wemos51/Uptime/min,1823
109360686 : Command: publish
109360692 : [elseif 11 < 30]=false
109360697 : [elseif 11 < 40]=false
109360703 : [elseif 11 < 50]=false
109360705 : ReplacementString SunTime: %sunrise% offset: 0
109360708 : else = true //THIS IS NOT CORRECT
109360710 : ReplacementString SunTime: %sunset-30m% offset: -1800
109360712 : ACT : publish Wemos51/Sunset/time,20:46
109360723 : Command: publish
109360729 : EVENT: SYSVAL Processing time:68 milliSeconds

- Added also nesting levels to if-elseif-else clausules define in RULES_IF_MAX_NESTING_LEVEL declaration. Example:

Rule:
On SYSVAL do
if %eventvalue% > 1
publish %sysname%/Sunrise/time,%sunrise+1h%
else
if %syssec% < 10
publish %sysname%/IP,%ip%
elseif %syssec% < 20
publish %sysname%/Uptime/min,%uptime%
elseif %syssec% < 30
publish %sysname%/Systime/time,%systime%
elseif %syssec% < 40
publish %sysname%/eventvalue,%eventvalue%
elseif %syssec% < 50
publish %sysname%/Sunrise/time,%sunrise%
else
publish %sysname%/Sunset/time,%sunset-30m%
endif
endif
endon

Result:
>event,SYSVAL=-5
4977875 : Command: event
4977876 : EVENT: SYSVAL=-5
4977883 : Lev.1: [if -5 > 1]=false
4977886 : ReplacementString SunTime: %sunrise+1h% offset: 3600
4977889 : Lev.1: [else]=true
4977893 : Lev.2: [if 30 < 10]=false
4977900 : Lev.2: [elseif 30 < 20]=false
4977906 : Lev.2: [elseif 30 < 30]=false
4977913 : Lev.2: [elseif 30 < 40]=true
4977916 : ACT : publish Wemos49/eventvalue,-5
4977932 : ReplacementString SunTime: %sunrise% offset: 0
4977935 : Lev.2: [else]=false
4977938 : ReplacementString SunTime: %sunset-30m% offset: -1800
4977944 : EVENT: SYSVAL=-5 Processing time:67 milliSeconds

- Finally, the substitution of %eventvalue% is done earlier so that it can be used in if sentence too.
2018-08-11 16:51:56 +02:00
56 changed files with 2280 additions and 773 deletions
+4
View File
@@ -18,3 +18,7 @@ lib/readme.txt
src/Custom.h
/ESPEasy
test/output_export.cpp
.vscode
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
+4 -4
View File
@@ -1,8 +1,8 @@
|Latest Nightly | Build Status | Patreon | Ko-Fi |
|-------|-------|-------|-------|
| [![GitHub version](https://img.shields.io/github/release/letscontrolit/ESPEasy/all.svg)](https://github.com/letscontrolit/ESPEasy/releases/latest) | [![Build Status](https://travis-ci.org/letscontrolit/ESPEasy.svg?branch=mega)](https://travis-ci.org/letscontrolit/ESPEasy) | [![donate](https://img.shields.io/badge/donate-Patreon-blue.svg)](https://www.patreon.com/GrovkillenTDer) | [![donate](https://img.shields.io/badge/donate-KoFi-blue.svg)](https://ko-fi.com/grovkillentder) |
|Latest Nightly | Build Status | Patreon | Ko-Fi | PayPal |
|-------|-------|-------|-------|-------|
| [![GitHub version](https://img.shields.io/github/release/letscontrolit/ESPEasy/all.svg)](https://github.com/letscontrolit/ESPEasy/releases/latest) | [![Build Status](https://travis-ci.org/letscontrolit/ESPEasy.svg?branch=mega)](https://travis-ci.org/letscontrolit/ESPEasy) | [![donate](https://img.shields.io/badge/donate-Patreon-blue.svg)](https://www.patreon.com/GrovkillenTDer) | [![donate](https://img.shields.io/badge/donate-KoFi-blue.svg)](https://ko-fi.com/grovkillentder) | [![donate](https://img.shields.io/badge/donate-PayPal-blue.svg)](https://www.paypal.me/espeasy) |
For ways to *support* us, see [this announcement on the forum](https://www.letscontrolit.com/forum/viewtopic.php?f=14&t=5787), or have a look at the [Patreon](https://www.patreon.com/GrovkillenTDer) or [Ko-Fi](https://ko-fi.com/grovkillentder) links above.
For ways to *support* us, see [this announcement on the forum](https://www.letscontrolit.com/forum/viewtopic.php?f=14&t=5787), or have a look at the [Patreon](https://www.patreon.com/GrovkillenTDer), [Ko-Fi](https://ko-fi.com/grovkillentder) or [PayPal](https://www.paypal.me/espeasy) links above.
# ESPEasy (development branch)
+2 -1
View File
@@ -22,7 +22,8 @@ for ENV in \
dev_ESP8266PUYA_1024_VCC\
hard_SONOFF_POW\
hard_Shelly_1\
esp32dev;\
esp32dev\
esp32test_1M8_partition;\
do
echo
echo "### Deploying environment $ENV for version $VERSION"
+61
View File
@@ -0,0 +1,61 @@
_____ ____ ____
| ____/ ___|| _ \ ___ __ _ ___ _ _
| _| \___ \| |_) / _ \/ _` / __| | | |
| |___ ___) | __/ __/ (_| \__ \ |_| |
|_____|____/|_| \___|\__,_|___/\__, |
|___/
This is the distribution folder for ESPeasy.
In here you will find a flash tool to program the ESP module.
Also a number of binary images is included.
The filename is quite descriptive:
ESP_Easy_mega-<date>_<buildType>_<chip>_<memorySize>.bin
Build type can be: (differ in included plugins)
- normal => Only Stable plugins and controllers
- test => Stable + Testing
- dev => Stable + Testing + Development
There is also a number of special builds:
- normal_IR => "Normal" + IR receiver/transmitter plugins and library
- hard_xxxxx => Special builds for some off-the-shelf hardware.
Chip can be:
- ESP8266 => Most likely option
- ESP8285 => Used in some Sonoff modules
- ESP32 => Experimental support at this moment
- ESP8266PUYA => For ESP modules with a flash chip labeled "PUYA" (often 1 MB)
The "PUYA" version deserves a bit more attention.
If you cannot save settings, better try to see if the flash chip has "PUYA" written on it.
If so, try the "PUYA" build.
MemorySize can be:
- 1024 => 1 MB flash modules (e.g. almost all Sonoff modules)
- 2048 => 2 MB flash modules (e.g. Shelly1/WROOM02)
- 4096 => 4 MB flash modules (e.g. NodeMCU/ESP32)
ESP32 now has 2 builds:
- esp32dev Using the default partition layout (1.4 MB for the sketch)
- esp32test_1M8_partition Larger sketch partition (1.8MB) smaller SPIFFS (316 kB)
Please note that changing between those versions will destroy the settings!
The SPIFFS partition will be lost and that contains all settings.
To help recover from a bad flash, there are also blank images included.
- blank_1MB.bin
- blank_2MB.bin
- blank_4MB.bin
When the wrong image is flashed, or the module behaves unstable, or is in a reboot loop,
flash these images first and then the right image for the module.
Another great flash tool can be found here: (Windows only)
https://github.com/Grovkillen/ESP_Easy_Flasher
For more information, see: https://github.com/letscontrolit/ESPEasy
Or our forum: https://www.letscontrolit.com/forum/
+287
View File
@@ -1,3 +1,290 @@
-------------------------------------------------
Changes in release mega-20181007 (since mega-20181006)
-------------------------------------------------
Release date: Sun Oct 7 04:00:09 CEST 2018
Max (2):
Force slash to be converted in htmlEscape
Fix XSS-Vulnerabilites on wifi configuration pages
Plebs (3):
Add three new TOGGLE commands
fixed float to int conversion
added "mcpgpiotoggle" command
TD-er (3):
[ESP32] Allow Wrover dev kit to be used for PIO debug
[Stack] Move Arduino 'cont' stack into user RAM
[SPIFFS] Make sure to close open files on SPIFFS
-------------------------------------------------
Changes in release mega-20181006 (since mega-20181004)
-------------------------------------------------
Release date: Sat Oct 6 04:00:13 CEST 2018
TD-er (3):
[Stack] Increase stack to 5k and reduce stack allocations in rules
[WiFi] Add delay to connection attempts in ControllerSettings
[Build flags] Remove NO_EXTRA_4K_HEAP
-------------------------------------------------
Changes in release mega-20181004 (since mega-20181003)
-------------------------------------------------
Release date: Thu Oct 4 04:00:08 CEST 2018
Bartlomiej Zimon (1):
- partial fix for #1723
JojoS (1):
added error checking and logging
JojoS62 (5):
added float calculation for time to distance conversion
added more settings: unit, filtertype and size
max distance depends on measurement unit
code clean up
fixed 'unused variable' warning
TD-er (3):
[sendHttp] #1830 Set timeout and early exit on timeout reached
[WiFiClient] Set timeout and make it configurable for controllers
[Core 2.4.1] Move back to core 2.4.1 from 2.4.2
Thomas (1):
Update _P075_Nextion.ino (#1)
-------------------------------------------------
Changes in release mega-20181003 (since mega-20181002)
-------------------------------------------------
Release date: Wed Oct 3 04:00:18 CEST 2018
David Conran (2):
Acknowledge credit & origin of code used in IRTX
Acknowledge credit & origin of code used in _P016IR.ino
-------------------------------------------------
Changes in release mega-20181002 (since mega-20181001)
-------------------------------------------------
Release date: Tue Oct 2 04:00:29 CEST 2018
Plebs (1):
split parseTemplate function
TD-er (4):
[#1798] Bugfix Sonoff Si7021 stability
[ESP32] Add default partition table for reference
[ESP32] Update to PIO espressif32@1.4.0
[Stack] Report stack usage on ESP32 and increase stack for ESP8266normal
-------------------------------------------------
Changes in release mega-20181001 (since mega-20180930)
-------------------------------------------------
Release date: Mon Oct 1 13:13:13 CEST 2018
TD-er (4):
[#1824] Show stack size on main page
[Heap] Use NO_EXTRA_4K_HEAP to get old stack address space
[Stack] Check if a block sent to save on SPIFFS is stack allocated
[Stack] Revert move Settings from stack to heap
-------------------------------------------------
Changes in release mega-20180930 (since mega-20180927)
-------------------------------------------------
Release date: Sun Sep 30 04:00:24 CEST 2018
JojoS (5):
fixed distance reading
on INIT, delete sensordef before adding new
removed sensordefs helper structure
changed implementation to use shared_ptr instead of helper structure
minor change: unit was missing for threshold in 'state' mode
TD-er (2):
[Default Settings] Properly clear settings when reset to default
[Defaults] Other default initializations
-------------------------------------------------
Changes in release mega-20180927 (since mega-20180924)
-------------------------------------------------
Release date: Thu Sep 27 04:00:17 CEST 2018
TD-er (7):
[ESP32] Change partition size (will clear all settings) and add plugins
[Travis] Uninitialized variable in P073_7DGT
[Stack] Move Settings from stack to heap
[ESP32] RTOS move handle_schedule() to core1 and increase stack
[Info] Add board name to the sysinfo page.
[ESP32] Split new partition layout to separate build
[Build] Add esp32test_1M8_partition build and warning on ESP32 partition
-------------------------------------------------
Changes in release mega-20180924 (since mega-20180923)
-------------------------------------------------
Release date: Mon Sep 24 04:00:20 CEST 2018
Benno Eigenmann (1):
Fix platformio
TD-er (2):
[MQTT] Work around for lost MQTT connection
[ESP32] Fix I2C handling to allow I2C devices to work
sakinit (1):
change to platform version core_esp32_1_3_0
stefan (1):
Change type of sensor for MCP and PCF devices
-------------------------------------------------
Changes in release mega-20180923 (since mega-20180922)
-------------------------------------------------
Release date: Sun Sep 23 04:00:12 CEST 2018
TD-er (2):
[MQTT import] Fix crash at boot when plugin is enabled
[BME280] Fix slow reading of BME280 causing watchdog resets
sakinit (5):
ESP32 build issues fixed
Fix ESP32 stack overflow in addPinSelect when called from P1WifiGateway
ESP32: Split webserver spiffs filelist into pages
Reverted Webserver change
ESP32 platform updated to 1.2.0; Webserver replaced by platform one
-------------------------------------------------
Changes in release mega-20180922 (since mega-20180916)
-------------------------------------------------
Release date: Sat Sep 22 04:00:22 CEST 2018
Gijs Noorlander (1):
Revert "Revert "Added 2 new operators in Calculate() function""
TD-er (2):
Revert "[Scheduler] Disable command scheduler"
Revert "Revert "Fix elseif & Add if-elseif-else nesting levels""
-------------------------------------------------
Changes in release mega-20180916 (since mega-20180915)
-------------------------------------------------
Release date: Sun Sep 16 04:00:11 CEST 2018
Gijs Noorlander (3):
Revert "Added 2 new operators in Calculate() function"
Revert "Fix elseif & Add if-elseif-else nesting levels"
Added warning to release notes 20180915
TD-er (1):
[HW Watchdog] Backgroundtasks instead of yield during rules handling
-------------------------------------------------
Changes in release mega-20180915 (since mega-20180914)
-------------------------------------------------
Release date: Sat Sep 15 04:00:15 CEST 2018
Known issue:
Causes reboots. (see [#1748](https://github.com/letscontrolit/ESPEasy/issues/1748) )
Plebs (1):
Added 2 new operators in Calculate
TD-er (4):
[Scheduler] Disable command scheduler
[Controller settings] Validate settings on load/save
[#1713] Make hostname-unitnumber optional & validate settings
[#1698] Incorrect sunrise value southern hemisphere
svmac (4):
Fix elseif & Add if-elseif-else nesting levels
reenabled code about !
some code optimization
fix mistake
-------------------------------------------------
Changes in release mega-20180914 (since mega-20180910)
-------------------------------------------------
Release date: Fri Sep 14 04:00:17 CEST 2018
Gijs Noorlander (1):
Added PayPal link
giddyhup (1):
Fix IR plugin passing received code
Plebs (7):
Use parameters inside rules when calling commands
few changes
fixed ESP32 compatibility issue
fixed calls to F-macro
adding more parameters to EVENT
final version with '=' sign as a prefix to identify the formula in rules
added %eventvalue4%
TD-er (2):
[Flash tools] Add blank files and README.txt
[CrashRecover] Disable failing step based on failed boot count
sakinit (1):
Feature: Split webserver spiffs filelist into pages
-------------------------------------------------
Changes in release mega-20180910 (since mega-20180909)
-------------------------------------------------
Release date: Mon Sep 10 04:00:22 CEST 2018
TD-er (2):
[HTTP] Command SendToHttp cannot connect
[Domoticz IDX] Allow for IDX of > 9999
sakinit (1):
Reduced buffer size to prevent stack overflow
-------------------------------------------------
Changes in release mega-20180909 (since mega-20180908)
-------------------------------------------------
Release date: Sun Sep 9 04:00:14 CEST 2018
Gijs Noorlander (1):
Revert [WDT] Add watchdog feed to backgroundtasks()
TD-er (5):
[#1720] WiFi read all lines from slow servers
Add forward declaration for void backgroundtasks()
[Serial Log] Limit serial log to prevent buffer overflow
[ESP32] Fix Build, ESP32 doesn't have the availableForWrite
[Serial log] Use buffer to prevent Serial buffer to overflow
-------------------------------------------------
Changes in release mega-20180908 (since mega-20180904)
-------------------------------------------------
+1
View File
File diff suppressed because one or more lines are too long
+1
View File
File diff suppressed because one or more lines are too long
+1
View File
File diff suppressed because one or more lines are too long
+7
View File
@@ -0,0 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x140000,
app1, app, ota_1, 0x150000,0x140000,
eeprom, data, 0x99, 0x290000,0x1000,
spiffs, data, spiffs, 0x291000,0x16F000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xe000 0x2000
4 app0 app ota_0 0x10000 0x140000
5 app1 app ota_1 0x150000 0x140000
6 eeprom data 0x99 0x290000 0x1000
7 spiffs data spiffs 0x291000 0x16F000
+7
View File
@@ -0,0 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x1D0000,
app1, app, ota_1, 0x1E0000,0x1D0000,
eeprom, data, 0x99, 0x3B0000,0x1000,
spiffs, data, spiffs, 0x3B1000,0x4F000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xe000 0x2000
4 app0 app ota_0 0x10000 0x1D0000
5 app1 app ota_1 0x1E0000 0x1D0000
6 eeprom data 0x99 0x3B0000 0x1000
7 spiffs data spiffs 0x3B1000 0x4F000
+75 -13
View File
@@ -6,12 +6,13 @@
// ---------------------------------------------------------------------------
#include "NewPingESP8266.h"
//#include "ESPEasy-Globals.h"
// ---------------------------------------------------------------------------
// NewPingESP8266 constructor
// ---------------------------------------------------------------------------
NewPingESP8266::NewPingESP8266(uint32_t trigger_pin, uint32_t echo_pin, unsigned int max_cm_distance) {
_errorState = STATUS_SENSOR_READY;
#if DO_BITWISE == true
_triggerBit = digitalPinToBitMask(trigger_pin); // Get the port register bitmask for the trigger pin.
_echoBit = digitalPinToBitMask(echo_pin); // Get the port register bitmask for the echo pin.
@@ -58,7 +59,10 @@ unsigned int NewPingESP8266::ping(unsigned int max_cm_distance) {
while (!digitalRead(_echoPin)) // Wait for the ping echo.
#endif
{
if (micros() > _max_time) return NO_ECHO; // Stop the loop and return NO_ECHO (false) if we're beyond the set maximum distance.
if ((_max_cm_distance > 0) && (micros() > _max_time)) {
_errorState = STATUS_MAX_DISTANCE_EXCEEDED;
return NO_ECHO; // Stop the loop and return NO_ECHO (false) if we're beyond the set maximum distance.
}
}
#else
#if DO_BITWISE == true
@@ -67,10 +71,14 @@ unsigned int NewPingESP8266::ping(unsigned int max_cm_distance) {
while (digitalRead(_echoPin)) // Wait for the ping echo.
#endif
{
if (micros() > _max_time) return NO_ECHO; // Stop the loop and return NO_ECHO (false) if we're beyond the set maximum distance.
if ((_max_cm_distance > 0) && (micros() > _max_time)) {
_errorState = STATUS_MAX_DISTANCE_EXCEEDED;
return NO_ECHO; // Stop the loop and return NO_ECHO (false) if we're beyond the set maximum distance.
}
}
#endif
_errorState = STATUS_MEASUREMENT_VALID;
return (micros() - (_max_time - _maxEchoTime) - PING_OVERHEAD); // Calculate ping time, include overhead.
}
@@ -144,15 +152,39 @@ boolean NewPingESP8266::ping_trigger() {
#endif
#if URM37_ENABLED == true
if (!(*_echoInput & _echoBit)) return false; // Previous ping hasn't finished, abort.
if (!(*_echoInput & _echoBit)) { // Previous ping hasn't finished, abort.{
_errorState = STATUS_ECHO_STATE_ERROR;
return false;
}
_max_time = micros() + _maxEchoTime + MAX_SENSOR_DELAY; // Maximum time we'll wait for ping to start (most sensors are <450uS, the SRF06 can take up to 34,300uS!)
while (*_echoInput & _echoBit) // Wait for ping to start.
if (micros() > _max_time) return false; // Took too long to start, abort.
{
if (millis() > (start + 50)) {
_errorState = STATUS_ECHO_START_TIMEOUT_50ms;
return false;
}
if ((_max_cm_distance > 0) && (micros() > _max_time)) { // check max. distance if != 0 cm
_errorState = STATUS_ECHO_START_TIMEOUT_DISTANCE;
return false; // echo too late, max distance exceeded
}
}
#else
if (*_echoInput & _echoBit) return false; // Previous ping hasn't finished, abort.
if (*_echoInput & _echoBit) { // Previous ping hasn't finished, abort.
_errorState = STATUS_ECHO_STATE_ERROR;
return false;
}
_max_time = micros() + _maxEchoTime + MAX_SENSOR_DELAY; // Maximum time we'll wait for ping to start (most sensors are <450uS, the SRF06 can take up to 34,300uS!)
while (!(*_echoInput & _echoBit)) // Wait for ping to start.
if (micros() > _max_time) return false; // Took too long to start, abort.
{
if (millis() > (start + 50)) {
_errorState = STATUS_ECHO_START_TIMEOUT_50ms;
return false;
}
if ((_max_cm_distance > 0) && (micros() > _max_time)) { // check max. distance if != 0 cm
_errorState = STATUS_ECHO_START_TIMEOUT_DISTANCE;
return false; // echo too late, max distance exceeded
}
}
#endif
#else
#if ONE_PIN_ENABLED == true
@@ -170,30 +202,51 @@ boolean NewPingESP8266::ping_trigger() {
#endif
#if URM37_ENABLED == true
if (!digitalRead(_echoPin)) return false; // Previous ping hasn't finished, abort.
if (!digitalRead(_echoPin)) {
_errorState = STATUS_ECHO_STATE_ERROR;
return false; // Previous ping hasn't finished, abort.
}
_max_time = micros() + _maxEchoTime + MAX_SENSOR_DELAY; // Maximum time we'll wait for ping to start (most sensors are <450uS, the SRF06 can take up to 34,300uS!)
while (digitalRead(_echoPin)) // Wait for ping to start.
{
if (millis() > (start + 50)) return false;
if (micros() > _max_time) return false; // Took too long to start, abort.
if (millis() > (start + 50)) {
_errorState = STATUS_ECHO_START_TIMEOUT_50ms;
return false;
}
if ((_max_cm_distance > 0) && (micros() > _max_time)) { // check max. distance if != 0 cm
_errorState = STATUS_ECHO_START_TIMEOUT_DISTANCE;
return false; // echo too late, max distance exceeded
}
}
#else
if (digitalRead(_echoPin)) return false; // Previous ping hasn't finished, abort.
if (digitalRead(_echoPin)) {
_errorState = STATUS_ECHO_STATE_ERROR;
return false; // Previous ping hasn't finished, abort.
}
_max_time = micros() + _maxEchoTime + MAX_SENSOR_DELAY; // Maximum time we'll wait for ping to start (most sensors are <450uS, the SRF06 can take up to 34,300uS!)
while (!digitalRead(_echoPin)) // Wait for ping to start.
{
if (millis() > (start + 50)) return false;
if (micros() > _max_time) return false; // Took too long to start, abort.
if (millis() > (start + 50)) {
_errorState = STATUS_ECHO_START_TIMEOUT_50ms;
return false;
}
if ((_max_cm_distance > 0) && (micros() > _max_time)) { // check max. distance if != 0 cm
_errorState = STATUS_ECHO_START_TIMEOUT_DISTANCE;
return false; // echo too late, max distance exceeded
}
}
#endif
#endif
_max_time = micros() + _maxEchoTime; // Ping started, set the time-out.
_errorState = STATUS_ECHO_TRIGGERED;
return true; // Ping started successfully.
}
void NewPingESP8266::set_max_distance(unsigned int max_cm_distance) {
_max_cm_distance = max_cm_distance;
#if ROUNDING_ENABLED == false
_maxEchoTime = min(max_cm_distance + 1, (unsigned int) MAX_SENSOR_DISTANCE + 1) * US_ROUNDTRIP_CM; // Calculate the maximum distance in uS (no rounding).
#else
@@ -222,3 +275,12 @@ unsigned int NewPingESP8266::convert_in(unsigned int echoTime) {
return NewPingESP8266Convert(echoTime, US_ROUNDTRIP_IN); // Convert uS to inches.
#endif
}
float NewPingESP8266::convert_cm_F(unsigned int echoTime) {
return ((float)echoTime / US_ROUNDTRIP_CM); // Convert uS to centimeters (no rounding).
}
float NewPingESP8266::convert_in_F(unsigned int echoTime) {
return ((float)echoTime / US_ROUNDTRIP_IN); // Convert uS to inches (no rounding).
}
+17 -1
View File
@@ -194,15 +194,29 @@
class NewPingESP8266 {
public:
enum errorState {
STATUS_SENSOR_READY, // no error, no measruement started
STATUS_MEASUREMENT_VALID, // no errors
STATUS_ECHO_TRIGGERED, // echo triggered, intermediate state
STATUS_MAX_DISTANCE_EXCEEDED, // echo too late, maximum distance exceeded
STATUS_ECHO_START_TIMEOUT_50ms, // no echo start signal after 50 ms
STATUS_ECHO_START_TIMEOUT_DISTANCE, // no echo start signal after max. distance
STATUS_ECHO_STATE_ERROR // echopin level not low after triggered
};
NewPingESP8266(uint32_t trigger_pin, uint32_t echo_pin, unsigned int max_cm_distance = MAX_SENSOR_DISTANCE);
~NewPingESP8266() { };
unsigned int ping(unsigned int max_cm_distance = 0);
unsigned long ping_cm(unsigned int max_cm_distance = 0);
unsigned long ping_in(unsigned int max_cm_distance = 0);
unsigned long ping_median(uint32_t it = 5, unsigned int max_cm_distance = 0);
static unsigned int convert_cm(unsigned int echoTime);
static unsigned int convert_in(unsigned int echoTime);
static float convert_cm_F(unsigned int echoTime);
static float convert_in_F(unsigned int echoTime);
unsigned int getMaxEchoTime() { return _maxEchoTime; }
unsigned int getMaxEchoTime() { return _maxEchoTime; };
errorState getErrorState() { return _errorState; };
private:
boolean ping_trigger();
void set_max_distance(unsigned int max_cm_distance);
@@ -218,6 +232,8 @@ class NewPingESP8266 {
#endif
unsigned int _maxEchoTime;
unsigned long _max_time;
errorState _errorState;
unsigned int _max_cm_distance;
};
+72 -27
View File
@@ -65,6 +65,7 @@ platform = https://github.com/platformio/platform-espressif8266
[core_esp32_0_12_0]
platform = espressif32@0.12.0
lib_deps = "ESP32WebServer"
[core_esp32_1_2_0]
platform = espressif32@1.2.0
@@ -72,20 +73,23 @@ platform = espressif32@1.2.0
[core_esp32_1_3_0]
platform = espressif32@1.3.0
[core_esp32_1_4_0]
platform = espressif32@1.4.0
[core_esp32_stage]
platform = https://github.com/platformio/platform-espressif32.git#feature/stage
[core_esp32]
platform = ${core_esp32_0_12_0.platform}
platform = ${core_esp32_1_4_0.platform}
build_unflags = -Wall
build_flags = -D BUILD_GIT='"${sysenv.TRAVIS_TAG}"'
-lstdc++ -lsupc++
lib_ignore = AS_BH1750, ESP8266WiFi, ESP8266Ping, ESP8266WebServer, ESP8266HTTPUpdateServer, ESP8266mDNS, IRremoteESP8266, ESPEasy_ESP8266Ping, SerialSensors, SDM
lib_deps = ESP32WebServer
lib_deps = ""
monitor_speed = 115200
; Build Flags:
; -DUSE_CONFIG_OVERRIDE
; lwIP 1.4 (Default)
@@ -100,11 +104,16 @@ monitor_speed = 115200
; -DVTABLES_IN_DRAM
; VTABLES in IRAM
; -DVTABLES_IN_IRAM
; NO_EXTRA_4K_HEAP - this forces the default NONOS-SDK user's heap location
; Default currently overlaps cont stack (Arduino) with sys stack (System)
; to save up-to 4 kB of heap. (starting core_2.4.2)
; ESP8266_DISABLE_EXTRA4K - Calls disable_extra4k_at_link_time() from setup
; to force the linker keep user's stack in user ram.
; CONT_STACKSIZE to set the 'cont' (Arduino) stack size. Default = 4096
[common]
board_build.f_cpu = 80000000L
build_unflags = ""
build_unflags =
build_flags = -D BUILD_GIT='"${sysenv.TRAVIS_TAG}"'
-D NDEBUG
-lstdc++ -lsupc++
@@ -119,18 +128,20 @@ lib_archive = false
upload_speed = 460800
framework = arduino
board = esp12e
platform = ${core_2_4_2.platform}
platform = ${core_2_4_1.platform}
monitor_speed = 115200
[normal]
platform = ${common.platform}
build_flags = -DCONT_STACKSIZE=5120
[testing]
platform = ${core_2_4_2.platform}
platform = ${core_2_4_1.platform}
build_flags = -DCONT_STACKSIZE=5120 -DPLUGIN_BUILD_TESTING
[dev]
platform = ${core_2_4_2.platform}
platform = ${core_2_4_1.platform}
build_flags = -DCONT_STACKSIZE=5120 -DPLUGIN_BUILD_DEV
[ir]
lib_ignore = ESP32_ping, ESP32WebServer
@@ -158,7 +169,7 @@ board_build.flash_mode = ${esp8266_1M.board_build.flash_mode}
board_build.f_cpu = ${esp8266_1M.board_build.f_cpu}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld
platform = ${core_2_4_2.platform}
platform = ${core_2_4_1.platform}
[Sonoff_8285]
board_upload.maximum_size = ${esp8285_1M.board_upload.maximum_size}
@@ -167,7 +178,7 @@ board_build.f_cpu = ${esp8285_1M.board_build.f_cpu}
board = ${esp8285_1M.board}
build_unflags = ${esp8285_1M.build_unflags}
build_flags = ${esp8285_1M.build_flags}
platform = ${core_2_4_2.platform}
platform = ${core_2_4_1.platform}
[espWroom2M]
board_build.flash_mode = dout
@@ -193,6 +204,25 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld
; Will probably not work, not tested and guaranteed to take a few hours time of some ;
; still trying to build the version without reading this warning. ;
; *********************************************************************
[env:esp-wrover-kit_test_1M8_partition]
platform = ${core_esp32.platform}
board = esp-wrover-kit
build_unflags = ${core_esp32.build_unflags}
build_flags = ${core_esp32.build_flags} -DPLUGIN_SET_TEST_ESP32
lib_deps = ${core_esp32.lib_deps}
lib_ignore = ${core_esp32.lib_ignore}
lib_ldf_mode = ${common.lib_ldf_mode}
lib_archive = ${common.lib_archive}
framework = ${common.framework}
upload_speed = ${common.upload_speed}
upload_protocol = ftdi
debug_tool = ftdi
monitor_speed = ${common.monitor_speed}
board_build.partitions = esp32_partition_app1810k_spiffs316k.csv
board_upload.maximum_size = 1900544
debug_extra_cmds = break Misc.ino:3011
[env:esp32dev]
platform = ${core_esp32.platform}
board = esp32dev
@@ -206,6 +236,21 @@ framework = ${common.framework}
upload_speed = ${common.upload_speed}
monitor_speed = ${common.monitor_speed}
[env:esp32test_1M8_partition]
platform = ${core_esp32.platform}
board = esp32dev
build_unflags = ${core_esp32.build_unflags}
build_flags = ${core_esp32.build_flags} -DPLUGIN_SET_TEST_ESP32
lib_deps = ${core_esp32.lib_deps}
lib_ignore = ${core_esp32.lib_ignore}
lib_ldf_mode = ${common.lib_ldf_mode}
lib_archive = ${common.lib_archive}
framework = ${common.framework}
upload_speed = ${common.upload_speed}
monitor_speed = ${common.monitor_speed}
board_build.partitions = esp32_partition_app1810k_spiffs316k.csv
board_upload.maximum_size = 1900544
;;; NORMAL (STABLE) ; ****; ****; ****; ****; ****; ****; ****; ****; ****; ****; ****;;;;
; normal version with stable plugins ;
@@ -226,7 +271,7 @@ board_upload.maximum_size = ${esp8266_1M.board_upload.maximum_size}
board_build.f_cpu = ${esp8266_1M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_1M.board_build.flash_mode}
build_unflags = ${esp8266_1M.build_unflags}
build_flags = ${esp8266_1M.build_flags}
build_flags = ${esp8266_1M.build_flags} ${normal.build_flags}
; NORMAL: 1024k for esp8285 ----------------------
[env:normal_ESP8285_1024]
@@ -243,7 +288,7 @@ board_upload.maximum_size = ${esp8285_1M.board_upload.maximum_size}
board_build.f_cpu = ${esp8285_1M.board_build.f_cpu}
board_build.flash_mode = ${esp8285_1M.board_build.flash_mode}
build_unflags = ${esp8285_1M.build_unflags}
build_flags = ${esp8285_1M.build_flags}
build_flags = ${esp8285_1M.build_flags} ${normal.build_flags}
; NORMAL: 2048k version --------------------------
[env:normal_WROOM02_2048]
@@ -259,7 +304,7 @@ board = ${espWroom2M.board}
board_build.f_cpu = ${espWroom2M.board_build.f_cpu}
board_build.flash_mode = ${espWroom2M.board_build.flash_mode}
build_unflags = ${espWroom2M.build_unflags}
build_flags = ${espWroom2M.build_flags}
build_flags = ${espWroom2M.build_flags} ${normal.build_flags}
; NORMAL: 4096k version --------------------------
[env:normal_ESP8266_4096]
@@ -275,7 +320,7 @@ board = ${common.board}
board_build.f_cpu = ${esp8266_4M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_4M.board_build.flash_mode}
build_unflags = ${esp8266_4M.build_unflags}
build_flags = ${esp8266_4M.build_flags}
build_flags = ${esp8266_4M.build_flags} ${normal.build_flags}
; NORMAL IR: 4096k version --------------------------
@@ -293,7 +338,7 @@ board = ${common.board}
board_build.f_cpu = ${esp8266_4M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_4M.board_build.flash_mode}
build_unflags = ${esp8266_4M.build_unflags}
build_flags = ${esp8266_4M.build_flags} -DPLUGIN_BUILD_NORMAL_IR
build_flags = ${esp8266_4M.build_flags} ${normal.build_flags} -DPLUGIN_BUILD_NORMAL_IR
;;; TESTING ; ****; ****; ****; ****; ****; ****; ****; ****; ****; ****; ****; ****; ****
@@ -315,7 +360,7 @@ board_upload.maximum_size = ${esp8266_1M.board_upload.maximum_size}
board_build.flash_mode = ${esp8266_1M.board_build.flash_mode}
board_build.f_cpu = ${esp8266_1M.board_build.f_cpu}
build_unflags = ${esp8266_1M.build_unflags}
build_flags = ${esp8266_1M.build_flags} -D PLUGIN_BUILD_TESTING
build_flags = ${esp8266_1M.build_flags} ${testing.build_flags}
; TEST: 1024k for esp8285 ------------------------
[env:test_ESP8285_1024]
@@ -332,7 +377,7 @@ board_build.f_cpu = ${esp8285_1M.board_build.f_cpu}
board_build.flash_mode = ${esp8285_1M.board_build.flash_mode}
board = ${esp8285_1M.board}
build_unflags = ${esp8285_1M.build_unflags}
build_flags = ${esp8285_1M.build_flags} -D PLUGIN_BUILD_TESTING
build_flags = ${esp8285_1M.build_flags} ${testing.build_flags}
; TEST: 2048k version ----------------------------
[env:test_WROOM02_2048]
@@ -348,7 +393,7 @@ board_build.f_cpu = ${espWroom2M.board_build.f_cpu}
board_build.flash_mode = ${espWroom2M.board_build.flash_mode}
board = ${espWroom2M.board}
build_unflags = ${espWroom2M.build_unflags}
build_flags = ${espWroom2M.build_flags} -D PLUGIN_BUILD_TESTING
build_flags = ${espWroom2M.build_flags} ${testing.build_flags}
; TEST: 4096k version ----------------------------
[env:test_ESP8266_4096]
@@ -364,7 +409,7 @@ monitor_speed = ${common.monitor_speed}
board_build.f_cpu = ${esp8266_4M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_4M.board_build.flash_mode}
build_unflags = ${esp8266_4M.build_unflags}
build_flags = ${esp8266_4M.build_flags} -D PLUGIN_BUILD_TESTING
build_flags = ${esp8266_4M.build_flags} ${testing.build_flags}
; TEST: 4096k version + FEATURE_ADC_VCC ----------
[env:test_ESP8266_4096_VCC]
@@ -380,7 +425,7 @@ monitor_speed = ${common.monitor_speed}
board_build.f_cpu = ${esp8266_4M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_4M.board_build.flash_mode}
build_unflags = ${esp8266_4M.build_unflags}
build_flags = ${esp8266_4M.build_flags} -D PLUGIN_BUILD_TESTING -D FEATURE_ADC_VCC=true
build_flags = ${esp8266_4M.build_flags} ${testing.build_flags} -D FEATURE_ADC_VCC=true
@@ -403,7 +448,7 @@ board_build.f_cpu = ${esp8266_1M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_1M.board_build.flash_mode}
board = ${common.board}
build_unflags = ${esp8266_1M.build_unflags}
build_flags = ${esp8266_1M.build_flags} -D PLUGIN_BUILD_DEV
build_flags = ${esp8266_1M.build_flags} ${dev.build_flags}
; DEV: 1024k for esp8285 -------------------------
[env:dev_ESP8285_1024]
@@ -420,7 +465,7 @@ board_build.f_cpu = ${esp8285_1M.board_build.f_cpu}
board_build.flash_mode = ${esp8285_1M.board_build.flash_mode}
board = ${esp8285_1M.board}
build_unflags = ${esp8285_1M.build_unflags}
build_flags = ${esp8285_1M.build_flags} -D PLUGIN_BUILD_DEV
build_flags = ${esp8285_1M.build_flags} ${dev.build_flags}
; DEV: 2048k version -----------------------------
[env:dev_WROOM02_2048]
@@ -436,7 +481,7 @@ board_build.f_cpu = ${espWroom2M.board_build.f_cpu}
board_build.flash_mode = ${espWroom2M.board_build.flash_mode}
board = ${espWroom2M.board}
build_unflags = ${espWroom2M.build_unflags}
build_flags = ${espWroom2M.build_flags} -D PLUGIN_BUILD_DEV
build_flags = ${espWroom2M.build_flags} ${dev.build_flags}
; DEV : 4096k version ----------------------------
[env:dev_ESP8266_4096]
@@ -452,7 +497,7 @@ monitor_speed = ${common.monitor_speed}
board_build.f_cpu = ${esp8266_4M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_4M.board_build.flash_mode}
build_unflags = ${esp8266_4M.build_unflags}
build_flags = ${esp8266_4M.build_flags} -D PLUGIN_BUILD_DEV
build_flags = ${esp8266_4M.build_flags} ${dev.build_flags}
@@ -475,7 +520,7 @@ board_upload.maximum_size = ${esp8266_1M.board_upload.maximum_size}
board_build.f_cpu = ${esp8266_1M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_1M.board_build.flash_mode}
build_unflags = ${esp8266_1M.build_unflags}
build_flags = ${esp8266_1M.build_flags} -D PLUGIN_BUILD_DEV -D FLASH_QUIRK_WRITE_0_TO_1
build_flags = ${esp8266_1M.build_flags} ${dev.build_flags} -D FLASH_QUIRK_WRITE_0_TO_1
; DEV+PUYA : 1024k version + FEATURE_ADC_VCC -----
[env:dev_ESP8266PUYA_1024_VCC]
@@ -492,7 +537,7 @@ board_upload.maximum_size = ${esp8266_1M.board_upload.maximum_size}
board_build.f_cpu = ${esp8266_1M.board_build.f_cpu}
board_build.flash_mode = ${esp8266_1M.board_build.flash_mode}
build_unflags = ${esp8266_1M.build_unflags}
build_flags = ${esp8266_1M.build_flags} -D PLUGIN_BUILD_DEV -D FLASH_QUIRK_WRITE_0_TO_1 -D FEATURE_ADC_VCC=true
build_flags = ${esp8266_1M.build_flags} ${dev.build_flags} -D FLASH_QUIRK_WRITE_0_TO_1 -D FEATURE_ADC_VCC=true
+7 -6
View File
@@ -131,7 +131,8 @@ String doExecuteCommand(const char * cmd, struct EventStruct *event, const char*
COMMAND_CASE("taskclear" , Command_Task_Clear); // Tasks.h
COMMAND_CASE("taskclearall" , Command_Task_ClearAll); // Tasks.h
COMMAND_CASE("taskrun" , Command_Task_Run); // Tasks.h
COMMAND_CASE("taskvalueset" , Command_Task_ValueSet); // Tasks.h
COMMAND_CASE("taskvalueset" , Command_Task_ValueSet); // Tasks.h
COMMAND_CASE("taskvaluetoggle" , Command_Task_ValueToggle); // Tasks.h
COMMAND_CASE("taskvaluesetandrun" , Command_Task_ValueSetAndRun); // Tasks.h
COMMAND_CASE("timerpause" , Command_Timer_Pause); // Timers.h
COMMAND_CASE("timerresume" , Command_Timer_Resume); // Timers.h
@@ -216,11 +217,11 @@ void ExecuteCommand(byte source, const char *Line)
// since commands can originate from anywhere.
TempEvent.Source = source;
GetArgv(Line, cmd, 1);
if (GetArgv(Line, TmpStr1, 2)) TempEvent.Par1 = str2int(TmpStr1);
if (GetArgv(Line, TmpStr1, 3)) TempEvent.Par2 = str2int(TmpStr1);
if (GetArgv(Line, TmpStr1, 4)) TempEvent.Par3 = str2int(TmpStr1);
if (GetArgv(Line, TmpStr1, 5)) TempEvent.Par4 = str2int(TmpStr1);
if (GetArgv(Line, TmpStr1, 6)) TempEvent.Par5 = str2int(TmpStr1);
if (GetArgv(Line, TmpStr1, 2)) TempEvent.Par1 = CalculateParam(TmpStr1);
if (GetArgv(Line, TmpStr1, 3)) TempEvent.Par2 = CalculateParam(TmpStr1);
if (GetArgv(Line, TmpStr1, 4)) TempEvent.Par3 = CalculateParam(TmpStr1);
if (GetArgv(Line, TmpStr1, 5)) TempEvent.Par4 = CalculateParam(TmpStr1);
if (GetArgv(Line, TmpStr1, 6)) TempEvent.Par5 = CalculateParam(TmpStr1);
if (source == VALUE_SOURCE_WEB_FRONTEND) {
// Must run immediately, to see result in web frontend
+2 -1
View File
@@ -24,7 +24,8 @@ String Command_HTTP_SendToHTTP(struct EventStruct *event, const char* Line)
}
WiFiClient client;
const int port_int = port.toInt();
if (client.connect(host.c_str(), port_int) != 1) {
const bool connected = client.connect(host.c_str(), port_int) == 1;
if (connected) {
String hostportString = host;
if (port_int != 0 && port_int != 80) {
hostportString += ':';
+9
View File
@@ -30,6 +30,15 @@ String Command_Task_ValueSet(struct EventStruct *event, const char* Line)
return return_command_success();
}
String Command_Task_ValueToggle(struct EventStruct *event, const char* Line)
{
const int result = round(UserVar[(VARS_PER_TASK * (event->Par1 - 1)) + event->Par2 - 1]);
if (result == 0 || result == 1) {
UserVar[(VARS_PER_TASK * (event->Par1 - 1)) + event->Par2 - 1] = !result;
}
return return_command_success();
}
String Command_Task_ValueSetAndRun(struct EventStruct *event, const char* Line)
{
char TmpStr1[INPUT_COMMAND_SIZE];
+12 -2
View File
@@ -133,7 +133,7 @@ bool MQTTConnect(int controller_idx)
{
++mqtt_reconnect_count;
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(controller_idx, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(controller_idx, ControllerSettings);
if (!ControllerSettings.checkHostReachable(true))
return false;
if (MQTTclient.connected()) {
@@ -141,6 +141,7 @@ bool MQTTConnect(int controller_idx)
updateMQTTclient_connected();
}
mqtt = WiFiClient(); // workaround see: https://github.com/esp8266/Arduino/issues/4497#issuecomment-373023864
mqtt.setTimeout(ControllerSettings.ClientTimeout);
if (ControllerSettings.UseDNS) {
MQTTclient.setServer(ControllerSettings.getHost().c_str(), ControllerSettings.Port);
} else {
@@ -161,6 +162,15 @@ bool MQTTConnect(int controller_idx)
clientid = F("ESPClient_");
clientid += WiFi.macAddress();
}
// Work-around for 'lost connections' to the MQTT broker.
// If the broker thinks the connection is still alive, a reconnect from the
// client will be refused.
// To overcome this issue, append the number of reconnects to the client ID to
// make it different from the previous one.
if (wifi_reconnects >= 1) {
clientid += F("_");
clientid += wifi_reconnects;
}
String LWTTopic = ControllerSettings.MQTTLwtTopic;
if(LWTTopic.length() == 0)
@@ -309,7 +319,7 @@ void MQTTStatus(String& status)
ControllerSettingsStruct ControllerSettings;
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
LoadControllerSettings(enabledMqttController, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(enabledMqttController, ControllerSettings);
String pubname = ControllerSettings.Subscribe;
pubname.replace(F("/#"), F("/status"));
parseSystemVariables(pubname, false);
+99 -15
View File
@@ -68,6 +68,9 @@
#if defined(ESP32)
#define USE_RTOS_MULTITASKING
#endif
#ifdef M5STACK_ESP
// #include <M5Stack.h>
#endif
#define DEFAULT_USE_RULES false // (true|false) Enable Rules?
@@ -188,6 +191,8 @@
#define MAX_FLASHWRITES_PER_DAY 100 // per 24 hour window
#define INPUT_COMMAND_SIZE 240 // Affects maximum command length in rules and other commands
// FIXME TD-er: INPUT_COMMAND_SIZE is also used in commands where simply a check for valid parameter is needed
// and some may need less memory. (which is stack allocated)
#define NODE_TYPE_ID_ESP_EASY_STD 1
#define NODE_TYPE_ID_ESP_EASYM_STD 17
@@ -223,6 +228,9 @@
// N.B. Retries without a connection to wifi do not count as retry.
#define CONTROLLER_DELAY_QUEUE_RETRY_MAX 10
#define CONTROLLER_DELAY_QUEUE_RETRY_DFLT 10
// Timeout of the client in msec.
#define CONTROLLER_CLIENTTIMEOUT_MAX 1000
#define CONTROLLER_CLIENTTIMEOUT_DFLT 100
#define PLUGIN_INIT_ALL 1
@@ -297,7 +305,11 @@
#if defined(PLUGIN_BUILD_TESTING) || defined(PLUGIN_BUILD_DEV)
#define DEVICES_MAX 75
#else
#define DEVICES_MAX 50
#ifdef ESP32
#define DEVICES_MAX 75
#else
#define DEVICES_MAX 50
#endif
#endif
#if defined(ESP8266)
@@ -325,6 +337,8 @@
#define RULESETS_MAX 4
#define RULES_BUFFER_SIZE 64
#define NAME_FORMULA_LENGTH_MAX 40
#define RULES_IF_MAX_NESTING_LEVEL 4
#define UDP_PACKETSIZE_MAX 2048
#define PIN_MODE_UNDEFINED 0
@@ -357,6 +371,9 @@
#define SENSOR_TYPE_LONG 20
#define SENSOR_TYPE_WIND 21
#define UNIT_NUMBER_MAX 9999 // Stored in Settings.Unit
#define DOMOTICZ_MAX_IDX 999999999 // Looks like it is an unsigned int, so could be up to 4 bln.
#define VALUE_SOURCE_SYSTEM 1
#define VALUE_SOURCE_SERIAL 2
#define VALUE_SOURCE_HTTP 3
@@ -393,13 +410,21 @@
#endif
// Forward declaration
struct ControllerSettingsStruct;
void scheduleNextDelayQueue(unsigned long id, unsigned long nextTime);
String LoadControllerSettings(int ControllerIndex, byte* memAddress, int datasize);
String LoadControllerSettings(int ControllerIndex, ControllerSettingsStruct& controller_settings);
String get_formatted_Controller_number(int controller_index);
bool loglevelActiveFor(byte logLevel);
void addToLog(byte loglevel, const String& string);
void addToLog(byte logLevel, const __FlashStringHelper* flashString);
void statusLED(boolean traffic);
void backgroundtasks();
uint32_t getCurrentFreeStack();
uint32_t getFreeStackWatermark();
bool canYield();
bool getBitFromUL(uint32_t number, byte bitnr);
void setBitToUL(uint32_t& number, byte bitnr, bool value);
enum SettingsType {
BasicSettings_Type = 0,
@@ -443,6 +468,7 @@ bool showSettingsFileLayout = false;
#include "I2CTypes.h"
#include <I2Cdev.h>
#include <map>
#include <deque>
#define FS_NO_GLOBALS
#if defined(ESP8266)
@@ -510,10 +536,10 @@ bool showSettingsFileLayout = false;
#define FILE_RULES "/rules1.txt"
#include <WiFi.h>
#include "esp32_ping.h"
#include <ESP32WebServer.h>
#include <WebServer.h>
#include "SPIFFS.h"
#include <rom/rtc.h>
ESP32WebServer WebServer(80);
WebServer WebServer(80);
#ifdef FEATURE_MDNS
#include <ESPmDNS.h>
#endif
@@ -657,17 +683,42 @@ struct SettingsStruct
clearAll();
}
// VariousBits1 defaults to 0, keep in mind when adding bit lookups.
bool appendUnitToHostname() { return !getBitFromUL(VariousBits1, 1); }
void appendUnitToHostname(bool value) { setBitToUL(VariousBits1, 1, !value); }
void validate() {
if (UDPPort > 65535) UDPPort = 0;
if (Latitude < -90.0 || Latitude > 90.0) Latitude = 0.0;
if (Longitude < -180.0 || Longitude > 180.0) Longitude = 0.0;
if (VariousBits1 > (1 << 30)) VariousBits1 = 0;
}
void clearNetworkSettings() {
for (byte i = 0; i < 4; ++i) {
IP[i] = 0;
Gateway[i] = 0;
Subnet[i] = 0;
DNS[i] = 0;
}
}
void clearAll() {
PID = 0;
Version = 0;
Build = 0;
IP_Octet = 0;
Unit = 0;
Name[0] = 0;
NTPHost[0] = 0;
Delay = 0;
Pin_i2c_sda = -1;
Pin_i2c_scl = -1;
Pin_status_led = -1;
Pin_sd_cs = -1;
for (byte i = 0; i < 17; ++i) { PinBootStates[i] = 0; }
for (byte i = 0; i < 4; ++i) { Syslog_IP[i] = 0; }
UDPPort = 0;
SyslogLevel = 0;
SerialLogLevel = 0;
@@ -692,13 +743,17 @@ struct SettingsStruct
Pin_status_led_Inversed = false;
deepSleepOnFail = false;
UseValueLogger = false;
ArduinoOTAEnable = false;
DST_Start = 0;
DST_End = 0;
UseRTOSMultitasking = false;
Pin_Reset = -1;
SyslogFacility = DEFAULT_SYSLOG_FACILITY;
StructSize = 0;
StructSize = sizeof(SettingsStruct);
MQTTUseUnitNameAsClientId = 0;
Latitude = 0.0;
Longitude = 0.0;
VariousBits1 = 0;
for (byte i = 0; i < CONTROLLER_MAX; ++i) {
Protocol[i] = 0;
@@ -711,6 +766,7 @@ struct SettingsStruct
for (byte task = 0; task < TASKS_MAX; ++task) {
clearTask(task);
}
clearNetworkSettings();
}
void clearTask(byte task) {
@@ -825,6 +881,7 @@ struct SettingsStruct
//TODO: document config.dat somewhere here
float Latitude;
float Longitude;
uint32_t VariousBits1;
// FIXME @TD-er: As discussed in #1292, the CRC for the settings is now disabled.
// make sure crc is the last value in the struct
@@ -832,7 +889,10 @@ struct SettingsStruct
// uint8_t ProgmemMd5[16]; // crc of the binary that last saved the struct to file.
// uint8_t md5[16];
} Settings;
/*
SettingsStruct* SettingsStruct_ptr = new SettingsStruct;
SettingsStruct& Settings = *SettingsStruct_ptr;
*/
/*********************************************************************************************\
* ControllerSettingsStruct
@@ -840,7 +900,7 @@ struct SettingsStruct
struct ControllerSettingsStruct
{
ControllerSettingsStruct() : UseDNS(false), Port(0),
MinimalTimeBetweenMessages(100), MaxQueueDepth(10), MaxRetry(10), DeleteOldest(false) {
MinimalTimeBetweenMessages(100), MaxQueueDepth(10), MaxRetry(10), DeleteOldest(false), ClientTimeout(100) {
for (byte i = 0; i < 4; ++i) {
IP[i] = 0;
}
@@ -864,6 +924,17 @@ struct ControllerSettingsStruct
unsigned int MaxQueueDepth;
unsigned int MaxRetry;
boolean DeleteOldest; // Action to perform when buffer full, delete oldest, or ignore newest.
unsigned int ClientTimeout;
void validate() {
if (Port > 65535) Port = 0;
if (MinimalTimeBetweenMessages < 1 || MinimalTimeBetweenMessages > CONTROLLER_DELAY_QUEUE_DELAY_MAX)
MinimalTimeBetweenMessages = CONTROLLER_DELAY_QUEUE_DELAY_DFLT;
if (MaxQueueDepth > CONTROLLER_DELAY_QUEUE_DEPTH_MAX) MaxQueueDepth = CONTROLLER_DELAY_QUEUE_DEPTH_DFLT;
if (MaxRetry > CONTROLLER_DELAY_QUEUE_RETRY_MAX) MaxRetry = CONTROLLER_DELAY_QUEUE_RETRY_MAX;
if (ClientTimeout < 10 || ClientTimeout > CONTROLLER_CLIENTTIMEOUT_MAX)
ClientTimeout = CONTROLLER_CLIENTTIMEOUT_DFLT;
}
IPAddress getIP() const {
IPAddress host(IP[0], IP[1], IP[2], IP[3]);
@@ -886,6 +957,7 @@ struct ControllerSettingsStruct
if (!WiFiConnected(10)) {
return false; // Not connected, so no use in wasting time to connect to a host.
}
delay(1); // Make sure the Watchdog will not trigger a reset.
if (quick && ipSet()) return true;
if (UseDNS) {
if (!updateIPcache()) {
@@ -1240,6 +1312,9 @@ struct LogStruct {
} Logging;
std::deque<char> serialLogBuffer;
unsigned long last_serial_log_emptied = 0;
byte highest_active_log_level = 0;
bool log_to_serial_disabled = false;
// Do this in a template to prevent casting to String when not needed.
@@ -1357,6 +1432,7 @@ std::map<unsigned long, systemTimerStruct> systemTimers;
\*********************************************************************************************/
struct pinStatesStruct
{
pinStatesStruct() : plugin(0), index(0), mode(0), value(0) {}
byte plugin;
byte index;
byte mode;
@@ -1374,18 +1450,20 @@ struct pinStatesStruct
//max 40 bytes: ( 74 - 64 ) * 4
struct RTCStruct
{
RTCStruct() : ID1(0), ID2(0), unused1(false), factoryResetCounter(0),
deepSleepState(0), bootFailedCount(0), flashDayCounter(0),
flashCounter(0), bootCounter(0) {}
byte ID1;
byte ID2;
boolean unused1;
byte factoryResetCounter;
byte deepSleepState;
byte unused2;
byte bootFailedCount;
byte flashDayCounter;
unsigned long flashCounter;
unsigned long bootCounter;
} RTC;
int deviceCount = -1;
int protocolCount = -1;
int notificationCount = -1;
@@ -1401,6 +1479,8 @@ float UserVar[VARS_PER_TASK * TASKS_MAX];
\*********************************************************************************************/
struct rulesTimerStatus
{
rulesTimerStatus() : timestamp(0), interval(0), paused(false) {}
unsigned long timestamp;
unsigned int interval; //interval in milliseconds
boolean paused;
@@ -1408,14 +1488,15 @@ struct rulesTimerStatus
msecTimerHandlerStruct msecTimerHandler;
unsigned long timermqtt_interval;
unsigned long lastSend;
unsigned long lastWeb;
unsigned long timermqtt_interval = 250;
unsigned long lastSend = 0;
unsigned long lastWeb = 0;
byte cmd_within_mainloop = 0;
unsigned long connectionFailures;
unsigned long connectionFailures = 0;
unsigned long wdcounter = 0;
unsigned long timerAPoff = 0;
unsigned long timerAwakeFromDeepSleep = 0;
unsigned long last_system_event_run = 0;
#if FEATURE_ADC_VCC
float vcc = -1.0;
@@ -1562,15 +1643,18 @@ String eventBuffer = "";
uint32_t lowestRAM = 0;
String lowestRAMfunction = "";
uint32_t lowestFreeStack = 0;
String lowestFreeStackfunction = "";
bool shouldReboot=false;
bool firstLoop=true;
boolean activeRuleSets[RULESETS_MAX];
boolean UseRTOSMultitasking;
boolean UseRTOSMultitasking = false;
void (*MainLoopCall_ptr)(void);
// void (*MainLoopCall_ptr)(void); //FIXME TD-er: No idea what this does.
/*********************************************************************************************\
* TimingStats
+50 -6
View File
@@ -106,9 +106,14 @@ int firstEnabledBlynkController() {
\*********************************************************************************************/
void setup()
{
#ifdef ESP8266_DISABLE_EXTRA4K
disable_extra4k_at_link_time();
#endif
WiFi.persistent(false); // Do not use SDK storage of SSID/WPA parameters
WiFi.setAutoReconnect(false);
setWifiMode(WIFI_OFF);
lowestFreeStack = getFreeStackWatermark();
lowestRAM = FreeMem();
Plugin_id.resize(PLUGIN_MAX);
Task_id_to_Plugin_id.resize(TASKS_MAX);
@@ -119,8 +124,6 @@ void setup()
ledChannelPin[x] = -1;
#endif
lowestRAM = FreeMem();
Serial.begin(115200);
// Serial.print("\n\n\nBOOOTTT\n\n\n");
@@ -158,6 +161,7 @@ void setup()
//warm boot
if (readFromRTC())
{
RTC.bootFailedCount++;
RTC.bootCounter++;
readUserVarFromRTC();
@@ -193,6 +197,16 @@ void setup()
fileSystemCheck();
progMemMD5check();
LoadSettings();
if (RTC.bootFailedCount > 10 && RTC.bootCounter > 10) {
byte toDisable = RTC.bootFailedCount - 10;
toDisable = disablePlugin(toDisable);
if (toDisable != 0) {
toDisable = disableController(toDisable);
}
if (toDisable != 0) {
toDisable = disableNotification(toDisable);
}
}
// setWifiMode(WIFI_STA);
checkRuleSets();
@@ -304,9 +318,17 @@ void setup()
if(UseRTOSMultitasking){
log = F("RTOS : Launching tasks");
addLog(LOG_LEVEL_INFO, log);
xTaskCreatePinnedToCore(RTOS_TaskServers, "RTOS_TaskServers", 8192, NULL, 1, NULL, 1);
xTaskCreatePinnedToCore(RTOS_TaskServers, "RTOS_TaskServers", 16384, NULL, 1, NULL, 1);
xTaskCreatePinnedToCore(RTOS_TaskSerial, "RTOS_TaskSerial", 8192, NULL, 1, NULL, 1);
xTaskCreatePinnedToCore(RTOS_Task10ps, "RTOS_Task10ps", 8192, NULL, 1, NULL, 1);
xTaskCreatePinnedToCore(
RTOS_HandleSchedule, /* Function to implement the task */
"RTOS_HandleSchedule", /* Name of the task */
16384, /* Stack size in words */
NULL, /* Task input parameter */
1, /* Priority of the task */
NULL, /* Task handle. */
1); /* Core where the task should run */
}
#endif
@@ -353,6 +375,14 @@ void RTOS_Task10ps( void * parameter )
run10TimesPerSecond();
}
}
void RTOS_HandleSchedule( void * parameter )
{
while (true){
handle_schedule();
}
}
#endif
int firstEnabledMQTTController() {
@@ -435,8 +465,11 @@ int getLoopCountPerSec() {
\*********************************************************************************************/
void loop()
{
/*
//FIXME TD-er: No idea what this does.
if(MainLoopCall_ptr)
MainLoopCall_ptr();
*/
updateLoopStats();
@@ -465,7 +498,10 @@ void loop()
firstLoop = false;
timerAwakeFromDeepSleep = millis(); // Allow to run for "awake" number of seconds, now we have wifi.
// schedule_all_task_device_timers(); Disabled for now, since we are now using queues for controllers.
}
RTC.bootFailedCount = 0;
saveToRTC();
}
// Deep sleep mode, just run all tasks one (more) time and go back to sleep as fast as possible
if ((firstLoopConnectionsEstablished || readyForSleep()) && isDeepSleepEnabled())
@@ -480,7 +516,10 @@ void loop()
//normal mode, run each task when its time
else
{
handle_schedule();
if (!UseRTOSMultitasking) {
// On ESP32 the schedule is executed on the 2nd core.
handle_schedule();
}
}
backgroundtasks();
@@ -828,11 +867,16 @@ void backgroundtasks()
//checkRAM(F("backgroundtasks"));
//always start with a yield
yield();
/*
// Remove this watchdog feed for now.
// See https://github.com/letscontrolit/ESPEasy/issues/1722#issuecomment-419659193
#ifdef ESP32
// Have to find a similar function to call ESP32's esp_task_wdt_feed();
#else
ESP.wdtFeed();
#endif
*/
//prevent recursion!
if (runningBackgroundTasks)
@@ -844,7 +888,7 @@ void backgroundtasks()
#if defined(ESP8266)
tcpCleanup();
#endif
process_serialLogBuffer();
if(!UseRTOSMultitasking){
if (Settings.UseSerial)
if (Serial.available())
+107 -28
View File
@@ -113,7 +113,7 @@ void fileSystemCheck()
{
ResetFactory();
}
f.close();
if (f) f.close();
}
else
{
@@ -147,6 +147,7 @@ String SaveSettings(void)
// Settings have changed, save to file.
memcpy(Settings.md5, tmp_md5, 16);
*/
Settings.validate();
err=SaveToFile((char*)FILE_CONFIG, 0, (byte*)&Settings, sizeof(Settings));
if (err.length())
return(err);
@@ -182,6 +183,7 @@ String LoadSettings()
err=LoadFromFile((char*)FILE_CONFIG, 0, (byte*)&Settings, sizeof( SettingsStruct));
if (err.length())
return(err);
Settings.validate();
// FIXME @TD-er: As discussed in #1292, the CRC for the settings is now disabled.
/*
@@ -219,6 +221,51 @@ String LoadSettings()
return(err);
}
/********************************************************************************************\
Disable Plugin, based on bootFailedCount
\*********************************************************************************************/
byte disablePlugin(byte bootFailedCount) {
for (byte i = 0; i < TASKS_MAX && bootFailedCount > 0; ++i) {
if (Settings.TaskDeviceEnabled[i]) {
--bootFailedCount;
if (bootFailedCount == 0) {
Settings.TaskDeviceEnabled[i] = false;
}
}
}
return bootFailedCount;
}
/********************************************************************************************\
Disable Controller, based on bootFailedCount
\*********************************************************************************************/
byte disableController(byte bootFailedCount) {
for (byte i = 0; i < CONTROLLER_MAX && bootFailedCount > 0; ++i) {
if (Settings.ControllerEnabled[i]) {
--bootFailedCount;
if (bootFailedCount == 0) {
Settings.ControllerEnabled[i] = false;
}
}
}
return bootFailedCount;
}
/********************************************************************************************\
Disable Notification, based on bootFailedCount
\*********************************************************************************************/
byte disableNotification(byte bootFailedCount) {
for (byte i = 0; i < NOTIFICATION_MAX && bootFailedCount > 0; ++i) {
if (Settings.NotificationEnabled[i]) {
--bootFailedCount;
if (bootFailedCount == 0) {
Settings.NotificationEnabled[i] = false;
}
}
}
return bootFailedCount;
}
/********************************************************************************************\
Offsets in settings files
\*********************************************************************************************/
@@ -388,20 +435,25 @@ String LoadCustomTaskSettings(int TaskIndex, byte* memAddress, int datasize)
/********************************************************************************************\
Save Controller settings to SPIFFS
\*********************************************************************************************/
String SaveControllerSettings(int ControllerIndex, byte* memAddress, int datasize)
String SaveControllerSettings(int ControllerIndex, ControllerSettingsStruct& controller_settings)
{
checkRAM(F("SaveControllerSettings"));
return SaveToFile(ControllerSettings_Type, ControllerIndex, (char*)FILE_CONFIG, memAddress, datasize);
controller_settings.validate(); // Make sure the saved controller settings have proper values.
return SaveToFile(ControllerSettings_Type, ControllerIndex,
(char*)FILE_CONFIG, (byte*)&controller_settings, sizeof(controller_settings));
}
/********************************************************************************************\
Load Controller settings to SPIFFS
\*********************************************************************************************/
String LoadControllerSettings(int ControllerIndex, byte* memAddress, int datasize)
{
String LoadControllerSettings(int ControllerIndex, ControllerSettingsStruct& controller_settings) {
checkRAM(F("LoadControllerSettings"));
return(LoadFromFile(ControllerSettings_Type, ControllerIndex, (char*)FILE_CONFIG, memAddress, datasize));
String result =
LoadFromFile(ControllerSettings_Type, ControllerIndex,
(char*)FILE_CONFIG, (byte*)&controller_settings, sizeof(controller_settings));
controller_settings.validate(); // Make sure the loaded controller settings have proper values.
return result;
}
@@ -466,13 +518,15 @@ String InitFile(const char* fname, int datasize)
FLASH_GUARD();
fs::File f = SPIFFS.open(fname, "w");
SPIFFS_CHECK(f, fname);
if (f) {
SPIFFS_CHECK(f, fname);
for (int x = 0; x < datasize ; x++)
{
SPIFFS_CHECK(f.write(0), fname);
for (int x = 0; x < datasize ; x++)
{
SPIFFS_CHECK(f.write(0), fname);
}
f.close();
}
f.close();
//OK
return String();
@@ -483,6 +537,15 @@ String InitFile(const char* fname, int datasize)
\*********************************************************************************************/
String SaveToFile(char* fname, int index, byte* memAddress, int datasize)
{
#ifndef ESP32
if (allocatedOnStack(memAddress)) {
String log = F("SaveToFile: ");
log += fname;
log += F(" ERROR, Data allocated on stack");
addLog(LOG_LEVEL_ERROR, log);
// return log; // FIXME TD-er: Should this be considered a breaking error?
}
#endif
if (index < 0) {
String log = F("SaveToFile: ");
log += fname;
@@ -495,19 +558,27 @@ String SaveToFile(char* fname, int index, byte* memAddress, int datasize)
FLASH_GUARD();
fs::File f = SPIFFS.open(fname, "r+");
SPIFFS_CHECK(f, fname);
if (f) {
SPIFFS_CHECK(f, fname);
SPIFFS_CHECK(f.seek(index, fs::SeekSet), fname);
byte *pointerToByteToSave = memAddress;
for (int x = 0; x < datasize ; x++)
{
SPIFFS_CHECK(f.write(*pointerToByteToSave), fname);
pointerToByteToSave++;
SPIFFS_CHECK(f.seek(index, fs::SeekSet), fname);
byte *pointerToByteToSave = memAddress;
for (int x = 0; x < datasize ; x++)
{
SPIFFS_CHECK(f.write(*pointerToByteToSave), fname);
pointerToByteToSave++;
}
f.close();
String log = F("FILE : Saved ");
log=log+fname;
addLog(LOG_LEVEL_INFO, log);
} else {
String log = F("SaveToFile: ");
log += fname;
log += F(" ERROR, Cannot save to file");
addLog(LOG_LEVEL_ERROR, log);
return log;
}
f.close();
String log = F("FILE : Saved ");
log=log+fname;
addLog(LOG_LEVEL_INFO, log);
//OK
return String();
@@ -530,14 +601,22 @@ String ClearInFile(char* fname, int index, int datasize)
FLASH_GUARD();
fs::File f = SPIFFS.open(fname, "r+");
SPIFFS_CHECK(f, fname);
if (f) {
SPIFFS_CHECK(f, fname);
SPIFFS_CHECK(f.seek(index, fs::SeekSet), fname);
for (int x = 0; x < datasize ; x++)
{
SPIFFS_CHECK(f.write(0), fname);
SPIFFS_CHECK(f.seek(index, fs::SeekSet), fname);
for (int x = 0; x < datasize ; x++)
{
SPIFFS_CHECK(f.write(0), fname);
}
f.close();
} else {
String log = F("ClearInFile: ");
log += fname;
log += F(" ERROR, Cannot save to file");
addLog(LOG_LEVEL_ERROR, log);
return log;
}
f.close();
//OK
return String();
+5 -2
View File
@@ -418,8 +418,10 @@ void setWifiMode(WiFiMode_t wifimode) {
String WifiGetAPssid()
{
String ssid(Settings.Name);
ssid+=F("_");
ssid+=Settings.Unit;
if (Settings.appendUnitToHostname()) {
ssid+=F("_");
ssid+=Settings.Unit;
}
return (ssid);
}
@@ -676,6 +678,7 @@ void WifiScan()
String formatScanResult(int i, const String& separator) {
String result = WiFi.SSID(i);
htmlEscape(result);
#ifndef ESP32
if (WiFi.isHidden(i)) {
result += F("#Hidden#");
+12 -4
View File
@@ -11,6 +11,12 @@ bool I2C_read_words(uint8_t i2caddr, I2Cdata_words& data) {
return size == i2cdev.readWords(i2caddr, data.getRegister(), size, data.get());
}
// See https://github.com/platformio/platform-espressif32/issues/126
#ifdef ESP32
#define END_TRANSMISSION_FLAG true
#else
#define END_TRANSMISSION_FLAG false
#endif
//**************************************************************************/
// Wake up I2C device
@@ -66,7 +72,7 @@ uint8_t I2C_read8_reg(uint8_t i2caddr, byte reg, bool * is_ok) {
Wire.beginTransmission(i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission(false);
Wire.endTransmission(END_TRANSMISSION_FLAG);
byte count = Wire.requestFrom(i2caddr, (byte)1);
if (is_ok != NULL) {
*is_ok = (count == 1);
@@ -84,7 +90,7 @@ uint16_t I2C_read16_reg(uint8_t i2caddr, byte reg) {
Wire.beginTransmission(i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission(false);
Wire.endTransmission(END_TRANSMISSION_FLAG);
Wire.requestFrom(i2caddr, (byte)2);
value = (Wire.read() << 8) | Wire.read();
@@ -99,7 +105,7 @@ int32_t I2C_read24_reg(uint8_t i2caddr, byte reg) {
Wire.beginTransmission(i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission(false);
Wire.endTransmission(END_TRANSMISSION_FLAG);
Wire.requestFrom(i2caddr, (byte)3);
value = (((int32_t)Wire.read()) << 16) | (Wire.read() << 8) | Wire.read();
@@ -114,7 +120,7 @@ int32_t I2C_read32_reg(uint8_t i2caddr, byte reg) {
Wire.beginTransmission(i2caddr);
Wire.write((uint8_t)reg);
Wire.endTransmission(false);
Wire.endTransmission(END_TRANSMISSION_FLAG);
Wire.requestFrom(i2caddr, (byte)3);
value = (((int32_t)Wire.read()) <<24) | (((uint32_t)Wire.read()) << 16) | (Wire.read() << 8) | Wire.read();
@@ -139,3 +145,5 @@ int16_t I2C_readS16_reg(uint8_t i2caddr, byte reg) {
int16_t I2C_readS16_LE_reg(uint8_t i2caddr, byte reg) {
return (int16_t)I2C_read16_LE_reg(i2caddr, reg);
}
#undef END_TRANSMISSION_FLAG
+609 -312
View File
File diff suppressed because it is too large Load Diff
+8 -1
View File
@@ -41,19 +41,26 @@ unsigned long getMixedId(unsigned long timerType, unsigned long id) {
\*********************************************************************************************/
void handle_schedule() {
unsigned long timer;
const unsigned long mixed_id = msecTimerHandler.getNextId(timer);
unsigned long mixed_id = 0;
if (timePassedSince(last_system_event_run) < 500) {
// Make sure system event queue will be looked at every now and then.
mixed_id = msecTimerHandler.getNextId(timer);
}
if (mixed_id == 0) {
// No id ready to run right now.
// Events are not that important to run immediately.
// Make sure normal scheduled jobs run at higher priority.
backgroundtasks();
process_system_event_queue();
last_system_event_run = millis();
return;
}
const unsigned long timerType = (mixed_id >> TIMER_ID_SHIFT);
const unsigned long mask = (1 << TIMER_ID_SHIFT) -1;
const unsigned long id = mixed_id & mask;
yield(); // See: https://github.com/letscontrolit/ESPEasy/issues/1818#issuecomment-425351328
switch (timerType) {
case CONST_INTERVAL_TIMER:
process_interval_timer(id, timer);
+23
View File
@@ -373,8 +373,31 @@ void htmlEscape(String & html)
html.replace("'", F("&#039;"));
html.replace("<", F("&lt;"));
html.replace(">", F("&gt;"));
html.replace("/", F("&#047;"));
}
void htmlStrongEscape(String & html)
{
String escaped;
for (unsigned i = 0; i < html.length(); ++i)
{
if ((html[i] >= 'a' && html[i] <= 'z') || (html[i] >= 'A' && html[i] <= 'Z') || (html[i] >= '0' && html[i] <= '9'))
{
escaped += html[i];
}
else
{
char s [4];
sprintf(s, "%03d", static_cast<int>(html[i]));
escaped += "&#";
escaped += s;
escaped += ";";
}
}
html = escaped;
}
/********************************************************************************************\
replace other system variables like %sysname%, %systime%, %ip%
\*********************************************************************************************/
+6 -2
View File
@@ -61,8 +61,8 @@ void calcSunRiseAndSet() {
float eqt = equationOfTime(doy);
float dec = sunDeclination(doy);
float da = diurnalArc(dec, Settings.Latitude);
float rise = 12 - da - eqt - Settings.Longitude / 15.0;
float set = 12 + da - eqt - Settings.Longitude / 15.0;
float rise = 12 - da - eqt;
float set = 12 + da - eqt;
tsRise.Hour = (int)rise;
tsRise.Minute = (rise - (int)rise) * 60.0;
tsSet.Hour = (int)set;
@@ -70,6 +70,10 @@ void calcSunRiseAndSet() {
tsRise.Day = tsSet.Day = tm.Day;
tsRise.Month = tsSet.Month = tm.Month;
tsRise.Year = tsSet.Year = tm.Year;
// Now apply the longitude
int secOffset_longitude = -1.0 * (Settings.Longitude / 15.0) * 3600;
tsSet = addSeconds(tsSet, secOffset_longitude, false);
tsRise = addSeconds(tsRise, secOffset_longitude, false);
breakTime(toLocal(makeTime(tsRise)), sunRise);
breakTime(toLocal(makeTime(tsSet)), sunSet);
}
+136 -31
View File
@@ -875,6 +875,13 @@ void handle_root() {
TXBuffer += F(" - ");
TXBuffer += String(lowestRAMfunction);
TXBuffer += F(")");
html_TR_TD(); TXBuffer += F("Free Stack:<TD>");
TXBuffer += String(getCurrentFreeStack());
TXBuffer += F(" (");
TXBuffer += String(lowestFreeStack);
TXBuffer += F(" - ");
TXBuffer += String(lowestFreeStackfunction);
TXBuffer += F(")");
html_TR_TD(); TXBuffer += F("IP:<TD>");
TXBuffer += formatIP(ip);
@@ -1033,6 +1040,7 @@ void handle_config() {
MQTTclient_should_reconnect = true;
}
strncpy(Settings.Name, name.c_str(), sizeof(Settings.Name));
Settings.appendUnitToHostname(isFormItemChecked(F("appendunittohostname")));
//strncpy(SecuritySettings.Password, password.c_str(), sizeof(SecuritySettings.Password));
copyFormPassword(F("password"), SecuritySettings.Password, sizeof(SecuritySettings.Password));
strncpy(SecuritySettings.WifiSSID, ssid.c_str(), sizeof(SecuritySettings.WifiSSID));
@@ -1082,7 +1090,8 @@ void handle_config() {
Settings.Name[25] = 0;
SecuritySettings.Password[25] = 0;
addFormTextBox( F("Unit Name"), F("name"), Settings.Name, 25);
addFormNumericBox( F("Unit Number"), F("unit"), Settings.Unit, 0, 9999);
addFormNumericBox( F("Unit Number"), F("unit"), Settings.Unit, 0, UNIT_NUMBER_MAX);
addFormCheckBox(F("Append Unit Number to hostname"), F("appendunittohostname"), Settings.appendUnitToHostname());
addFormPasswordBox(F("Admin Password"), F("password"), SecuritySettings.Password, 25);
addFormSubHeader(F("Wifi Settings"));
@@ -1174,6 +1183,7 @@ void handle_controllers() {
const int maxqueuedepth = getFormItemInt(F("maxqueuedepth"), 10);
const int maxretry = getFormItemInt(F("maxretry"), 10);
String deleteoldest = WebServer.arg(F("deleteoldest"));
const int clienttimeout = getFormItemInt(F("clienttimeout"), CONTROLLER_CLIENTTIMEOUT_DFLT);
//submitted data
@@ -1192,7 +1202,8 @@ void handle_controllers() {
//reset (some) default-settings
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[controllerindex]);
ControllerSettings.Port = Protocol[ProtocolIndex].defaultPort;
ControllerSettings.MinimalTimeBetweenMessages = 100;
ControllerSettings.MinimalTimeBetweenMessages = CONTROLLER_DELAY_QUEUE_DELAY_DFLT;
ControllerSettings.ClientTimeout = CONTROLLER_CLIENTTIMEOUT_DFLT;
// ControllerSettings.MaxQueueDepth = 0;
if (Protocol[ProtocolIndex].usesTemplate)
CPlugin_ptr[ProtocolIndex](CPLUGIN_PROTOCOL_TEMPLATE, &TempEvent, dummyString);
@@ -1257,12 +1268,13 @@ void handle_controllers() {
ControllerSettings.MaxQueueDepth = maxqueuedepth;
ControllerSettings.MaxRetry = maxretry;
ControllerSettings.DeleteOldest = deleteoldest.toInt();
ControllerSettings.ClientTimeout = clienttimeout;
CPlugin_ptr[ProtocolIndex](CPLUGIN_INIT, &TempEvent, dummyString);
}
}
addHtmlError(SaveControllerSettings(controllerindex, (byte*)&ControllerSettings, sizeof(ControllerSettings)));
addHtmlError(SaveControllerSettings(controllerindex, ControllerSettings));
addHtmlError(SaveSettings());
}
@@ -1276,7 +1288,7 @@ void handle_controllers() {
ControllerSettingsStruct ControllerSettings;
for (byte x = 0; x < CONTROLLER_MAX; x++)
{
LoadControllerSettings(x, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(x, ControllerSettings);
html_TR_TD();
TXBuffer += F("<a class='button link' href=\"controllers?index=");
TXBuffer += x + 1;
@@ -1332,7 +1344,7 @@ void handle_controllers() {
if (Settings.Protocol[controllerindex])
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(controllerindex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(controllerindex, ControllerSettings);
byte choice = ControllerSettings.UseDNS;
String options[2];
options[0] = F("Use IP address");
@@ -1364,6 +1376,8 @@ void handle_controllers() {
addFormNumericBox( F("Max Queue Depth"), F("maxqueuedepth"), ControllerSettings.MaxQueueDepth, 1, CONTROLLER_DELAY_QUEUE_DEPTH_MAX);
addFormNumericBox( F("Max Retries"), F("maxretry"), ControllerSettings.MaxRetry, 1, CONTROLLER_DELAY_QUEUE_RETRY_MAX);
addFormSelector(F("Full Queue Action"), F("deleteoldest"), 2, options_delete_oldest, NULL, NULL, choice_delete_oldest, true);
addFormNumericBox( F("Client Timeout"), F("clienttimeout"), ControllerSettings.ClientTimeout, 10, CONTROLLER_CLIENTTIMEOUT_MAX);
addUnit(F("ms"));
if (Protocol[ProtocolIndex].usesAccount)
@@ -2283,7 +2297,7 @@ void handle_devices() {
html_TR_TD(); TXBuffer += F("IDX:<TD>");
id = F("TDID"); //="taskdeviceid"
id += controllerNr + 1;
addNumericBox(id, Settings.TaskDeviceID[controllerNr][taskIndex], 0, 999999999); // Looks like it is an unsigned int, so could be up to 4 bln.
addNumericBox(id, Settings.TaskDeviceID[controllerNr][taskIndex], 0, DOMOTICZ_MAX_IDX);
}
}
}
@@ -2598,8 +2612,8 @@ void addPinSelect(boolean forI2C, String name, int choice)
//********************************************************************************
void addPinSelect(boolean forI2C, String name, int choice)
{
String options[PIN_D_MAX+1];
int optionValues[PIN_D_MAX+1];
String * options = new String[PIN_D_MAX+1];
int * optionValues = new int[PIN_D_MAX+1];
options[0] = F("- None -");
optionValues[0] = -1;
for(byte x=1; x < PIN_D_MAX+1; x++)
@@ -2609,6 +2623,8 @@ void addPinSelect(boolean forI2C, String name, int choice)
optionValues[x] = x;
}
renderHTMLForPinSelect(options, optionValues, forI2C, name, choice, PIN_D_MAX+1);
delete[] optionValues;
delete[] options;
}
#endif
@@ -3649,6 +3665,7 @@ void handle_control() {
}
else if (command.equalsIgnoreCase(F("taskrun")) ||
command.equalsIgnoreCase(F("taskvalueset")) ||
command.equalsIgnoreCase(F("taskvaluetoggle")) ||
command.equalsIgnoreCase(F("rules"))) {
addLog(LOG_LEVEL_INFO,String(F("HTTP : ")) + webrequest);
ExecuteCommand(VALUE_SOURCE_HTTP,webrequest.c_str());
@@ -4190,6 +4207,7 @@ void handle_download()
WebServer.sendHeader(F("Content-Disposition"), str);
WebServer.streamFile(dataFile, F("application/octet-stream"));
dataFile.close();
}
@@ -4569,18 +4587,40 @@ void handle_filelist() {
checkRuleSets();
}
const int pageSize = 25;
int startIdx = 0;
String fstart = WebServer.arg(F("start"));
if (fstart.length() > 0)
{
startIdx = atoi(fstart.c_str());
}
int endIdx = startIdx + pageSize - 1;
TXBuffer += F("<table class='multirow' border=1px frame='box' rules='all'><TH style='width:50px;'><TH>Filename<TH style='width:80px;'>Size");
fs::Dir dir = SPIFFS.openDir("");
int count = -1;
while (dir.next())
{
++count;
if (count < startIdx)
{
continue;
}
html_TR_TD();
if (dir.fileName() != F(FILE_CONFIG) && dir.fileName() != F(FILE_SECURITY) && dir.fileName() != F(FILE_NOTIFICATION))
{
TXBuffer += F("<a class='button link' href=\"filelist?delete=");
TXBuffer += dir.fileName();
if (startIdx > 0)
{
TXBuffer += F("&start=");
TXBuffer += startIdx;
}
TXBuffer += F("\">Del</a>");
}
@@ -4591,12 +4631,32 @@ void handle_filelist() {
TXBuffer += F("</a>");
fs::File f = dir.openFile("r");
html_TD();
TXBuffer += f.size();
if (f) {
TXBuffer += f.size();
f.close();
}
if (count >= endIdx)
{
break;
}
}
TXBuffer += F("</table></form>");
TXBuffer += F("<BR><a class='button link' href=\"/upload\">Upload</a><BR><BR>");
sendHeadandTail(F("TmplStd"),true);
TXBuffer.endStream();
TXBuffer += F("<BR><a class='button link' href=\"/upload\">Upload</a>");
if (startIdx > 0)
{
TXBuffer += F("<a class='button link' href=\"/filelist?start=");
TXBuffer += max(0, startIdx - pageSize);
TXBuffer += F("\">Previous</a>");
}
if (count >= endIdx and dir.next())
{
TXBuffer += F("<a class='button link' href=\"/filelist?start=");
TXBuffer += endIdx + 1;
TXBuffer += F("\">Next</a>");
}
TXBuffer += F("<BR><BR>");
sendHeadandTail(F("TmplStd"),true);
TXBuffer.endStream();
#endif
#if defined(ESP32)
String fdelete = WebServer.arg(F("delete"));
@@ -4607,35 +4667,67 @@ void handle_filelist() {
// flashCount();
}
const int pageSize = 25;
int startIdx = 0;
String fstart = WebServer.arg(F("start"));
if (fstart.length() > 0)
{
startIdx = atoi(fstart.c_str());
}
int endIdx = startIdx + pageSize - 1;
TXBuffer += F("<table class='multirow' border=1px frame='box' rules='all'><TH><TH>Filename<TH>Size");
File root = SPIFFS.open("/");
File file = root.openNextFile();
while (file)
int count = -1;
while (file and count < endIdx)
{
if(!file.isDirectory()){
html_TR_TD();
if (strcmp(file.name(), FILE_CONFIG) != 0 && strcmp(file.name(), FILE_SECURITY) != 0 && strcmp(file.name(), FILE_NOTIFICATION) != 0)
{
TXBuffer += F("<a class='button link' href=\"filelist?delete=");
TXBuffer += file.name();
TXBuffer += F("\">Del</a>");
}
++count;
TXBuffer += F("<TD><a href=\"");
TXBuffer += file.name();
TXBuffer += F("\">");
TXBuffer += file.name();
TXBuffer += F("</a>");
html_TD();
TXBuffer += file.size();
file = root.openNextFile();
if (count >= startIdx)
{
html_TR_TD();
if (strcmp(file.name(), FILE_CONFIG) != 0 && strcmp(file.name(), FILE_SECURITY) != 0 && strcmp(file.name(), FILE_NOTIFICATION) != 0)
{
TXBuffer += F("<a class='button link' href=\"filelist?delete=");
TXBuffer += file.name();
if (startIdx > 0)
{
TXBuffer += F("&start=");
TXBuffer += startIdx;
}
TXBuffer += F("\">Del</a>");
}
TXBuffer += F("<TD><a href=\"");
TXBuffer += file.name();
TXBuffer += F("\">");
TXBuffer += file.name();
TXBuffer += F("</a>");
html_TD();
TXBuffer += file.size();
}
}
file = root.openNextFile();
}
TXBuffer += F("</table></form>");
TXBuffer += F("<BR><a class='button link' href=\"/upload\">Upload</a><BR><BR>");
TXBuffer += F("<BR><a class='button link' href=\"/upload\">Upload</a>");
if (startIdx > 0)
{
TXBuffer += F("<a class='button link' href=\"/filelist?start=");
TXBuffer += startIdx < pageSize ? 0 : startIdx - pageSize;
TXBuffer += F("\">Previous</a>");
}
if (count >= endIdx and file)
{
TXBuffer += F("<a class='button link' href=\"/filelist?start=");
TXBuffer += endIdx + 1;
TXBuffer += F("\">Next</a>");
}
TXBuffer += F("<BR><BR>");
sendHeadandTail(F("TmplStd"),true);
TXBuffer.endStream();
#endif
@@ -4900,7 +4992,11 @@ void handle_setup() {
{
html_TR_TD(); TXBuffer += F("<label class='container2'>");
TXBuffer += F("<input type='radio' name='ssid' value='");
TXBuffer += WiFi.SSID(i);
{
String escapeBuffer = WiFi.SSID(i);
htmlStrongEscape(escapeBuffer);
TXBuffer += escapeBuffer;
}
TXBuffer += F("'");
if (WiFi.SSID(i) == ssid)
TXBuffer += F(" checked ");
@@ -5039,7 +5135,7 @@ void handle_rules() {
log += F(" Create new file: ");
log += fileName;
fs::File f = SPIFFS.open(fileName, "w");
f.close();
if (f) f.close();
}
}
addLog(LOG_LEVEL_INFO, log);
@@ -5175,6 +5271,13 @@ void handle_sysinfo() {
TXBuffer += F(" - ");
TXBuffer += lowestRAMfunction;
TXBuffer += F(")");
html_TR_TD(); TXBuffer += F("Free Stack<TD>");
TXBuffer += getCurrentFreeStack();
TXBuffer += F(" (");
TXBuffer += lowestFreeStack;
TXBuffer += F(" - ");
TXBuffer += lowestFreeStackfunction;
TXBuffer += F(")");
html_TR_TD(); TXBuffer += F("Boot<TD>");
TXBuffer += getLastBootCauseString();
@@ -5342,6 +5445,8 @@ void handle_sysinfo() {
TXBuffer += ESP.getCpuFreqMHz();
TXBuffer += F(" MHz");
#endif
html_TR_TD(); TXBuffer += F("ESP Board Name:<TD>");
TXBuffer += ARDUINO_BOARD;
addTableSeparator(F("Storage"), 2, 3);
+1 -1
View File
@@ -34,7 +34,7 @@ boolean CPlugin_001(byte function, struct EventStruct *event, String& string)
case CPLUGIN_INIT:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
C001_DelayHandler.configureControllerSettings(ControllerSettings);
break;
}
+2 -2
View File
@@ -36,7 +36,7 @@ boolean CPlugin_002(byte function, struct EventStruct *event, String& string)
case CPLUGIN_INIT:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
MQTTDelayHandler.configureControllerSettings(ControllerSettings);
break;
}
@@ -146,7 +146,7 @@ boolean CPlugin_002(byte function, struct EventStruct *event, String& string)
if (event->idx != 0)
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
/*
if (!ControllerSettings.checkHostReachable(true)) {
success = false;
+3 -3
View File
@@ -33,7 +33,7 @@ boolean CPlugin_003(byte function, struct EventStruct *event, String& string)
case CPLUGIN_INIT:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
C003_DelayHandler.configureControllerSettings(ControllerSettings);
break;
}
@@ -82,7 +82,7 @@ bool do_process_c003_delay_queue(int controller_number, const C003_queue_element
delay(1);
timer = millis() + 1000;
while (client.available() && !timeOutReached(timer) && !success)
while (client_available(client) && !timeOutReached(timer) && !success)
{
// String line = client.readStringUntil('\n');
@@ -109,7 +109,7 @@ bool do_process_c003_delay_queue(int controller_number, const C003_queue_element
addLog(LOG_LEVEL_DEBUG, log);
client.print(element.txt);
delay(10);
while (client.available())
while (client_available(client))
client.read();
strcpy_P(log, PSTR("TELNT: closing connection"));
+1 -1
View File
@@ -33,7 +33,7 @@ boolean CPlugin_004(byte function, struct EventStruct *event, String& string)
case CPLUGIN_INIT:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
C004_DelayHandler.configureControllerSettings(ControllerSettings);
break;
}
+2 -2
View File
@@ -34,7 +34,7 @@ boolean CPlugin_005(byte function, struct EventStruct *event, String& string)
case CPLUGIN_INIT:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
MQTTDelayHandler.configureControllerSettings(ControllerSettings);
break;
}
@@ -93,7 +93,7 @@ boolean CPlugin_005(byte function, struct EventStruct *event, String& string)
case CPLUGIN_PROTOCOL_SEND:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
if (!ControllerSettings.checkHostReachable(true)) {
success = false;
break;
+2 -2
View File
@@ -34,7 +34,7 @@ boolean CPlugin_006(byte function, struct EventStruct *event, String& string)
case CPLUGIN_INIT:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
MQTTDelayHandler.configureControllerSettings(ControllerSettings);
break;
}
@@ -91,7 +91,7 @@ boolean CPlugin_006(byte function, struct EventStruct *event, String& string)
break;
}
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
statusLED(true);
+1 -1
View File
@@ -33,7 +33,7 @@ boolean CPlugin_007(byte function, struct EventStruct *event, String& string)
case CPLUGIN_INIT:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
C007_DelayHandler.configureControllerSettings(ControllerSettings);
break;
}
+2 -2
View File
@@ -35,7 +35,7 @@ boolean CPlugin_008(byte function, struct EventStruct *event, String& string)
case CPLUGIN_INIT:
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
C008_DelayHandler.configureControllerSettings(ControllerSettings);
break;
}
@@ -56,7 +56,7 @@ boolean CPlugin_008(byte function, struct EventStruct *event, String& string)
PluginCall(PLUGIN_GET_DEVICEVALUENAMES, event, dummyString);
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
for (byte x = 0; x < valueCount; x++)
{
+1 -1
View File
@@ -24,7 +24,7 @@
- removed obsolete http get url code
- v1.04
- added build options and node_type_id to JSON/device
/******************************************************************************/
******************************************************************************/
#define CPLUGIN_009
#define CPLUGIN_ID_009 9
+1 -1
View File
@@ -46,7 +46,7 @@ boolean CPlugin_010(byte function, struct EventStruct *event, String& string)
PluginCall(PLUGIN_GET_DEVICEVALUENAMES, event, dummyString);
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
for (byte x = 0; x < valueCount; x++)
{
+1 -1
View File
@@ -148,7 +148,7 @@ boolean Create_schedule_HTTP_C011(struct EventStruct *event)
return false;
}
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
C011_ConfigStruct customConfig;
LoadCustomControllerSettings(event->ControllerIndex,(byte*)&customConfig, sizeof(customConfig));
+4 -4
View File
@@ -41,7 +41,7 @@ boolean CPlugin_012(byte function, struct EventStruct *event, String& string)
PluginCall(PLUGIN_GET_DEVICEVALUENAMES, event, dummyString);
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(event->ControllerIndex, ControllerSettings);
for (byte x = 0; x < valueCount; x++)
{
@@ -83,7 +83,7 @@ boolean Blynk_get(const String& command, byte controllerIndex, float *data )
}
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(controllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(controllerIndex, ControllerSettings);
if ((SecuritySettings.ControllerPassword[controllerIndex][0] == 0)) {
addLog(LOG_LEVEL_ERROR, F("Blynk : No password set"));
@@ -113,7 +113,7 @@ boolean Blynk_get(const String& command, byte controllerIndex, float *data )
char log[80] = {0};
// Read all the lines of the reply from server and log them
while (client.available()) {
while (client_available(client)) {
String line;
safeReadStringUntil(client, line, '\n');
addLog(LOG_LEVEL_DEBUG_MORE, line);
@@ -154,7 +154,7 @@ boolean Blynk_get(const String& command, byte controllerIndex, float *data )
client.flush();
client.stop();
// important - backgroudtasks - free mem
// important - backgroundtasks - free mem
timer = millis() + Settings.MessageDelay;
while (!timeOutReached(timer))
backgroundtasks();
+24 -5
View File
@@ -324,7 +324,7 @@ ControllerDelayHandlerStruct<MQTT_queue_element> MQTTDelayHandler;
C##NNN##_queue_element element; \
if (!C##NNN##_DelayHandler.getNext(element)) return; \
ControllerSettingsStruct ControllerSettings; \
LoadControllerSettings(element.controller_idx, (byte*)&ControllerSettings, sizeof(ControllerSettings)); \
LoadControllerSettings(element.controller_idx, ControllerSettings); \
C##NNN##_DelayHandler.configureControllerSettings(ControllerSettings); \
if (!WiFiConnected(100)) { \
scheduleNextDelayQueue(TIMER_C##NNN##_DELAY_QUEUE, C##NNN##_DelayHandler.getNextScheduleTime()); \
@@ -380,7 +380,9 @@ ControllerDelayHandlerStruct<MQTT_queue_element> MQTTDelayHandler;
bool safeReadStringUntil(Stream &input, String &str, char terminator, unsigned int maxSize = 1024, unsigned int timeout = 1000)
{
int c;
const unsigned long timer = millis() + timeout;
const unsigned long start = millis();
const unsigned long timer = start + timeout;
unsigned long backgroundtasks_timer = start + 10;
str = "";
do {
@@ -401,7 +403,13 @@ bool safeReadStringUntil(Stream &input, String &str, char terminator, unsigned i
}
}
}
yield();
// We must run the backgroundtasks every now and then.
if (timeOutReached(backgroundtasks_timer)) {
backgroundtasks_timer += 10;
backgroundtasks();
} else {
yield();
}
} while (!timeOutReached(timer));
addLog(LOG_LEVEL_ERROR, F("Timeout while reading input data!"));
@@ -576,6 +584,7 @@ bool count_connection_results(bool success, const String& prefix, int controller
}
bool try_connect_host(int controller_number, WiFiUDP& client, ControllerSettingsStruct& ControllerSettings) {
client.setTimeout(ControllerSettings.ClientTimeout);
log_connecting_to(F("UDP : "), controller_number, ControllerSettings);
bool success = ControllerSettings.beginPacket(client) != 0;
return count_connection_results(
@@ -585,6 +594,7 @@ bool try_connect_host(int controller_number, WiFiUDP& client, ControllerSettings
bool try_connect_host(int controller_number, WiFiClient& client, ControllerSettingsStruct& ControllerSettings) {
// Use WiFiClient class to create TCP connections
client.setTimeout(ControllerSettings.ClientTimeout);
log_connecting_to(F("HTTP : "), controller_number, ControllerSettings);
bool success = ControllerSettings.connectToHost(client);
return count_connection_results(
@@ -592,17 +602,26 @@ bool try_connect_host(int controller_number, WiFiClient& client, ControllerSetti
F("HTTP : "), controller_number, ControllerSettings);
}
// Use "client.available() || client.connected()" to read all lines from slow servers.
// See: https://github.com/esp8266/Arduino/pull/5113
// https://github.com/esp8266/Arduino/pull/1829
bool client_available(WiFiClient& client) {
return client.available() || client.connected();
}
bool send_via_http(const String& logIdentifier, WiFiClient& client, const String& postStr) {
bool success = false;
// This will send the request to the server
client.print(postStr);
unsigned long timer = millis() + 200;
while (!client.available() && !timeOutReached(timer))
while (!client.available()) {
if (timeOutReached(timer)) return false;
delay(1);
}
// Read all the lines of the reply from server and print them to Serial
while (client.available() && !success) {
while (client_available(client) && !success) {
// String line = client.readStringUntil('\n');
String line;
safeReadStringUntil(client, line, '\n');
+1
View File
@@ -73,6 +73,7 @@ boolean NPlugin_001_send(const NotificationSettingsStruct& notificationsettings,
// Use WiFiClient class to create TCP connections
WiFiClient client;
client.setTimeout(CONTROLLER_CLIENTTIMEOUT_DFLT);
String aHost = notificationsettings.Server;
addLog(LOG_LEVEL_DEBUG, String(F("EMAIL: Connecting to ")) + aHost + notificationsettings.Port);
if (client.connect(aHost.c_str(), notificationsettings.Port) != 1) {
+16
View File
@@ -257,6 +257,22 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
}
}
if (command == F("gpiotoggle"))
{
success = true;
byte mode;
uint16_t currentState;
getPinState(PLUGIN_ID_001, event->Par1, &mode, &currentState);
if (mode == PIN_MODE_OUTPUT || mode == PIN_MODE_UNDEFINED) { //toggle only output pins
digitalWrite(event->Par1, !currentState);
setPinState(PLUGIN_ID_001, event->Par1, PIN_MODE_OUTPUT, !currentState);
log = String(F("SW : Toggle GPIO ")) + String(event->Par1) + String(F(" Set to ")) + String(!currentState);
addLog(LOG_LEVEL_INFO, log);
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_001, event->Par1, log, 0));
}
}
if (command == F("pwm"))
{
success = true;
+4 -4
View File
@@ -90,7 +90,7 @@ boolean Plugin_004(byte function, struct EventStruct * event, String& string)
resolutionChoice = Plugin_004_DS_getResolution(savedAddress);
else
resolutionChoice = 9;
String resultsOptions[4] = { "9", "10", "11", "12" };
String resultsOptions[4] = { F("9"), F("10"), F("11"), F("12") };
int resultsOptionValues[4] = { 9, 10, 11, 12 };
addFormSelector(F("Device Resolution"), F("plugin_004_res"), 4, resultsOptions, resultsOptionValues, resolutionChoice);
addHtml(F(" Bit"));
@@ -105,7 +105,6 @@ boolean Plugin_004(byte function, struct EventStruct * event, String& string)
// save the address for selected device and store into extra tasksettings
Plugin_004_DallasPin = Settings.TaskDevicePin1[event->TaskIndex];
// byte devCount =
if (Plugin_004_DallasPin != -1){
Plugin_004_DS_scan(getFormItemInt(F("plugin_004_dev")), addr);
for (byte x = 0; x < 8; x++)
@@ -124,11 +123,12 @@ boolean Plugin_004(byte function, struct EventStruct * event, String& string)
{
if (x != 0)
string += "-";
// string += String(ExtraTaskSettings.TaskDevicePluginConfigLong[x], HEX);
string += String(ExtraTaskSettings.TaskDevicePluginConfigLong[x], HEX);
}
success = true;
break;
}
case PLUGIN_INIT:
{
Plugin_004_DallasPin = Settings.TaskDevicePin1[event->TaskIndex];
@@ -169,7 +169,7 @@ boolean Plugin_004(byte function, struct EventStruct * event, String& string)
for (byte x = 0; x < 8; x++)
{
if (x != 0)
log += "-";
log += '-';
log += String(ExtraTaskSettings.TaskDevicePluginConfigLong[x], HEX);
}
+142 -116
View File
@@ -9,6 +9,19 @@
#define PLUGIN_VALUENAME1_005 "Temperature"
#define PLUGIN_VALUENAME2_005 "Humidity"
#define P005_DHT11 11
#define P005_DHT12 12
#define P005_DHT22 22
#define P005_AM2301 23
#define P005_SI7021 70
#define P005_error_no_reading 1
#define P005_error_protocol_timeout 2
#define P005_error_checksum_error 3
#define P005_error_invalid_NAN_reading 4
#define P005_info_temperature 5
#define P005_info_humidity 6
uint8_t Plugin_005_DHT_Pin;
boolean Plugin_005(byte function, struct EventStruct *event, String& string)
@@ -49,7 +62,7 @@ boolean Plugin_005(byte function, struct EventStruct *event, String& string)
case PLUGIN_WEBFORM_LOAD:
{
const String options[] = { F("DHT 11"), F("DHT 22"), F("DHT 12"), F("Sonoff am2301"), F("Sonoff si7021") };
int indices[] = { 11, 22, 12, 23, 70 };
int indices[] = { P005_DHT11, P005_DHT22, P005_DHT12, P005_AM2301, P005_SI7021 };
addFormSelector(F("DHT Type"), F("plugin_005_dhttype"), 5, options, indices, Settings.TaskDevicePluginConfig[event->TaskIndex][0] );
@@ -67,92 +80,7 @@ boolean Plugin_005(byte function, struct EventStruct *event, String& string)
case PLUGIN_READ:
{
byte dht_dat[5];
byte i;
boolean error = false;
byte Par3 = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
Plugin_005_DHT_Pin = Settings.TaskDevicePin1[event->TaskIndex];
pinMode(Plugin_005_DHT_Pin, OUTPUT);
digitalWrite(Plugin_005_DHT_Pin, LOW); // Pull low
if(Par3 == 11 || Par3 == 22 || Par3 == 12) delay(18);
else if (Par3 == 23 ) delayMicroseconds(900);
else if (Par3 == 70 ) delayMicroseconds(500);
pinMode(Plugin_005_DHT_Pin, INPUT); // change pin to input
delayMicroseconds(50);
error = waitState(0);
if(error)
{ logError(event, F("DHT : no Reading !"));
break;
}
error = waitState(1);
if(error)
{ logError(event, F("DHT : no Reading !"));
break;
}
noInterrupts();
error = waitState(0);
if(error)
{ logError(event, F("DHT : no Reading !"));
break;
}
for (i = 0; i < 5; i++)
{
byte data = Plugin_005_read_dht_dat();
if(data == -1)
{ logError(event, F("DHT : protocol timeout!"));
break;
}
dht_dat[i] = data;
}
interrupts();
// Checksum calculation is a Rollover Checksum by design!
byte dht_check_sum = (dht_dat[0] + dht_dat[1] + dht_dat[2] + dht_dat[3]) & 0xFF; // check check_sum
if (dht_dat[4] != dht_check_sum)
{
logError(event, F("DHT : checksum error!"));
break;
}
float temperature = NAN;
float humidity = NAN;
if (Par3 == 11)
{
temperature = float(dht_dat[2]); // Temperature
humidity = float(dht_dat[0]); // Humidity
}
else if (Par3 == 12)
{
temperature = float(dht_dat[2]*10 + (dht_dat[3] & 0x7f)) / 10.0; // Temperature
if (dht_dat[3] & 0x80) { temperature = -temperature; } // Negative temperature
humidity = float(dht_dat[0]*10+dht_dat[1]) / 10.0; // Humidity
}
else if (Par3 == 22 || Par3 == 23 || Par3 == 70)
{
if (dht_dat[2] & 0x80) // negative temperature
temperature = -0.1 * word(dht_dat[2] & 0x7F, dht_dat[3]);
else
temperature = 0.1 * word(dht_dat[2], dht_dat[3]);
humidity = 0.1 * word(dht_dat[0], dht_dat[1]); // Humidity
}
if (temperature == NAN || humidity == NAN)
{ logError(event, F("DHT : invalid NAN reading !"));
break;
}
UserVar[event->BaseVarIndex] = temperature;
UserVar[event->BaseVarIndex + 1] = humidity;
String log = F("DHT : Temperature: ");
log += UserVar[event->BaseVarIndex];
addLog(LOG_LEVEL_INFO, log);
log = F("DHT : Humidity: ");
log += UserVar[event->BaseVarIndex + 1];
addLog(LOG_LEVEL_INFO, log);
success = true;
success = P005_do_plugin_read(event);
break;
}
}
@@ -163,28 +91,144 @@ boolean Plugin_005(byte function, struct EventStruct *event, String& string)
/*********************************************************************************************\
* DHT sub to log an error
\*********************************************************************************************/
void logError(struct EventStruct *event, String text)
void P005_log(struct EventStruct *event, int logNr)
{
bool isError = true;
String text = F("DHT : ");
switch (logNr) {
case P005_error_no_reading: text += F("No Reading"); break;
case P005_error_protocol_timeout: text += F("Protocol Timeout"); break;
case P005_error_checksum_error: text += F("Checksum Error"); break;
case P005_error_invalid_NAN_reading: text += F("Invalid NAN reading"); break;
case P005_info_temperature:
text += F("Temperature: ");
text += UserVar[event->BaseVarIndex];
isError = false;
break;
case P005_info_humidity:
text += F("Humidity: ");
text += UserVar[event->BaseVarIndex + 1];
isError = false;
break;
}
addLog(LOG_LEVEL_INFO, text);
UserVar[event->BaseVarIndex] = NAN;
UserVar[event->BaseVarIndex + 1] = NAN;
if (isError) {
UserVar[event->BaseVarIndex] = NAN;
UserVar[event->BaseVarIndex + 1] = NAN;
}
}
/*********************************************************************************************\
* DHT sub to wait until a pin is in a certiin state
* DHT sub to wait until a pin is in a certain state
\*********************************************************************************************/
boolean waitState(int state)
boolean P005_waitState(int state)
{
byte counter = 0;
while (( digitalRead(Plugin_005_DHT_Pin) != state) && (counter < 100))
unsigned long timeout = micros() + 100;
while (digitalRead(Plugin_005_DHT_Pin) != state)
{
if (usecTimeOutReached(timeout)) return false;
delayMicroseconds(1);
counter++;
}
if( counter < 100) return false;
return true;
}
/*********************************************************************************************\
* Perform the actual reading + interpreting of data.
\*********************************************************************************************/
bool P005_do_plugin_read(struct EventStruct *event) {
byte i;
byte Par3 = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
Plugin_005_DHT_Pin = Settings.TaskDevicePin1[event->TaskIndex];
pinMode(Plugin_005_DHT_Pin, OUTPUT);
digitalWrite(Plugin_005_DHT_Pin, LOW); // Pull low
switch (Par3) {
case P005_DHT11:
case P005_DHT22:
case P005_DHT12: delay(18); break; // FIXME TD-er: Must this be so long?
case P005_AM2301: delayMicroseconds(900); break;
case P005_SI7021: delayMicroseconds(500); break;
}
switch (Par3) {
case P005_DHT11:
case P005_DHT22:
case P005_DHT12:
case P005_AM2301:
pinMode(Plugin_005_DHT_Pin, INPUT);
delayMicroseconds(50);
break;
case P005_SI7021:
// See: https://github.com/letscontrolit/ESPEasy/issues/1798
digitalWrite(Plugin_005_DHT_Pin, HIGH);
delayMicroseconds(20);
pinMode(Plugin_005_DHT_Pin, INPUT);
break;
}
if(!P005_waitState(0)) {P005_log(event, P005_error_no_reading); return false; }
if(!P005_waitState(1)) {P005_log(event, P005_error_no_reading); return false; }
noInterrupts();
if(!P005_waitState(0)) {P005_log(event, P005_error_no_reading); return false; }
bool readingAborted = false;
byte dht_dat[5];
for (i = 0; i < 5 && !readingAborted; i++)
{
byte data = Plugin_005_read_dht_dat();
if(data == -1)
{ P005_log(event, P005_error_protocol_timeout);
readingAborted = true;
}
dht_dat[i] = data;
}
interrupts();
if (readingAborted)
return false;
// Checksum calculation is a Rollover Checksum by design!
byte dht_check_sum = (dht_dat[0] + dht_dat[1] + dht_dat[2] + dht_dat[3]) & 0xFF; // check check_sum
if (dht_dat[4] != dht_check_sum)
{
P005_log(event, P005_error_checksum_error);
return false;
}
float temperature = NAN;
float humidity = NAN;
switch (Par3) {
case P005_DHT11:
temperature = float(dht_dat[2]); // Temperature
humidity = float(dht_dat[0]); // Humidity
break;
case P005_DHT12:
temperature = float(dht_dat[2]*10 + (dht_dat[3] & 0x7f)) / 10.0; // Temperature
if (dht_dat[3] & 0x80) { temperature = -temperature; } // Negative temperature
humidity = float(dht_dat[0]*10+dht_dat[1]) / 10.0; // Humidity
break;
case P005_DHT22:
case P005_AM2301:
case P005_SI7021:
if (dht_dat[2] & 0x80) // negative temperature
temperature = -0.1 * word(dht_dat[2] & 0x7F, dht_dat[3]);
else
temperature = 0.1 * word(dht_dat[2], dht_dat[3]);
humidity = 0.1 * word(dht_dat[0], dht_dat[1]); // Humidity
break;
}
if (temperature == NAN || humidity == NAN)
{ P005_log(event, P005_error_invalid_NAN_reading);
return false;
}
UserVar[event->BaseVarIndex] = temperature;
UserVar[event->BaseVarIndex + 1] = humidity;
P005_log(event, P005_info_temperature);
P005_log(event, P005_info_humidity);
return true;
}
/*********************************************************************************************\
* DHT sub to get an 8 bit value from the receiving bitstream
\*********************************************************************************************/
@@ -192,31 +236,13 @@ int Plugin_005_read_dht_dat(void)
{
byte i = 0;
byte result = 0;
byte counter = 0;
for (i = 0; i < 8; i++)
{
while ((!digitalRead(Plugin_005_DHT_Pin)) && (counter < 100))
{
delayMicroseconds(1);
counter++;
}
if (counter >= 100)
{
return -1;
}
if (!P005_waitState(1)) return -1;
delayMicroseconds(35); // was 30
if (digitalRead(Plugin_005_DHT_Pin))
result |= (1 << (7 - i));
counter = 0;
while ((digitalRead(Plugin_005_DHT_Pin)) && (counter < 100))
{
delayMicroseconds(1);
counter++;
}
if (counter >= 100)
{
return -1;
}
if (!P005_waitState(0)) return -1;
}
return result;
}
+17 -1
View File
@@ -20,7 +20,7 @@ boolean Plugin_009(byte function, struct EventStruct *event, String& string)
{
Device[++deviceCount].Number = PLUGIN_ID_009;
Device[deviceCount].Type = DEVICE_TYPE_I2C;
Device[deviceCount].VType = SENSOR_TYPE_SINGLE;
Device[deviceCount].VType = SENSOR_TYPE_SWITCH;
Device[deviceCount].Ports = 16;
Device[deviceCount].PullUpOption = false;
Device[deviceCount].InverseLogicOption = false;
@@ -124,6 +124,22 @@ boolean Plugin_009(byte function, struct EventStruct *event, String& string)
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_009, event->Par1, log, 0));
}
if (command == F("mcpgpiotoggle"))
{
success = true;
byte mode;
uint16_t currentState;
getPinState(PLUGIN_ID_009, event->Par1, &mode, &currentState);
if (mode == PIN_MODE_OUTPUT || mode == PIN_MODE_UNDEFINED) {
setPinState(PLUGIN_ID_009, event->Par1, PIN_MODE_OUTPUT, !currentState);
Plugin_009_Write(event->Par1, !currentState);
log = String(F("MCP : Toggle GPIO ")) + String(event->Par1) + String(F(" Set to ")) + String(!currentState);
addLog(LOG_LEVEL_INFO, log);
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_009, event->Par1, log, 0));
}
}
if (command == F("mcppulse"))
{
success = true;
+199 -58
View File
@@ -12,27 +12,21 @@
#include <map>
#include <NewPingESP8266.h>
struct P_013_sensordef {
P_013_sensordef() : sonar(NULL) {}
P_013_sensordef(byte TRIG_Pin, byte IRQ_Pin, int16_t max_cm_distance) : sonar(NULL) {
sonar = new NewPingESP8266(TRIG_Pin, IRQ_Pin, max_cm_distance);
}
~P_013_sensordef() {
if (sonar != NULL) {
delete sonar;
sonar = NULL;
}
}
NewPingESP8266 *sonar;
};
std::map<unsigned int, P_013_sensordef> P_013_sensordefs;
// PlugIn specific defines
// operatingMode
#define OPMODE_VALUE (0)
#define OPMODE_STATE (1)
// measuringUnit
#define UNIT_CM (0)
#define UNIT_INCH (1)
// filterType
#define FILTER_NONE (0)
#define FILTER_MEDIAN (1)
// map of sensors
std::map<unsigned int, std::shared_ptr<NewPingESP8266> > P_013_sensordefs;
boolean Plugin_013(byte function, struct EventStruct *event, String& string)
{
@@ -54,6 +48,7 @@ boolean Plugin_013(byte function, struct EventStruct *event, String& string)
Device[deviceCount].SendDataOption = true;
Device[deviceCount].TimerOption = true;
Device[deviceCount].GlobalSyncOption = true;
break;
}
@@ -72,19 +67,51 @@ boolean Plugin_013(byte function, struct EventStruct *event, String& string)
case PLUGIN_WEBFORM_LOAD:
{
byte choice = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
String options[2];
options[0] = F("Value");
options[1] = F("State");
int optionValues[2] = { 1, 2 };
addFormSelector(F("Mode"), F("plugin_013_mode"), 2, options, optionValues, choice);
int16_t operatingMode = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
int16_t threshold = Settings.TaskDevicePluginConfig[event->TaskIndex][1];
int16_t max_distance = Settings.TaskDevicePluginConfig[event->TaskIndex][2];
int16_t measuringUnit = Settings.TaskDevicePluginConfig[event->TaskIndex][3];
int16_t filterType = Settings.TaskDevicePluginConfig[event->TaskIndex][4];
int16_t filterSize = Settings.TaskDevicePluginConfig[event->TaskIndex][5];
if (Settings.TaskDevicePluginConfig[event->TaskIndex][0] == 2)
{
addFormNumericBox(F("Threshold"), F("plugin_013_threshold"), Settings.TaskDevicePluginConfig[event->TaskIndex][1]);
// default filtersize = 5
if (filterSize == 0) {
filterSize = 5;
Settings.TaskDevicePluginConfig[event->TaskIndex][5] = filterSize;
}
addFormNumericBox(F("Max Distance"), F("plugin_013_max_distance"), Settings.TaskDevicePluginConfig[event->TaskIndex][2], 0, 500);
addUnit(F("cm"));
String strUnit = (measuringUnit == UNIT_CM) ? F("cm") : F("inch");
String optionsOpMode[2];
int optionValuesOpMode[2] = { 0, 1 };
optionsOpMode[0] = F("Value");
optionsOpMode[1] = F("State");
addFormSelector(F("Mode"), F("plugin_013_mode"), 2, optionsOpMode, optionValuesOpMode, operatingMode);
if (operatingMode == OPMODE_STATE)
{
addFormNumericBox(F("Threshold"), F("plugin_013_threshold"), threshold);
addUnit(strUnit);
}
addFormNumericBox(F("Max Distance"), F("plugin_013_max_distance"), max_distance, 0, 500);
addUnit(strUnit);
String optionsUnit[2];
int optionValuesUnit[2] = { 0, 1 };
optionsUnit[0] = F("Metric");
optionsUnit[1] = F("Imperial");
addFormSelector(F("Unit"), F("plugin_013_Unit"), 2, optionsUnit, optionValuesUnit, measuringUnit);
String optionsFilter[2];
int optionValuesFilter[2] = { 0, 1 };
optionsFilter[0] = F("None");
optionsFilter[1] = F("Median");
addFormSelector(F("Filter"), F("plugin_013_FilterType"), 2, optionsFilter, optionValuesFilter, filterType);
// enable filtersize option if filter is used,
if (filterType != FILTER_NONE)
addFormNumericBox(F("Filter size"), F("plugin_013_FilterSize"), filterSize, 2, 20);
success = true;
break;
@@ -92,33 +119,60 @@ boolean Plugin_013(byte function, struct EventStruct *event, String& string)
case PLUGIN_WEBFORM_SAVE:
{
int16_t operatingMode = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
int16_t filterType = Settings.TaskDevicePluginConfig[event->TaskIndex][4];
Settings.TaskDevicePluginConfig[event->TaskIndex][0] = getFormItemInt(F("plugin_013_mode"));
if (Settings.TaskDevicePluginConfig[event->TaskIndex][0] == 2)
{
if (operatingMode == OPMODE_STATE)
Settings.TaskDevicePluginConfig[event->TaskIndex][1] = getFormItemInt(F("plugin_013_threshold"));
}
Settings.TaskDevicePluginConfig[event->TaskIndex][2] = getFormItemInt(F("plugin_013_max_distance"));
Settings.TaskDevicePluginConfig[event->TaskIndex][3] = getFormItemInt(F("plugin_013_Unit"));
Settings.TaskDevicePluginConfig[event->TaskIndex][4] = getFormItemInt(F("plugin_013_FilterType"));
if (filterType != FILTER_NONE)
Settings.TaskDevicePluginConfig[event->TaskIndex][5] = getFormItemInt(F("plugin_013_FilterSize"));
success = true;
break;
}
case PLUGIN_INIT:
{
byte Plugin_013_TRIG_Pin = Settings.TaskDevicePin1[event->TaskIndex];
byte Plugin_013_IRQ_Pin = Settings.TaskDevicePin2[event->TaskIndex];
int16_t max_cm_distance = Settings.TaskDevicePluginConfig[event->TaskIndex][2];
int16_t max_distance = Settings.TaskDevicePluginConfig[event->TaskIndex][2];
int16_t measuringUnit = Settings.TaskDevicePluginConfig[event->TaskIndex][3];
int16_t filterType = Settings.TaskDevicePluginConfig[event->TaskIndex][4];
int16_t filterSize = Settings.TaskDevicePluginConfig[event->TaskIndex][5];
int8_t Plugin_013_TRIG_Pin = Settings.TaskDevicePin1[event->TaskIndex];
int8_t Plugin_013_IRQ_Pin = Settings.TaskDevicePin2[event->TaskIndex];
int16_t max_distance_cm = (measuringUnit == UNIT_CM) ? max_distance : (float)max_distance * 2.54f;
// create sensor instance and add to std::map
P_013_sensordefs.erase(event->TaskIndex);
P_013_sensordefs[event->TaskIndex] =
P_013_sensordef(Plugin_013_TRIG_Pin, Plugin_013_IRQ_Pin, max_cm_distance);
std::shared_ptr<NewPingESP8266> (new NewPingESP8266(Plugin_013_TRIG_Pin, Plugin_013_IRQ_Pin, max_distance_cm));
String log = F("ULTRASONIC : TaskNr: ");
log += event->TaskIndex +1;
log += F(" TrigPin: ");
log += Plugin_013_TRIG_Pin;
log += F(" IRQ_Pin: ");
log += Plugin_013_IRQ_Pin;
log += F(" max dist cm: ");
log += max_cm_distance;
log += F(" max dist ");
log += (measuringUnit == UNIT_CM) ? F("[cm]: ") : F("[inch]: ");
log += max_distance;
log += F(" max echo: ");
log += P_013_sensordefs[event->TaskIndex].sonar->getMaxEchoTime();
log += P_013_sensordefs[event->TaskIndex]->getMaxEchoTime();
log += F(" Filter: ");
if (filterType == FILTER_NONE)
log += F("none");
else
if (filterType == FILTER_MEDIAN) {
log += F("Median size: ");
log += filterSize;
}
else
log += F("invalid!");
log += F(" nr_tasks: ");
log += P_013_sensordefs.size();
addLog(LOG_LEVEL_INFO, log);
@@ -136,7 +190,6 @@ boolean Plugin_013(byte function, struct EventStruct *event, String& string)
log += F(" usec, ");
addLog(LOG_LEVEL_INFO, log);
success = true;
break;
}
@@ -149,39 +202,48 @@ boolean Plugin_013(byte function, struct EventStruct *event, String& string)
case PLUGIN_READ: // If we select value mode, read and send the value based on global timer
{
if (Settings.TaskDevicePluginConfig[event->TaskIndex][0] == 1)
int16_t operatingMode = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
int16_t measuringUnit = Settings.TaskDevicePluginConfig[event->TaskIndex][3];
if (operatingMode == OPMODE_VALUE)
{
float value = Plugin_013_read(event->TaskIndex);
String log = F("ULTRASONIC : TaskNr: ");
log += event->TaskIndex +1;
log += F(" Distance: ");
if (value > 0)
UserVar[event->BaseVarIndex] = value;
log += UserVar[event->BaseVarIndex];
log += (measuringUnit == UNIT_CM) ? F(" cm ") : F(" inch ");
if (value == NO_ECHO)
{
UserVar[event->BaseVarIndex] = value;
log += UserVar[event->BaseVarIndex];
success = true;
log += F(" Error: ");
log += Plugin_013_getErrorStatusString(event->TaskIndex);
}
else
log += F("No reading!");
addLog(LOG_LEVEL_INFO,log);
addLog(LOG_LEVEL_INFO,log);
}
success = true;
break;
}
case PLUGIN_TEN_PER_SECOND: // If we select state mode, do more frequent checks and send only state changes
{
if (Settings.TaskDevicePluginConfig[event->TaskIndex][0] == 2)
int16_t operatingMode = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
int16_t threshold = Settings.TaskDevicePluginConfig[event->TaskIndex][1];
if (operatingMode == OPMODE_STATE)
{
byte state = 0;
float value = Plugin_013_read(event->TaskIndex);
if (value > 0)
if (value != NO_ECHO)
{
if (value < Settings.TaskDevicePluginConfig[event->TaskIndex][1])
if (value < threshold)
state = 1;
if (state != switchstate[event->TaskIndex])
{
String log = F("ULTRASONIC : State ");
String log = F("ULTRASONIC : TaskNr: ");
log += event->TaskIndex +1;
log += F(" state: ");
log += state;
addLog(LOG_LEVEL_INFO,log);
switchstate[event->TaskIndex] = state;
@@ -190,6 +252,14 @@ boolean Plugin_013(byte function, struct EventStruct *event, String& string)
sendData(event);
}
}
else {
String log = F("ULTRASONIC : TaskNr: ");
log += event->TaskIndex +1;
log += F(" Error: ");
log += Plugin_013_getErrorStatusString(event->TaskIndex);
addLog(LOG_LEVEL_INFO,log);
}
}
success = true;
break;
@@ -202,11 +272,82 @@ boolean Plugin_013(byte function, struct EventStruct *event, String& string)
float Plugin_013_read(unsigned int taskIndex)
/*********************************************************************/
{
if (P_013_sensordefs.count(taskIndex) == 0) return 0;
if (P_013_sensordefs[taskIndex].sonar == NULL) return 0;
delay(1);
float distance = P_013_sensordefs[taskIndex].sonar->ping_cm();
delay(1);
return distance;
if (P_013_sensordefs.count(taskIndex) == 0)
return 0;
int16_t max_distance = Settings.TaskDevicePluginConfig[taskIndex][2];
int16_t measuringUnit = Settings.TaskDevicePluginConfig[taskIndex][3];
int16_t filterType = Settings.TaskDevicePluginConfig[taskIndex][4];
int16_t filterSize = Settings.TaskDevicePluginConfig[taskIndex][5];
int16_t max_distance_cm = (measuringUnit == UNIT_CM) ? max_distance : (float)max_distance * 2.54f;
unsigned int echoTime = 0;
switch (filterType) {
case FILTER_NONE:
echoTime = (P_013_sensordefs[taskIndex])->ping();
break;
case FILTER_MEDIAN:
echoTime = (P_013_sensordefs[taskIndex])->ping_median(filterSize, max_distance_cm);
break;
default:
addLog(LOG_LEVEL_INFO, F("invalid Filter Type setting!"));
}
if (measuringUnit == UNIT_CM)
return NewPingESP8266::convert_cm_F(echoTime);
else
return NewPingESP8266::convert_in_F(echoTime);
}
/*********************************************************************/
String Plugin_013_getErrorStatusString(unsigned int taskIndex)
/*********************************************************************/
{
if (P_013_sensordefs.count(taskIndex) == 0)
return String(F("invalid taskindex"));
switch ((P_013_sensordefs[taskIndex])->getErrorState()) {
case NewPingESP8266::STATUS_SENSOR_READY: {
return String(F("Sensor ready"));
break;
}
case NewPingESP8266::STATUS_MEASUREMENT_VALID: {
return String(F("no error, measurement valid"));
break;
}
case NewPingESP8266::STATUS_ECHO_TRIGGERED: {
return String(F("Echo triggered, waiting for Echo end"));
break;
}
case NewPingESP8266::STATUS_ECHO_STATE_ERROR: {
return String(F("Echo pulse error, Echopin not low on trigger"));
break;
}
case NewPingESP8266::STATUS_ECHO_START_TIMEOUT_50ms: {
return String(F("Echo timeout error, no echo start whithin 50 ms"));
break;
}
case NewPingESP8266::STATUS_ECHO_START_TIMEOUT_DISTANCE: {
return String(F("Echo timeout error, no echo start whithin time for max. distance"));
break;
}
case NewPingESP8266::STATUS_MAX_DISTANCE_EXCEEDED: {
return String(F("Echo too late, maximum distance exceeded"));
break;
}
default: {
return String(F("unknown error"));
break;
}
}
}
#endif // USES_P013
+6
View File
@@ -41,6 +41,9 @@ decode_results results;
#define PLUGIN_NAME_016 "Communication - TSOP4838"
#define PLUGIN_VALUENAME1_016 "IR"
// A lot of the following code has been taken directly (with permission) from the IRrecvDumpV2.ino example code
// of the IRremoteESP8266 library. (https://github.com/markszabo/IRremoteESP8266)
// ==================== start of TUNEABLE PARAMETERS ====================
// As this program is a special purpose capture/decoder, let us use a larger
// than normal buffer so we can handle Air Conditioner remote codes.
@@ -155,7 +158,10 @@ boolean Plugin_016(byte function, struct EventStruct *event, String& string)
{
if (irReceiver->decode(&results))
{
unsigned long IRcode = results.value;
irReceiver->resume();
UserVar[event->BaseVarIndex] = (IRcode & 0xFFFF);
UserVar[event->BaseVarIndex + 1] = ((IRcode >> 16) & 0xFFFF);
String log = "IR: ";
if (results.overflow)
log += F("WARNING: IR code is too big for buffer. This result shouldn't be trusted until this is resolved. Edit & increase CAPTURE_BUFFER_SIZE.\n");
+17 -1
View File
@@ -20,7 +20,7 @@ boolean Plugin_019(byte function, struct EventStruct *event, String& string)
{
Device[++deviceCount].Number = PLUGIN_ID_019;
Device[deviceCount].Type = DEVICE_TYPE_I2C;
Device[deviceCount].VType = SENSOR_TYPE_SINGLE;
Device[deviceCount].VType = SENSOR_TYPE_SWITCH;
Device[deviceCount].Ports = 8;
Device[deviceCount].PullUpOption = false;
Device[deviceCount].InverseLogicOption = false;
@@ -128,6 +128,22 @@ boolean Plugin_019(byte function, struct EventStruct *event, String& string)
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_019, event->Par1, log, 0));
}
if (command == F("pcfgpiotoggle"))
{
success = true;
byte mode;
uint16_t currentState;
getPinState(PLUGIN_ID_019, event->Par1, &mode, &currentState);
if (mode == PIN_MODE_OUTPUT || mode == PIN_MODE_UNDEFINED) {
setPinState(PLUGIN_ID_019, event->Par1, PIN_MODE_OUTPUT, !currentState);
Plugin_019_Write(event->Par1, !currentState);
log = String(F("PCF : Toggle GPIO ")) + String(event->Par1) + String(F(" Set to ")) + String(!currentState);
addLog(LOG_LEVEL_INFO, log);
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_019, event->Par1, log, 0));
}
}
if (command == F("pcfpulse"))
{
success = true;
+7 -12
View File
@@ -382,8 +382,10 @@ bool Plugin_028_update_measurements(const uint8_t i2cAddress, float tempOffset,
return false;
}
if (!timeOutReached(sensor.last_measurement + 1000)) {
// Must wait one second to make sure the filtered values stabilize.
// It takes at least 1.587 sec for valit measurements to complete.
// The datasheet names this the "T63" moment.
// 1 second = 63% of the time needed to perform a measurement.
if (!timeOutReached(sensor.last_measurement + 1587)) {
return false;
}
if (!Plugin_028_readUncompensatedData(i2cAddress)) {
@@ -510,7 +512,7 @@ bool Plugin_028_begin(uint8_t i2cAddress) {
I2C_write8_reg(i2cAddress, BMx280_REGISTER_SOFTRESET, 0xB6);
delay(2); // Startup time is 2 ms (datasheet)
Plugin_028_readCoefficients(i2cAddress);
delay(65); //May be needed here as well to fix first wrong measurement?
// delay(65); //May be needed here as well to fix first wrong measurement?
return true;
}
@@ -548,8 +550,8 @@ void Plugin_028_readCoefficients(uint8_t i2cAddress)
bool Plugin_028_readUncompensatedData(uint8_t i2cAddress) {
// wait until measurement has been completed, otherwise we would read
// the values from the last measurement
while (I2C_read8_reg(i2cAddress, BMx280_REGISTER_STATUS) & 0x08)
delay(1);
if (I2C_read8_reg(i2cAddress, BMx280_REGISTER_STATUS) & 0x08)
return false;
I2Cdata_bytes BME280_data(BME280_P_T_H_DATA_LEN, BME280_DATA_ADDR);
bool allDataRead = I2C_read_bytes(i2cAddress, BME280_data);
@@ -642,13 +644,6 @@ float Plugin_028_readHumidity(uint8_t i2cAddress)
// No support for humidity
return 0.0;
}
// It takes at least 1.587 sec for valit measurements to complete.
// The datasheet names this the "T63" moment.
// 1 second = 63% of the time needed to perform a measurement.
unsigned long difTime = millis() - sensor.last_measurement;
if (difTime < 1587) {
delay(1587 - difTime);
}
int32_t adc_H = sensor.uncompensated.humidity;
int32_t v_x1_u32r;
+1 -1
View File
@@ -53,7 +53,7 @@ boolean Plugin_029(byte function, struct EventStruct *event, String& string)
addHtml(F("<TR><TD>IDX:<TD>"));
String id = F("TDID"); //="taskdeviceid"
id += controllerNr + 1;
addNumericBox(id, Settings.TaskDeviceID[controllerNr][event->TaskIndex], 0, 9999);
addNumericBox(id, Settings.TaskDeviceID[controllerNr][event->TaskIndex], 0, DOMOTICZ_MAX_IDX);
success = true;
break;
}
+3 -1
View File
@@ -274,6 +274,8 @@ boolean Plugin_035(byte function, struct EventStruct *event, String& string)
return success;
}
// A lot of the following code has been taken directly (with permission) from the IRMQTTServer.ino example code
// of the IRremoteESP8266 library. (https://github.com/markszabo/IRremoteESP8266)
// Parse an Air Conditioner A/C Hex String/code and send it.
// Args:
@@ -615,4 +617,4 @@ uint16_t countValuesInStr(const String str, char sep) {
// }
// return result;
//}
#endif // USES_P035
#endif // USES_P035
+66 -41
View File
@@ -24,6 +24,37 @@
WiFiClient espclient_037;
PubSubClient *MQTTclient_037 = NULL;
bool MQTTclient_037_connected = false;
int reconnectCount = 0;
String getClientName() {
//
// Generate the MQTT import client name from the system name and a suffix
//
String tmpClientName = F("%sysname%-Import");
String ClientName = parseTemplate(tmpClientName, 20);
if (reconnectCount != 0) ClientName += reconnectCount;
return ClientName;
}
void Plugin_037_try_connect() {
Plugin_037_update_connect_status();
if (MQTTclient_037_connected) return;
// workaround see: https://github.com/esp8266/Arduino/issues/4497#issuecomment-373023864
espclient_037 = WiFiClient();
espclient_037.setTimeout(CONTROLLER_CLIENTTIMEOUT_DFLT);
if (MQTTclient_037 == NULL) {
MQTTclient_037 = new PubSubClient(espclient_037);
}
if (MQTTConnect_037())
{
// Subscribe to ALL the topics from ALL instance of this import module
MQTTSubscribe_037();
} else {
MQTTclient_037->disconnect();
}
Plugin_037_update_connect_status();
}
void Plugin_037_update_connect_status() {
bool connected = false;
@@ -39,6 +70,8 @@ void Plugin_037_update_connect_status() {
if (!connected) {
// workaround see: https://github.com/esp8266/Arduino/issues/4497#issuecomment-373023864
espclient_037 = WiFiClient();
espclient_037.setTimeout(CONTROLLER_CLIENTTIMEOUT_DFLT);
++reconnectCount;
addLog(LOG_LEVEL_ERROR, F("IMPT : MQTT 037 Connection lost"));
}
}
@@ -49,11 +82,6 @@ boolean Plugin_037(byte function, struct EventStruct *event, String& string)
boolean success = false;
char deviceTemplate[4][41]; // variable for saving the subscription topics
//
// Generate the MQTT import client name from the system name and a suffix
//
String tmpClientName = F("%sysname%-Import");
String ClientName = parseTemplate(tmpClientName, 20);
switch (function)
{
@@ -121,30 +149,23 @@ boolean Plugin_037(byte function, struct EventStruct *event, String& string)
case PLUGIN_INIT:
{
if (!MQTTclient_037) {
MQTTclient_037 = new PubSubClient(espclient_037);
}
success = false;
// When we edit the subscription data from the webserver, the plugin is called again with init.
// In order to resubscribe we have to disconnect and reconnect in order to get rid of any obsolete subscriptions
MQTTclient_037->disconnect();
if (MQTTConnect_037(ClientName))
{
// Subscribe to ALL the topics from ALL instance of this import module
MQTTSubscribe_037();
success = true;
}
else
{
success = false;
if (MQTTclient_037 != NULL) {
MQTTclient_037->disconnect();
if (MQTTConnect_037())
{
// Subscribe to ALL the topics from ALL instance of this import module
MQTTSubscribe_037();
success = true;
}
}
}
case PLUGIN_TEN_PER_SECOND:
{
if (!MQTTclient_037->loop()) { // Listen out for callbacks
if (MQTTclient_037 != NULL && !MQTTclient_037->loop()) { // Listen out for callbacks
Plugin_037_update_connect_status();
}
success = true;
@@ -154,25 +175,26 @@ boolean Plugin_037(byte function, struct EventStruct *event, String& string)
case PLUGIN_ONCE_A_SECOND:
{
// Here we check that the MQTT client is alive.
Plugin_037_try_connect();
if (MQTTclient_037 != NULL) {
if (!MQTTclient_037->connected() || MQTTclient_should_reconnect) {
if (MQTTclient_should_reconnect) {
addLog(LOG_LEVEL_ERROR, F("IMPT : MQTT 037 Intentional reconnect"));
}
if (!MQTTclient_037->connected() || MQTTclient_should_reconnect) {
if (MQTTclient_should_reconnect) {
addLog(LOG_LEVEL_ERROR, F("IMPT : MQTT 037 Intentional reconnect"));
MQTTclient_037->disconnect();
Plugin_037_update_connect_status();
delay(250);
if (! MQTTConnect_037()) {
success = false;
break;
}
MQTTSubscribe_037();
}
MQTTclient_037->disconnect();
Plugin_037_update_connect_status();
delay(250);
if (! MQTTConnect_037(ClientName)) {
success = false;
break;
}
MQTTSubscribe_037();
success = true;
}
success = true;
break;
}
@@ -260,6 +282,7 @@ boolean Plugin_037(byte function, struct EventStruct *event, String& string)
}
boolean MQTTSubscribe_037()
{
if (!MQTTclient_037_connected) return false;
// Subscribe to the topics requested by ALL calls to this plugin.
// We do this because if the connection to the broker is lost, we want to resubscribe for all instances.
@@ -283,7 +306,7 @@ boolean MQTTSubscribe_037()
if (subscribeTo.length() > 0)
{
parseSystemVariables(subscribeTo, false);
if (MQTTclient_037->subscribe(subscribeTo.c_str()))
if (MQTTclient_037 != NULL && MQTTclient_037->subscribe(subscribeTo.c_str()))
{
String log = F("IMPT : [");
LoadTaskSettings(y);
@@ -350,9 +373,11 @@ void mqttcallback_037(char* c_topic, byte* b_payload, unsigned int length)
// For some reason this seems to failduring the call in INIT- however it succeeds later during recovery
// It would be nice to understand this....
boolean MQTTConnect_037(String clientid)
boolean MQTTConnect_037()
{
boolean result = false;
if (MQTTclient_037 == NULL) return false;
String clientid = getClientName();
// @ToDo TD-er: Plugin allows for more than one MQTT controller, but we're now using only the first enabled one.
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController < 0) {
@@ -368,7 +393,7 @@ boolean MQTTConnect_037(String clientid)
return false; // Not connected, so no use in wasting time to connect to a host.
}
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(enabledMqttController, (byte*)&ControllerSettings, sizeof(ControllerSettings));
LoadControllerSettings(enabledMqttController, ControllerSettings);
if (ControllerSettings.UseDNS) {
MQTTclient_037->setServer(ControllerSettings.getHost().c_str(), ControllerSettings.Port);
} else {
+16 -12
View File
@@ -16,7 +16,7 @@
#define P044_STATUS_LED 12
#define P044_BUFFER_SIZE 1024
#define P044_NETBUF_SIZE 600
#define P044_NETBUF_SIZE 128
#define P044_DISABLED 0
#define P044_WAITING 1
#define P044_READING 2
@@ -31,7 +31,7 @@ boolean CRCcheck = false;
unsigned int currCRC = 0;
int checkI = 0;
WiFiServer *P1GatewayServer;
WiFiServer *P1GatewayServer = nullptr;
WiFiClient P1GatewayClient;
boolean Plugin_044(byte function, struct EventStruct *event, String& string)
@@ -125,7 +125,11 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
#if defined(ESP32)
Serial.begin(ExtraTaskSettings.TaskDevicePluginConfigLong[1], serialconfig);
#endif
if (P1GatewayServer) P1GatewayServer->close();
if (P1GatewayServer)
{
P1GatewayServer->close();
delete P1GatewayServer;
}
P1GatewayServer = new WiFiServer(ExtraTaskSettings.TaskDevicePluginConfigLong[0]);
P1GatewayServer->begin();
@@ -164,7 +168,7 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
{
if (P1GatewayServer) {
P1GatewayServer->close();
//FIXME: shouldnt P1P1GatewayServer be deleted?
delete P1GatewayServer;
P1GatewayServer = NULL;
}
success = true;
@@ -175,7 +179,6 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
{
if (Plugin_044_init)
{
size_t bytes_read;
if (P1GatewayServer->hasClient())
{
if (P1GatewayClient) P1GatewayClient.stop();
@@ -186,24 +189,25 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
if (P1GatewayClient.connected())
{
connectionState = 1;
uint8_t net_buf[P044_BUFFER_SIZE];
uint8_t net_buf[P044_NETBUF_SIZE];
int count = P1GatewayClient.available();
if (count > 0)
{
if (count > P044_BUFFER_SIZE)
count = P044_BUFFER_SIZE;
bytes_read = P1GatewayClient.read(net_buf, count);
Serial.write(net_buf, bytes_read);
size_t net_bytes_read;
if (count > P044_NETBUF_SIZE)
count = P044_NETBUF_SIZE;
net_bytes_read = P1GatewayClient.read(net_buf, count);
Serial.write(net_buf, net_bytes_read);
Serial.flush(); // Waits for the transmission of outgoing serial data to complete
if (count == P044_BUFFER_SIZE) // if we have a full buffer, drop the last position to stuff with string end marker
if (count == P044_NETBUF_SIZE) // if we have a full buffer, drop the last position to stuff with string end marker
{
count--;
// and log buffer full situation
addLog(LOG_LEVEL_ERROR, F("P1 : Error: network buffer full!"));
}
net_buf[count] = 0; // before logging as a char array, zero terminate the last position to be safe.
char log[P044_BUFFER_SIZE + 40];
char log[P044_NETBUF_SIZE + 40];
sprintf_P(log, PSTR("P1 : Error: N>: %s"), (char*)net_buf);
addLog(LOG_LEVEL_DEBUG, log);
}
+1
View File
@@ -458,6 +458,7 @@ void p073_FillBufferWithTemp(long temperature)
int p073_numlenght = strlen(p073_digit);
byte p073_dispdigit;
for (int i=0;i<p073_numlenght;i++) {
p073_dispdigit = 10; // default is space
if (p073_digit[i] > 47 && p073_digit[i] < 58)
p073_dispdigit = p073_digit[i]-48;
else if (p073_digit[i] == 32) // space
+84 -42
View File
@@ -3,10 +3,15 @@
//################################### Plugin 075: Nextion <info@sensorio.cz> ###########################
//################################### Created on the work of majklovec ###########################
//################################### Revisions by BertB and ThomasB ###########################
//################################### Last Revision: Aug-03-2018 (TB) ###########################
//################################### Last Revision: Oct-03-2018 (TB) ###########################
//#######################################################################################################
//
// Updated: Aug-03-2018, ThomasB.
// Updated: Oct-03-2018, ThomasB.
// Added DEBUG_LOG define to reduce info log messages and prevent serial log flooding.
// Added SendStatus() to post log message on browser to acknowledge HTTP write.
// Added reserve() to minimize string memory allocations.
//
// Aug-03-2018 change log summary:
// This updated Nextion Plugin introduces hardware (UART) serial as an alternative to SoftSerial.
// Hardware serial offers more reliable communication with the Nextion display.
// Created on the experimental Serial.swap() work of BertB.
@@ -19,6 +24,9 @@
// Defines start here
// *****************************************************************************************************
//#define DEBUG_LOG // Enable this to include additional info messages in log output.
// Plug-In defines
#define PLUGIN_075
#define PLUGIN_ID_075 75
@@ -241,7 +249,9 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
SoftSerial = NULL;
}
String log = F("NEXTION075 : serial pin config RX:");
String log;
log.reserve(80); // Prevent re-allocation
log = F("NEXTION075 : serial pin config RX:");
log += rxPin;
log += F(", TX:");
log += txPin;
@@ -313,6 +323,7 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
RssiIndex = UcTmpString.indexOf(F("RSSIBAR")); // RSSI bargraph Keyword found, wifi value in dBm.
if(RssiIndex >= 0) {
int barVal;
newString.reserve(Lenlines+10); // Prevent re-allocation
newString = tmpString.substring(0, RssiIndex);
int nbars = WiFi.RSSI();
if (nbars < -100 || nbars >= 0)
@@ -345,31 +356,38 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
}
sendCommand(newString.c_str(), HwSerial);
String log = F("NEXTION075 : Cmd Statement Line-");
log += String(x+1);
log += F(" Sent: ");
log += newString;
addLog(LOG_LEVEL_INFO, log);
#ifdef DEBUG_LOG
String log;
log.reserve(Lenlines+50); // Prevent re-allocation
log = F("NEXTION075 : Cmd Statement Line-");
log += String(x+1);
log += F(" Sent: ");
log += newString;
addLog(LOG_LEVEL_INFO, log);
#endif
}
}
// At Interval timer, send idx & value data only if user enabled "values" interval mode.
if(IncludeValues) {
/*
String log = F("NEXTION075: Interval values data enabled, resending idx=");
log += String(UserVar[event->BaseVarIndex]);
log += F(", value=");
log += String(UserVar[event->BaseVarIndex+1]);
addLog(LOG_LEVEL_INFO, log);
*/
#ifdef DEBUG_LOG
String log;
log.reserve(120); // Prevent re-allocation
log = F("NEXTION075: Interval values data enabled, resending idx=");
log += String(UserVar[event->BaseVarIndex]);
log += F(", value=");
log += String(UserVar[event->BaseVarIndex+1]);
addLog(LOG_LEVEL_INFO, log);
#endif
success = true;
}
else {
/*
String log = F("NEXTION075: Interval values data disabled, idx & value not resent");
addLog(LOG_LEVEL_INFO, log);
*/
#ifdef DEBUG_LOG
String log = F("NEXTION075: Interval values data disabled, idx & value not resent");
addLog(LOG_LEVEL_INFO, log);
#endif
success = false;
}
@@ -386,6 +404,8 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
// Enable addLog() code below to help debug plugin write problems.
/*
String log;
log.reserve(140); // Prevent re-allocation
String log = F("Nextion arg0: ");
log += tmpString;
log += F(", TaskDeviceName: ");
@@ -401,11 +421,14 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
tmpString = string.substring(argIndex + 1);
sendCommand(tmpString.c_str(), HwSerial);
String log = F("NEXTION075 : WRITE, ");
log += F("Command is ");
log += (tmpString.c_str());
addLog(LOG_LEVEL_INFO, log);
String log;
log.reserve(110); // Prevent re-allocation
log = F("NEXTION075 : WRITE = ");
log += tmpString;
#ifdef DEBUG_LOG
addLog(LOG_LEVEL_INFO, log);
#endif
SendStatus(event->Source, log); // Reply (echo) to sender. This will print message on browser.
success = true; // Set true only if plugin found a command to execute.
}
break;
@@ -439,7 +462,6 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
uint16_t i;
uint8_t c;
uint8_t charCount;
String log;
String Vidx;
String Nvalue;
String Svalue;
@@ -447,7 +469,7 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
char __buffer[RXBUFFSZ+1]; // Staging buffer.
if(rxPin < 0) {
String log = F("NEXTION075 : Missing RxD Pin Number, aborted serial receive");
String log = F("NEXTION075 : Missing RxD Pin, aborted serial receive");
addLog(LOG_LEVEL_INFO, log);
break;
}
@@ -455,6 +477,8 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
if(HwSerial == UARTSERIAL) {
charCount = Serial.available(); // Prime the Hardware Serial engine.
if(charCount >= RXBUFFWARN) { // ESP8266 has 128 byte circular Rx buffer.
String log;
log.reserve(70); // Prevent re-allocation
log = F("NEXTION075 : RxD UART Buffer capacity warning,");
log += String(charCount);
log += F(" bytes");
@@ -465,6 +489,8 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
if(SoftSerial == NULL) break; // SoftSerial missing, exit.
charCount = SoftSerial->available(); // Prime the Soft Serial engine.
if(charCount >= RXBUFFWARN) {
String log;
log.reserve(70); // Prevent re-allocation
log = F("NEXTION075 : RxD SoftSerial Buffer capacity warning, ");
log += String(charCount);
log += F(" bytes");
@@ -495,13 +521,17 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
UserVar[event->BaseVarIndex + 1] = __buffer[3];
sendData(event);
log = F("NEXTION075 : code: ");
log += __buffer[1];
log += ",";
log += __buffer[2];
log += ",";
log += __buffer[3];
addLog(LOG_LEVEL_INFO, log);
#ifdef DEBUG_LOG
String log;
log.reserve(70); // Prevent re-allocation
log = F("NEXTION075 : code: ");
log += __buffer[1];
log += ",";
log += __buffer[2];
log += ",";
log += __buffer[3];
addLog(LOG_LEVEL_INFO, log);
#endif
}
}
}
@@ -534,9 +564,14 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
__buffer[i] = 0x00;
String tmpString = __buffer;
log = F("NEXTION075 : code: ");
log += tmpString;
addLog(LOG_LEVEL_INFO, log);
#ifdef DEBUG_LOG
String log;
log.reserve(50); // Prevent re-allocation
log = F("NEXTION075 : Code = ");
log += tmpString;
addLog(LOG_LEVEL_INFO, log);
#endif
int argIndex = tmpString.indexOf(F(",i"));
int argEnd = tmpString.indexOf(',', argIndex + 1);
@@ -568,14 +603,21 @@ boolean Plugin_075(byte function, struct EventStruct *event, String& string)
UserVar[event->BaseVarIndex+1] = Svalue.toFloat();
sendData(event);
log = F("NEXTION075 : Pipe Command Sent: ");
log += __buffer;
log += UserVar[event->BaseVarIndex];
#ifdef DEBUG_LOG
String log;
log.reserve(80); // Prevent re-allocation
log = F("NEXTION075 : Pipe Command Sent: ");
log += __buffer;
log += UserVar[event->BaseVarIndex];
addLog(LOG_LEVEL_INFO, log);
#endif
}
else {
log = F("NEXTION075 : Unknown Pipe Command, skipped");
#ifdef DEBUG_LOG
String log = F("NEXTION075 : Unknown Pipe Command, skipped");
addLog(LOG_LEVEL_INFO, log);
#endif
}
addLog(LOG_LEVEL_INFO, log);
}
}
if(HwSerial == UARTSERIAL) charCount = Serial.available();
+31 -2
View File
@@ -206,10 +206,25 @@ To create/register a plugin, you have to :
#define USES_P036 // FrameOLED
#define USES_P027 // INA219
#define USES_P028 // BME280
// TODO : Add list of compatible plugins for ESP32 board.
#endif
#ifdef PLUGIN_SET_TEST_ESP32
#ifndef ESP32
#define ESP32
#endif
#ifdef ESP8266
#undef ESP8266
#endif
// #define PLUGIN_SET_ONLY_SWITCH
#define PLUGIN_SET_TESTING
#define CONTROLLER_SET_STABLE
#define NOTIFIER_SET_STABLE
#define PLUGIN_SET_STABLE // add stable
// See also PLUGIN_SET_TEST_ESP32 section at end,
// where incompatible plugins will be disabled.
// TODO : Check compatibility of plugins for ESP32 board.
#endif
// Generic ------------------------------------
@@ -585,8 +600,22 @@ To create/register a plugin, you have to :
#ifdef NOTIFIER_SET_EXPERIMENTAL
#endif
/******************************************************************************\
* Remove incompatible plugins ************************************************
\******************************************************************************/
#ifdef PLUGIN_SET_TEST_ESP32
#undef USES_P010 // BH1750 (doesn't work yet on ESP32)
#undef USES_P049 // MHZ19 (doesn't work yet on ESP32)
#undef USES_P052 // SenseAir (doesn't work yet on ESP32)
#undef USES_P053 // PMSx003
#undef USES_P056 // SDS011-Dust (doesn't work yet on ESP32)
#undef USES_P065 // DRF0299
#undef USES_P071 // Kamstrup401
#undef USES_P075 // Nextion
#undef USES_P078 // Eastron Modbus Energy meters (doesn't work yet on ESP32)
#endif
/******************************************************************************\