Compare commits

..
331 Commits
Author SHA1 Message Date
ESPEasy release bot 4208048fc1 automaticly updated release notes for mega-20180313 2018-03-13 04:00:11 +01:00
Unknown 06a2f47812 Merge branch 'v2.0' into mega 2018-03-12 23:20:59 +01:00
mvdbroandGitHub 18e612dea2 Merge pull request #1067 from uzi18/mega
- fix for #1065
2018-03-12 19:35:51 +01:00
mvdbro f99593ed62 ESP32 C010 fix 2018-03-12 19:34:40 +01:00
Bartlomiej Zimon 25b4392dd5 - remove double trimm() 2018-03-12 12:09:07 +01:00
Bartlomiej Zimon ad4130a547 - fix for #1065 2018-03-12 11:42:00 +01:00
ESPEasy release bot 991384822f automaticly updated release notes for mega-20180312 2018-03-12 04:00:07 +01:00
Unknown 82ed319e59 Merge branch 'v2.0' into mega 2018-03-12 00:46:31 +01:00
Gijs NoorlanderandGitHub 2e4af86a99 Merge pull request #1061 from TD-er/bugfix/chunking_webserver
[webserver] Improve chunked transfer
2018-03-12 00:42:30 +01:00
Gijs NoorlanderandGitHub b4791d3421 Merge pull request #1060 from TD-er/bugfix/selection_accesspoints
[issue #1039 ] Change CSS to show topmost SSID on large screens
2018-03-12 00:40:13 +01:00
Unknown 885c5394a3 [webserver] Improve chunked transfer
Do chunked transfer using full buffer on all data sent to the streaming webserver.
2018-03-12 00:34:51 +01:00
Unknown e35304e4e7 [issue #1039 ] Change CSS to show topmost SSID on large screens
For screens with > 960 pixels width.
To show all accesspoints on AP selection.
2018-03-12 00:32:46 +01:00
mvdbro 6561d577d4 Rule Engine minor fix and added dev debugging 2018-03-11 10:40:54 +01:00
ESPEasy release bot 02d8834763 automaticly updated release notes for mega-20180311 2018-03-11 04:00:06 +01:00
Gijs NoorlanderandGitHub e82080dc52 Merge pull request #1053 from letscontrolit/v2.0
V2.0
2018-03-11 02:07:27 +01:00
Gijs NoorlanderandGitHub cfbf972c1b [issue #1039] Topmost SSID are covered on mobile Browser (#1052)
[issue #1039] Topmost SSID are covered on mobile Browser
2018-03-11 01:58:13 +01:00
Unknown e25ea52edc [issue #1039] Topmost SSID are covered on mobile Browser
Added <span> tags with a class around the error, which allow the CSS to position the content below the header.
2018-03-11 01:57:24 +01:00
Gijs NoorlanderandGitHub 7d8e5e5175 [DNS lookup] Controllers sometimes try to connect to 0.0.0.0 (#1051)
[DNS lookup] Controllers sometimes try to connect to 0.0.0.0
2018-03-11 01:37:38 +01:00
Unknown 3d39dec686 [DNS lookup] Controllers sometimes try to connect to 0.0.0.0
See issue #824
2018-03-11 01:36:29 +01:00
Unknown ff656593ec Merge branch 'v2.0' into mega 2018-03-10 23:07:53 +01:00
Gijs NoorlanderandGitHub 90b4e3438d [OLED] fix drawProgressBar (#1048)
[OLED] fix drawProgressBar
2018-03-10 22:58:25 +01:00
Gijs NoorlanderandGitHub 139f8905d0 [deepsleep] Use the 'shortcut' of running all when sleep enabled (#1047)
[deepsleep] Use the 'shortcut' of running all when sleep enabled
2018-03-10 22:55:59 +01:00
Unknown 6c1806fae6 [OLED] fix drawProgressBar
See this PR: https://github.com/ThingPulse/esp8266-oled-ssd1306/pull/178
2018-03-10 22:53:18 +01:00
Unknown e6b581e7ff [deepsleep] Make sure the 'shortcut' of running all services when sleep enabled
As pointed out on [the forum by arion_p](https://www.letscontrolit.com/forum/viewtopic.php?p=25771#p25771)
2018-03-10 22:42:04 +01:00
Gijs NoorlanderandGitHub 873d639461 Update P073 Plugin - support extra versions of TM1637 modules (@Papperone) (#1043)
Update P073 Plugin - support extra versions of TM1637 modules  (@Papperone)
2018-03-10 21:58:14 +01:00
Gijs NoorlanderandGitHub edb2a6d3f6 [AM/PM] Am/Pm notation doesn't have '0' hours (#1044)
[AM/PM] Am/Pm notation doesn't have '0' hours
2018-03-10 21:56:42 +01:00
Unknown bff60a2e27 [P073] Remove tm1637_bitDelay()
Not used anymore
2018-03-10 21:28:09 +01:00
Unknown 61831e5962 [AM/PM] Am/Pm notation doesn't have '0' hours
11.59 a.m. => 12.00 p.m.
12.59 p.m. => 1.00 p.m.
11.59 p.m. => 12.00 a.m.
2018-03-10 21:19:35 +01:00
Unknown d105b47d44 Update P07 Plugin
added suppor for other version of TM1637 modules (4dgt+colon, 4dgt+dots,6dgt+dots)
2018-03-10 18:38:33 +01:00
mvdbro 449568bcc4 Final ruleset speed-up
It's now down from 100 mSec to 19 mSec for 1 fully loaded non matching ruleset.
2018-03-10 16:53:02 +01:00
mvdbro 3144077103 Add read buffer to rule processing to speedup parsing
On a full ruleset (2k), a non matching event takes 100 mSec instead of 170 mSec.
2018-03-10 15:48:56 +01:00
mvdbro 8f056be0a8 Rule Engine, stop waisting time on non matching rules 2018-03-10 10:48:03 +01:00
mvdbro e9cdc5693d Improve flash read performance 2018-03-10 08:51:35 +01:00
ESPEasy release bot 377c50ec36 automaticly updated release notes for mega-20180310 2018-03-10 04:00:07 +01:00
Gijs NoorlanderandGitHub 90a2a799da [Conversions] Use more decimals in conversions and add AM/PM for time. (#1036)
[Conversions] Use more decimals in conversions and add AM/PM for time.
2018-03-09 23:15:48 +01:00
Unknown feb419b6ae [Conversions] Use more decimals in conversions and add AM/PM for time.
See comments on #1015
2018-03-09 23:13:03 +01:00
Gijs NoorlanderandGitHub e83d8468b0 Move plugin init before WiFi init (#1035)
Move plugin init before WiFi init
2018-03-09 22:18:35 +01:00
Unknown 6eabaaa62d Move plugin init before WiFi init
As suggested at PR #1032 by @M0ebiu5
2018-03-09 22:10:25 +01:00
ESPEasy release bot b0169b4aa7 automaticly updated release notes for mega-20180309 2018-03-09 04:00:11 +01:00
Unknown 786ec4714a Merge branch 'v2.0' into mega 2018-03-09 00:37:47 +01:00
Gijs NoorlanderandGitHub 4d749b19fd [Rule Events] Add a number of events to handle in rules and awake timer (#1032)
[Rule Events] Add a number of events to handle in rules and awake timer
2018-03-08 22:55:19 +01:00
Unknown 6a66440a5f [Rule Events] Add a number of events to handle in rules and awake timer
Changed the sleep checkbox to allow a number of seconds awake from deep sleep.

Also added the following events:

- MQTT#Connected
- WiFi#Connected
- System#Initialized 
- Time#Set    Time set by an update from NTP.
- Time#Initialized  Time set for the first time since boot.
- Login#Failed

See #951
2018-03-08 21:43:52 +01:00
ESPEasy release bot 1b23efe48c automaticly updated release notes for mega-20180308 2018-03-08 04:00:08 +01:00
mvdbro 9a9d39763f Second step towards port monitoring without tasks 2018-03-07 16:17:40 +01:00
mvdbro 9f94ef073c First step towards port monitoring without tasks 2018-03-07 14:13:12 +01:00
ESPEasy release bot 000d2d7c77 automaticly updated release notes for mega-20180307 2018-03-07 04:00:09 +01:00
Gijs NoorlanderandGitHub c1b945e6c1 [issue #1012] Removed Content-Length header + improved webserver speed (#1027)
[issue #1012] Removed Content-Length header + improved webserver speed
2018-03-07 00:55:48 +01:00
Unknown dbbe6b65dd [issue #1012] Removed Content-Length header + improved webserver speed
See: Web interface doesn't work on iOS #1012

The operatore+= String function now chunks long strings
2018-03-07 00:54:23 +01:00
Gijs NoorlanderandGitHub 4611ef5d87 [CSS] Quick fix for smaller displays (#1026)
[CSS] Quick fix for smaller displays by @doxikus
2018-03-06 21:52:15 +01:00
Unknown 807cc1796d [CSS] Quick fix for smaller displays
Quick fix, created by @doxikus
2018-03-06 21:50:54 +01:00
ESPEasy release bot 82933ae170 automaticly updated release notes for mega-20180305 2018-03-05 04:00:08 +01:00
Unknown 503fd3555e Merge branch 'v2.0' into mega 2018-03-05 00:40:22 +01:00
Edwin Eefting f31cce4182 Merge branch 'v2.0' into mega 2018-03-04 18:14:58 +01:00
Edwin Eefting f36fada375 Merge branch 'v2.0' into mega 2018-03-04 18:12:07 +01:00
soifandDatuX d51bce97f5 fixes typos in the issue template (#1006) 2018-03-04 18:09:34 +01:00
soifandDatuX 0368aa4d43 Add OS specific hidden files (#1005) 2018-03-04 18:09:08 +01:00
mvdbro 3c4aa7564f ESP32 - 32 Tasks -redo commit 2018-03-04 17:34:08 +01:00
mvdbro f46b89f1bd Merge branch 'mega' of https://github.com/letscontrolit/ESPEasy into mega 2018-03-04 17:15:43 +01:00
mvdbro 4e2b78056a ESP32 - 32 Tasks
Full reset needed!
2018-03-04 17:14:35 +01:00
Gijs NoorlanderandGitHub d94ce17fd4 Merge pull request #1009 from TD-er/bugfix/factory_reset_twice
[Webserver] Factory Reset was present twice
2018-03-04 16:27:16 +01:00
Unknown cd2c59ba5b [Webserver] Factory Reset was present twice
See issue #1008
2018-03-04 16:26:07 +01:00
mvdbro b6a6943668 ESP32 fix-2 for P020/P044
This time it actually works.
2018-03-04 12:27:38 +01:00
ESPEasy release bot e1e894d540 automaticly updated release notes for mega-20180304 2018-03-04 04:00:08 +01:00
Unknown d15311e70a Merge branch 'v2.0' into mega 2018-03-04 00:50:43 +01:00
Gijs NoorlanderandGitHub eef8391ffc _P072_HDC1080 allow to send values to the controllers (#999)
_P072_HDC1080 add success and break statement.
it seems that without the break statement and success set to true, the values aren't sent back to the controller(s).
2018-03-03 21:29:12 +01:00
Gijs NoorlanderandGitHub d47751c31f Fixes P073 plugin for latest TM1637 based 7 segments displays modules (#996)
Fixes P073 plugin for latest TM1637 based 7 segments displays modules
2018-03-03 20:40:11 +01:00
Gijs NoorlanderandGitHub b048d3f1f8 Merge pull request #1000 from uzi18/test3 (more comparisions in IF condition)
support for more comparisions in IF condition: >=,<=,!=,<>,<,>,= also fix extended conditions when first check is not '>'
2018-03-03 20:37:07 +01:00
Bartlomiej Zimon f94ab3a04a - support for more comparisions in IF conditions: >=,<=,!=,<>,<,>,=
also fix extended conditions when first check is not >
2018-03-03 16:04:44 +01:00
mvdbro 1b9375f83b ESP32 Dallas DS18B20 fix
This is a quick fix for this sensor only. It seems that ESP32 RTOS needs more or differtent interrupt handling for time critical sensor code.
2018-03-03 14:08:20 +01:00
clumsy-stefanandGitHub a77798d18f add success and break statement
it seems that without the break statement and success set to true, the values aren ot sent back to the controller(s).
2018-03-03 13:05:25 +01:00
ESPEasy release bot ec4dd09968 automaticly updated release notes for mega-20180303 2018-03-03 04:00:08 +01:00
Unknown d68a5fb9d4 Merge branch 'v2.0' into mega 2018-03-03 02:23:03 +01:00
Unknown 635c149f12 Merge branch 'v2.0' into mega 2018-03-02 22:16:37 +01:00
soif 57e256a5fa Fixes P073 plugin for latest TM1637 based 7 segments displays modules 2018-03-02 21:06:45 +01:00
Gijs NoorlanderandGitHub 7d16ffa4a4 revert json to non-chunking #988 from s0170071/mega
revert json to non-chunking
2018-03-02 20:36:42 +01:00
s0170071 856e370ba0 make handle_json return void 2018-03-02 15:00:48 +01:00
s0170071 4df9e7d065 Add git build and local time 2018-03-02 13:58:05 +01:00
s0170071 edb3857e04 revert json to non-chunking 2018-03-02 13:17:20 +01:00
ESPEasy release bot fb1cc219ee automaticly updated release notes for mega-20180302 2018-03-02 04:00:10 +01:00
Unknown da7329891d Merge branch 'v2.0' into mega 2018-03-02 02:08:55 +01:00
Unknown 7f897bc856 Merge branch 'v2.0' into mega
Merge initiated from GitKraken directly on Letscontrol_it/ESPEasy
2018-03-01 23:31:00 +01:00
Gijs NoorlanderandGitHub 0092ba92b5 Merge pull request #983 from kahvm/mega
Added support for degree sign on LCD1602/2004
2018-03-01 22:41:54 +01:00
kahvmandGitHub 7a4e3d954d Merge pull request #1 from kahvm/support-degree-sign-lcd1602
Support for degree sign on LCD1602
2018-03-01 22:00:41 +01:00
kahvmandGitHub 9dc4fefa0b Support for degree sign on LCD1602
More: https://www.letscontrolit.com/forum/viewtopic.php?p=11875#p11875
2018-03-01 20:09:50 +01:00
mvdbro 695bb58d64 Rule wildcard option on literal events
Added wildcard rule filter on literal string events
Changed "sendcontent free"content logging level to 'DEV'
2018-03-01 14:29:10 +01:00
Bartlomiej Zimon 608a7212eb Merge branch 'mega' of github.com:letscontrolit/ESPEasy into test3 2018-03-01 03:02:23 +01:00
ESPEasy release bot 4e2a5d3b3d automaticly updated release notes for mega-20180228 2018-02-28 04:00:09 +01:00
Edwin Eefting a4dcc304a9 Merge branch 'v2.0' into mega 2018-02-27 23:43:36 +01:00
Bartłomiej ZimońandDatuX f0fc20de57 fix #964, add timeStringToSeconds and use it to compare time conditions (#965)
* - pcfgpio,port,2 sets pin as input
- fix for #222,#702 - we can mix inputs and outputs now

* - extend conditions with AND/OR, now it is possible to simplify rules

test rules:
on test do
  if [test#a]=0 or [test#b]=0 or [test#c]=0
    event ok
  else
    event nok
  endif
endon

on test2 do
  if [test#a]=1 and [test#b]=1 and [test#c]=1
    event ok
  else
    event nok
  endif
endon

on test3 do
  if [test#a]=1 and [test#b]=1 or [test#c]=0
    event ok
  else
    event nok
  endif
endon

on test4 do
  if [test#a]=0
    event ok
  else
    event nok
  endif
endon

* - remove Serial print

* - add format #O to templates to show OFF/ON instead 0/1 - eg.: Pump:[Outputs#pump#O]

* - add formating for active low outputs eg.: #O!

* - fix #964, add timeStringToSeconds and use it to compare time conditions

* - fix number of pages available to browse
2018-02-27 23:42:20 +01:00
ESPEasy release bot 537d4cd1e9 automaticly updated release notes for mega-20180227 2018-02-27 04:00:11 +01:00
Edwin Eefting 62422f4924 Merge branch 'v2.0' into mega 2018-02-27 00:42:15 +01:00
Gijs NoorlanderandDatuX 076ce0127b [build conflict] Renamed ESP32 version of ping (#963)
Had a conflict with the ESP8266 version of ping.
Let's hope I did not break anything with the ESP32 builds @mvdbro does.
2018-02-27 00:10:17 +01:00
Edwin Eefting 226c0a6f83 Merge branch 'v2.0' into mega 2018-02-26 23:03:48 +01:00
s0170071andDatuX 6ffa8d92a6 Add Factory Reset button to web interface (#954) 2018-02-26 22:54:24 +01:00
Bartłomiej ZimońandDatuX dae2cc2f4a add format #O to templates to show OFF/ON instead 0/1 (#949)
* - pcfgpio,port,2 sets pin as input
- fix for #222,#702 - we can mix inputs and outputs now

* - extend conditions with AND/OR, now it is possible to simplify rules

test rules:
on test do
  if [test#a]=0 or [test#b]=0 or [test#c]=0
    event ok
  else
    event nok
  endif
endon

on test2 do
  if [test#a]=1 and [test#b]=1 and [test#c]=1
    event ok
  else
    event nok
  endif
endon

on test3 do
  if [test#a]=1 and [test#b]=1 or [test#c]=0
    event ok
  else
    event nok
  endif
endon

on test4 do
  if [test#a]=0
    event ok
  else
    event nok
  endif
endon

* - remove Serial print

* - add format #O to templates to show OFF/ON instead 0/1 - eg.: Pump:[Outputs#pump#O]

* - add formating for active low outputs eg.: #O!
2018-02-26 22:53:15 +01:00
mvdbro d277d22914 Fix ESP32 compile errors 2018-02-26 14:26:17 +01:00
ESPEasy release bot cbdddf8c06 automaticly updated release notes for mega-20180226 2018-02-26 04:00:08 +01:00
Gijs NoorlanderandGitHub 8b5d22a081 Merge pull request #948 from TD-er/build/remove_duplicate_library
[softwareSerial] Remove duplicate with only capilization as difference
2018-02-25 21:29:09 +01:00
Unknown 88fc0a8445 [softwareSerial] Remove duplicate with only capilization as difference 2018-02-25 21:27:57 +01:00
Gijs NoorlanderandGitHub ec9187d038 Merge pull request #947 from letscontrolit/v2.0
V2.0 => Mega: Ping library and Webserver@LowMemory
2018-02-25 21:20:37 +01:00
Edwin Eefting 99cc6f72af Merge branch 'v2.0' into mega 2018-02-25 17:18:59 +01:00
Edwin Eefting 3527b69718 Merge branch 'v2.0' into mega 2018-02-25 16:57:03 +01:00
Gijs NoorlanderandDatuX 72ff745eff [Mega] rename SoftwareSerial lib #930 (#937)
Just a rename of the library directory + some notes in the library description to indicate the differences.
2018-02-25 14:12:59 +01:00
Michael SchröderandDatuX dd9db3b557 Added Vcc-binaries to deploy process (#933) 2018-02-25 14:11:25 +01:00
Bartłomiej ZimońandDatuX 9c531b30bc - extend conditions with AND/OR, now it is possible to simplify rules (#932)
* - pcfgpio,port,2 sets pin as input
- fix for #222,#702 - we can mix inputs and outputs now

* - extend conditions with AND/OR, now it is possible to simplify rules

test rules:
on test do
  if [test#a]=0 or [test#b]=0 or [test#c]=0
    event ok
  else
    event nok
  endif
endon

on test2 do
  if [test#a]=1 and [test#b]=1 and [test#c]=1
    event ok
  else
    event nok
  endif
endon

on test3 do
  if [test#a]=1 and [test#b]=1 or [test#c]=0
    event ok
  else
    event nok
  endif
endon

on test4 do
  if [test#a]=0
    event ok
  else
    event nok
  endif
endon

* - remove Serial print
2018-02-25 14:04:55 +01:00
Edwin Eefting cd30b81202 Merge branch '2kwebservermergetomega' of https://github.com/s0170071/ESPEasy into mega 2018-02-25 13:55:28 +01:00
s0170071andDatuX 550881faa5 Memtracker (#927)
* preparations for lwip2

* Add CRC32 to settings

* Add CRC to progmem

* Add crc of program memory to stettings and security settings

.. so that there is a warning if the settings are used by another binary than they were written with.

* Moved to md5

* Flash included, moved to MD5 now

* Broken comment

* Stability improvements

free memory went as low as 3000 bytes which made the webserver unresponsive.

* Add binary filename to crc2.py and sysinfo

* Update WebServer.ino

* Memory tracker

displays debug memory trace

WD   : Uptime 3 ConnectFailures 0 FreeMem 15304
Memtrace
0: lowest: 4456  PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 handle_hardware-> 15192 sendWebPage-> 9672 sendWebPageChunkedData-> 5816 sendWebPageChunkedData-> 5128 sendWebPageChunkedData-> 4456 sendWebPageChunkedData-> 4456 
1: lowest: 4456  PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 handle_hardware-> 15192 sendWebPage-> 9672 sendWebPageChunkedData-> 5816 sendWebPageChunkedData-> 5128 sendWebPageChunkedData-> 4456 
2: lowest: 3768  PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 PluginCall_s (35)-> 15328 handle_hardware-> 15192 sendWebPage-> 9672 sendWebPageChunkedData-> 5816 sendWebPageChunkedData-> 5128 sendWebPageChunkedData-> 4456 sendWebPageChunkedData-> 4456 sendWebPageChunkedData-> 3768 
WD   : Uptime 4 ConnectFailures 0 FreeMem 15304

* Update Misc.ino
2018-02-25 13:14:57 +01:00
s0170071 ed45945f21 Fix compile error when SD card is enabled 2018-02-24 18:03:38 +01:00
s0170071 f13abe8922 Removed double entry on info page 2018-02-24 17:32:44 +01:00
s0170071 34b0a683a9 fix travis 2018-02-24 17:10:52 +01:00
s0170071 9ab10437b5 Merge remote-tracking branch 's0170071/2kwebservermergetomega' into 2kwebservermergetomega 2018-02-24 16:59:54 +01:00
s0170071 b0b7408522 variable timeout 2018-02-24 16:59:46 +01:00
s0170071 b104942db9 Merge remote-tracking branch 's0170071/2kwebservermergetomega' into 2kwebservermergetomega 2018-02-24 16:57:17 +01:00
s0170071 a694b658b1 Merge remote-tracking branch 's0170071/2kwebservermergetomega' into 2kwebservermergetomega 2018-02-24 16:57:07 +01:00
s0170071 cb07a0d342 Merge remote-tracking branch 's0170071/2kwebservermergetomega' into 2kwebservermergetomega 2018-02-24 16:54:06 +01:00
s0170071 1ceaad04ec Merge branch '2kws_dynpayload' into 2kwebservermergetomega 2018-02-24 16:53:56 +01:00
s0170071 5cbf0c1e38 Merge branch '2kws_dynpayload' into 2kwebservermergetomega 2018-02-24 16:48:14 +01:00
Bartlomiej Zimon 4951f294b9 - remove Serial print 2018-02-24 16:34:30 +01:00
s0170071 ef0ef092f0 Merge remote-tracking branch 's0170071/2kws_dynpayload' into 2kws_dynpayload 2018-02-24 16:24:44 +01:00
s0170071ands0170071 46d3ae6a2b Merge branch 'mega' into 2kwebservermergetomega 2018-02-24 16:24:32 +01:00
Bartlomiej Zimon ef1bf646ab Merge branch 'mega' of github.com:letscontrolit/ESPEasy into mega 2018-02-24 10:32:09 +01:00
Bartlomiej Zimon f72a48ffc2 - extend conditions with AND/OR, now it is possible to simplify rules
test rules:
on test do
  if [test#a]=0 or [test#b]=0 or [test#c]=0
    event ok
  else
    event nok
  endif
endon

on test2 do
  if [test#a]=1 and [test#b]=1 and [test#c]=1
    event ok
  else
    event nok
  endif
endon

on test3 do
  if [test#a]=1 and [test#b]=1 or [test#c]=0
    event ok
  else
    event nok
  endif
endon

on test4 do
  if [test#a]=0
    event ok
  else
    event nok
  endif
endon
2018-02-24 10:19:12 +01:00
ESPEasy release bot da54ddda78 automaticly updated release notes for mega-20180224 2018-02-24 04:00:06 +01:00
mvdbro c24205713d ESP32 fixed P020 and P044 2018-02-23 15:21:48 +01:00
s0170071andGitHub 52d4cb804e Merge branch 'mega' into 2kwebservermergetomega 2018-02-23 15:07:18 +01:00
mvdbro ae077de72b Fix ESP32 compile errors 2018-02-23 14:38:14 +01:00
s0170071 86fa5ec6ae Merge into mega
... and removed obsolete function
2018-02-23 14:07:46 +01:00
s0170071 41c9d68422 Merge remote-tracking branch 'origin/mega' into 2kwebservermergetomega 2018-02-23 14:00:19 +01:00
ESPEasy release bot e713da5d79 automaticly updated release notes for mega-20180223 2018-02-23 04:00:07 +01:00
GHolliandDatuX edc261ca2b * BugFix: According to the data sheet, the offset for the detection range values (command byte 0x99) is 3..4 instead of 6..7 (#921)
Reference: http://www.winsen-sensor.com/d/files/infrared-gas-sensor/mh-z19b-co2-ver1_0.pdf
* Optimisation of the code
  - Using an enumeration for the commands to send
  - Removing redundancy of the commands stored in flash
  - Creating a function for the checksum calculation
2018-02-22 19:11:35 +01:00
s0170071andDatuX 8f4a52a6f1 Include name of binary file in crc2.py and sysinfo (#918)
* preparations for lwip2

* Add CRC32 to settings

* Add CRC to progmem

* Add crc of program memory to stettings and security settings

.. so that there is a warning if the settings are used by another binary than they were written with.

* Moved to md5

* Flash included, moved to MD5 now

* Broken comment

* Stability improvements

free memory went as low as 3000 bytes which made the webserver unresponsive.

* Add binary filename to crc2.py and sysinfo

* Update WebServer.ino
2018-02-22 18:55:45 +01:00
ESPEasy release bot c04b80b2f1 automaticly updated release notes for mega-20180221 2018-02-21 04:00:09 +01:00
Edwin Eefting cdbc2498c1 [test suite] corrected PUYA test. added erase/build/flash for all chips. preparations for full automatic hardware regression testing 2018-02-21 02:44:57 +01:00
Edwin Eefting 78997b4329 Merge branch 'v2.0' into mega 2018-02-21 02:11:18 +01:00
GHolliandDatuX 790a946cf6 Optimisation: Save RAM (freeing RAM by moving static data from RAM to program memory). (#910) 2018-02-21 00:02:59 +01:00
Stanislav MihicandDatuX 69c5be6489 Frontend (#906)
* Updating template structure, adding viewport meta name for mobile devices, feature ready for responsive layout

* Adding meta viewport, feature ready nad support for mobile devices, responsive layout, update template structure, adding article html5 tag, easier to style interface, find/replace uppercase to lowercase, matter of elegance and preference code readability :-)

* revert to default state and change only template related lines

* final check, revert uppercase

* Last template changes, lost in undo process :-)

* h6 footer TR
2018-02-20 23:54:46 +01:00
ESPEasy release bot 3de400fc91 automaticly updated release notes for mega-20180220 2018-02-20 04:00:08 +01:00
Edwin Eefting 6fae1f79d8 function was moved to StringConverter.inp 2018-02-20 01:20:57 +01:00
Edwin Eefting 1222e04caf Merge branch 'v2.0' into mega 2018-02-20 01:08:29 +01:00
Bartłomiej ZimońandDatuX f38973aad6 - pcfgpio,port,2 sets pin as input (#897)
- fix for #222,#702 - we can mix inputs and outputs now
2018-02-20 00:57:55 +01:00
ESPEasy release bot 3032463917 automaticly updated release notes for mega-20180219 2018-02-19 04:00:09 +01:00
Bartlomiej Zimon f5e84a155e - pcfgpio,port,2 sets pin as input
- fix for #222,#702 - we can mix inputs and outputs now
2018-02-19 01:38:52 +01:00
Edwin Eefting bbb97bfc7e Merge branch 'v2.0' into mega 2018-02-18 19:23:09 +01:00
Gijs NoorlanderandDatuX e747756dd2 [Build Mega] Fix for Build Mega 20180217 (#889) 2018-02-18 13:17:02 +01:00
s0170071 6df5840db9 Fixed String redeclaration 2018-02-17 09:45:40 +01:00
s0170071 5f79e4b922 Merge Webserver 2018-02-17 09:43:46 +01:00
s0170071 e058507b9a Merge remote-tracking branch 'origin/mega' into 2kRamWebserver 2018-02-17 09:26:32 +01:00
ESPEasy release bot 5c4defdf6e automaticly updated release notes for mega-20180217 2018-02-17 04:00:07 +01:00
Edwin Eefting e58ea2a3fe Merge branch 'v2.0' into mega 2018-02-16 21:43:23 +01:00
Bartłomiej ZimońandDatuX 2b7a61469f provide System@Sleep event (#875)
- provide System@Sleep event
- fixes #870 (mqtt not sent before sleep)
- call deepsleep at the end of loop - so we know all is done
2018-02-16 21:28:52 +01:00
s0170071andGitHub 75f1c6c140 Update .gitignore 2018-02-14 20:56:44 +01:00
ESPEasy release bot e3cd057ad8 automaticly updated release notes for mega-20180214 2018-02-14 04:00:10 +01:00
Edwin Eefting fec069ba00 Merge branch 'v2.0' into mega 2018-02-14 03:27:15 +01:00
Bartłomiej ZimońandDatuX b2db97e808 fix for Blynk Controller (#863)
* fix for Blynk Controller

- use of real controller index
- we use idx
- check if password not empty
- use real password
- use proper port

* Update _C012.ino

add SENSOR_TYPE_SWITCH support
2018-02-14 00:23:38 +01:00
s0170071 4e537461f2 Fix travis
unsigned int -> int comparison
2018-02-13 21:59:18 +01:00
s0170071 dc7bb12581 4->12 Devices per page
that was easy :-)
2018-02-13 21:53:04 +01:00
s0170071andGitHub 0c80cdc119 Merge branch 'mega' into 2kRamWebserver 2018-02-13 21:36:05 +01:00
s0170071 37210031b7 Cleanup and +1k Ram
- on 2.4.0 git /low mem LWIP ram goes never below 20k, during TX core dives down to 18,7k (each main menu clicked once, plain new config.)
- Fixed json output
- cleanup of send function#
- un-split css, transfer to buffer byte by byte (prevents 1.7k temporary string)
- removed commented-out function
2018-02-13 21:28:10 +01:00
ESPEasy release bot d7134e6b87 automaticly updated release notes for mega-20180213 2018-02-13 04:00:09 +01:00
Edwin Eefting 8dc1924059 Merge branch 'v2.0' into mega 2018-02-13 03:16:06 +01:00
Edwin Eefting a7b77b6008 make blynk stuff compile again 2018-02-13 03:11:09 +01:00
Edwin Eefting 649305a2dd Merge branch 'v2.0' into mega 2018-02-13 01:43:11 +01:00
Henri de JongandDatuX 2371b0f315 Added support for pioneer ir signals (#844) 2018-02-13 01:14:44 +01:00
Gijs NoorlanderandDatuX 59b7768722 Blynk controler (re-implementation of PR#92) (#837)
* Blynk controler (re-implementation of PR#92)

See #92
This plugin is just ported from the old implementation, which was not merged into the Mega branch.
It now is using a lot of the newly created functions and optimizations.
But not yet tested.

* Update _C012.ino
2018-02-13 00:32:02 +01:00
s0170071 baa1df620f Travis... 2018-02-12 16:55:24 +01:00
s0170071 a310811919 fix Travis
uninitialized variable.
2018-02-12 13:46:36 +01:00
s0170071 e9dd5da690 Add Ram usage debug message
usually shows: 
Ram usage: Webserver only: 1048 including Core: 3120
2018-02-12 11:48:01 +01:00
s0170071 f9c25489d1 fix download page
don't stream this one.
2018-02-12 09:26:00 +01:00
s0170071 46ee928b07 navMenuIndex
fixed order. Needs to be set before stream starts.
2018-02-12 08:11:15 +01:00
s0170071 3af102f2ad Unused variable 2018-02-12 07:07:12 +01:00
s0170071 ca53ec0263 fix travis
unused variable
2018-02-12 06:48:46 +01:00
s0170071 5ca7c073f1 fix travis 2018-02-12 06:34:19 +01:00
ESPEasy release bot b320c2a1e2 automaticly updated release notes for mega-20180212 2018-02-12 04:00:09 +01:00
s0170071 3f68154819 Merge branch 'webserverminmem' into mega 2018-02-11 22:24:17 +01:00
s0170071 7b1c4483bb Merge remote-tracking branch 's0170071/webserverminmem' into webserverminmem 2018-02-11 22:23:50 +01:00
s0170071 572d9c0714 2k Webserver 2018-02-11 22:23:38 +01:00
mvdbro b85010006b Fix compile errors on ESP32 2018-02-11 14:46:08 +01:00
s0170071 48643cf87e Merge remote-tracking branch 's0170071/webserverminmem' into webserverminmem 2018-02-09 12:28:17 +01:00
s0170071 9ea594afeb Optimized memory usage
memory never goes below 10k now. 
Added wait for memory return on header send, 
Added wait for memory return on chunk end send,
removed duplicate of data stashing with  getWebPageTemplateVar
2018-02-09 12:27:45 +01:00
ESPEasy release bot 749c8cd931 automaticly updated release notes for mega-20180209 2018-02-09 04:00:15 +01:00
s0170071 49a783c381 "Content-Type","text/html" 2018-02-08 20:11:07 +01:00
s0170071 c9b81f7ab9 Wait for memory be like before send chunked
goes not below 9680 bytes now
2018-02-08 19:57:16 +01:00
AndreyandDatuX eb2dbb5b90 Added HIGH-Z state options for GPIO command (#833)
Add command like 'GPIO,12,2' for set pin to HIGH-Z (INPUT) state.
2018-02-08 19:37:52 +01:00
s0170071 91c6e3af61 Does Travis like extern "C" ? 2018-02-08 17:31:26 +01:00
s0170071 faeb921bcf Merge remote-tracking branch 's0170071/webserverminmem' into webserverminmem 2018-02-08 17:13:01 +01:00
s0170071 9928f56ad3 try fix travis 2018-02-08 17:12:53 +01:00
s0170071andGitHub 61d27084c1 trigger travis re-compile
trigger travis re-compile to see if the compile failure was due to a quick re-submission.
2018-02-08 10:04:07 +01:00
s0170071 e5393a9fa4 Adapted timeout 2018-02-07 22:08:43 +01:00
s0170071 1cbc49021a tcp_cleanup for LWIP1 & 2 2018-02-07 22:04:39 +01:00
s0170071 84f389b44e Timeout 100ms 2018-02-07 17:29:16 +01:00
s0170071 765775e22f Adjusted to min 7k free 2018-02-07 17:21:28 +01:00
s0170071 02c97c4513 Webserver min memory
memory went as low as 3k, so wait for it to return ...
2018-02-07 17:15:23 +01:00
ESPEasy release bot d87cd7eafe automaticly updated release notes for mega-20180206 2018-02-06 05:00:10 +01:00
Edwin Eefting 58bb62cc1a Merge branch 'v2.0' into mega 2018-02-06 01:08:36 +01:00
s0170071andDatuX 201d013230 Add compile time (#811) 2018-02-05 23:49:26 +01:00
ESPEasy release bot 9a77b1727c automaticly updated release notes for mega-20180203 2018-02-03 05:00:11 +01:00
GrovkillenandGitHub f0d35527df Update README.md
Made the "warning" stand out a bit more.
2018-02-02 12:50:58 +01:00
ESPEasy release bot 9cbaa4d7e7 automaticly updated release notes for mega-20180202 2018-02-02 05:00:12 +01:00
Edwin Eefting af4ad9fbcb Merge branch 'v2.0' into mega 2018-02-02 03:17:01 +01:00
Edwin Eefting 8bdfa656de Add CRC checks to all binaries when building a release with travis. fixes #779 2018-02-02 02:27:23 +01:00
Edwin Eefting 952bf68b93 Merge branch 'v2.0' into mega 2018-02-02 01:37:35 +01:00
DatuXandGitHub 13f73c0156 Update README.md 2018-02-02 01:15:34 +01:00
Gijs NoorlanderandDatuX b32212b061 [Mega] Fix pointer arithmetic on void pointers for CRC computations (#795)
It was a change I made last week to get it to compile for the 2.4.0 core lib, but made an error in the pointer arithmetic.
No it shoud be correct.
See https://github.com/letscontrolit/ESPEasy/issues/792#issuecomment-361714575
2018-02-02 00:28:58 +01:00
ESPEasy release bot cae3baf71e automaticly updated release notes for mega-20180130 2018-01-30 05:00:12 +01:00
Edwin Eefting 27db33f1bd Merge branch 'v2.0' into mega 2018-01-30 01:54:10 +01:00
Edwin Eefting b96e12f217 Merge branch 'v2.0' into mega 2018-01-29 22:52:14 +01:00
Edwin Eefting ad8e229c06 Merge branch 'v2.0' into mega 2018-01-29 20:52:56 +01:00
ESPEasy release bot 0ec7085022 automaticly updated release notes for mega-20180126 2018-01-26 05:00:12 +01:00
Edwin Eefting 913cd67eee Merge branch 'v2.0' into mega 2018-01-25 22:15:57 +01:00
Gijs NoorlanderandDatuX 2586b94e28 [Mega] Force 2.3.0 for all builds and add an option for 2.4.0 core (#775)
* [Mega] Force 2.3.0 for all builds and add an option for 2.4.0 core

This way we can test issues easier and people are still using 2.3.0 core version.

* Update platformio.ini

Environment labels should not use dots. Then they will not show in the build selection box.
2018-01-25 22:06:45 +01:00
josemariaaraujoandDatuX b811b13483 Update _C007.ino (#774)
This change allows to send the switch state to Emoncms, previously it was ignored
2018-01-25 15:49:31 +01:00
Gijs NoorlanderandDatuX c149888bed [Mega] Allow compile with 2.4.0 core library (#772)
Last few days, lots of issues reported by users who installed the 2.4.0 core libraries.
e.g. #769 and #763
It appeared the default PlatformIO Espressif 8266 1.6.0 libs now include the 2.4.0 core libraries.
Now I have to find a way to get my own environment back to the 2.3.0 core libs and see how I can get PlatformIO Espressif 8266 library back to version 1.5.0
2018-01-25 15:47:58 +01:00
ESPEasy release bot 8aea298854 automaticly updated release notes for mega-20180124 2018-01-24 05:00:09 +01:00
Edwin Eefting 5617fbe0a0 Merge branch 'mega' of github.com:letscontrolit/ESPEasy into mega 2018-01-24 03:17:32 +01:00
Edwin Eefting 6a643da8ee Merge branch 'v2.0' into mega 2018-01-24 03:17:20 +01:00
s0170071andDatuX ee568a76c1 Space (#767)
* preparations for lwip2

* Add CRC32 to settings

* Add CRC to progmem

* Add crc of program memory to stettings and security settings

.. so that there is a warning if the settings are used by another binary than they were written with.

* Moved to md5

* Flash included, moved to MD5 now

* Broken comment
2018-01-23 23:55:55 +01:00
s0170071andDatuX beaf077b06 Broken comment (#766)
* preparations for lwip2

* Add CRC32 to settings

* Add CRC to progmem

* Add crc of program memory to stettings and security settings

.. so that there is a warning if the settings are used by another binary than they were written with.

* Moved to md5

* Flash included, moved to MD5 now

* Broken comment
2018-01-23 23:55:29 +01:00
ESPEasy release bot e36a9f163e automaticly updated release notes for mega-20180123 2018-01-23 05:00:10 +01:00
Edwin Eefting 17f0f6637a Merge branch 'v2.0' into mega 2018-01-23 04:58:52 +01:00
Edwin Eefting 0ec770fc51 Merge branch 'v2.0' into mega 2018-01-23 02:43:07 +01:00
Edwin Eefting 9da5f465d1 Merge branch 'v2.0' into mega 2018-01-23 01:02:12 +01:00
s0170071andDatuX 5230a4fe4f CRC on settings and security settings and progmem (#720)
* preparations for lwip2

* Add CRC32 to settings

* Add CRC to progmem

* Add crc of program memory to stettings and security settings

.. so that there is a warning if the settings are used by another binary than they were written with.

* Moved to md5

* Flash included, moved to MD5 now
2018-01-22 23:58:43 +01:00
Edwin Eefting b236887718 Merge branch 'v2.0' into mega 2018-01-22 23:54:55 +01:00
Edwin Eefting cbca4c3efa Merge branch 'v2.0' into mega 2018-01-22 23:35:45 +01:00
ESPEasy release bot a67f92176f automaticly updated release notes for mega-20180122 2018-01-22 05:00:08 +01:00
Edwin Eefting 3922827fad Merged v2.0 changes and fixed some regressions 2018-01-22 01:43:42 +01:00
ESPEasy release bot 4b298d6e31 automaticly updated release notes for mega-20180119 2018-01-19 05:00:07 +01:00
jctualandDatuX c0c65364e5 DHT plugin update (#736)
Modification of DHT plugin to use Sonoff am2301 and si7021 sensors.
Also correct some NAN readings.
2018-01-19 02:43:22 +01:00
Edwin Eefting 5f89698308 Merge branch 'v2.0' into mega 2018-01-19 01:30:40 +01:00
ESPEasy release bot 5821377b6c automaticly updated release notes for mega-20180118 2018-01-18 05:00:08 +01:00
Edwin Eefting a6ea35ef9c Merge branch 'v2.0' into mega 2018-01-18 02:15:01 +01:00
Edwin Eefting fe9a579dc3 added fixme 2018-01-18 02:03:54 +01:00
ESPEasy release bot ed7f597b3d automaticly updated release notes for mega-20180117 2018-01-17 05:00:08 +01:00
Edwin Eefting 6700030d7c Merge branch 'mega' of github.com:letscontrolit/ESPEasy into mega 2018-01-17 00:16:09 +01:00
Edwin Eefting f45c7650de fix #719 (initial ds18b20 value after power on 85 degrees) 2018-01-17 00:15:59 +01:00
papperoneandDatuX a36ee65865 merge with main branch (#648)
* removed note for 74HC595

74HC595 pin reminder not needed as this chip won't be supported anymore

* deleted GPIO notes referring to 75HC595 not supported
2018-01-16 20:20:52 +01:00
ESPEasy release bot dfb5b8a4c5 automaticly updated release notes for mega-20180116 2018-01-16 05:00:11 +01:00
Edwin Eefting 9d3dd49e9d Merge branch 'v2.0' into mega 2018-01-16 00:20:12 +01:00
ESPEasy release bot 0833029c82 automaticly updated release notes for mega-20180114 2018-01-14 05:00:08 +01:00
s0170071andDatuX 71cf207bf7 preparations for lwip2 (#707) 2018-01-13 12:22:32 +01:00
ESPEasy release bot 3d3a035822 automaticly updated release notes for mega-20180113 2018-01-13 05:00:10 +01:00
Edwin Eefting af3bf5217d fix version number 2018-01-13 03:07:38 +01:00
Edwin Eefting 11f47f26e6 Merge branch 'v2.0' into mega 2018-01-13 03:04:33 +01:00
Edwin Eefting f7b37306aa automaticly updated release notes for mega-20180112 2018-01-12 02:05:49 +01:00
Edwin Eefting 8b3d8f6ad4 Merge branch 'v2.0' into mega 2018-01-12 02:03:58 +01:00
Edwin Eefting b5cad22afd Merge branch 'v2.0' into mega 2018-01-12 01:41:13 +01:00
Edwin Eefting 407dae03ca merged v2.0 changes 2018-01-11 23:00:15 +01:00
ESPEasy release bot c17e683834 automaticly updated release notes for mega-20180111 2018-01-11 05:00:08 +01:00
Edwin Eefting 311abeabd0 Merge branch 'v2.0' into mega 2018-01-11 03:27:25 +01:00
Edwin Eefting 04f27e0d03 Merge branch 'v2.0' into mega 2018-01-11 00:52:36 +01:00
Edwin Eefting fc5103de8d oops...somehow git did made some changes :( 2018-01-10 22:34:36 +01:00
Edwin Eefting 14b6345277 no changes, just merge the v2.0 branch 2018-01-10 22:22:29 +01:00
Gijs NoorlanderandDatuX 9a70037e32 Merge/v2.0 dev13 to mega (#695)
* [switch] Fixed switch behavior and default settings. (#675)

As described in #673 .
The problem was partly related to the default values stored in flash ("0"), which was not a valid value for the switch type.

When upgrading from an older version of ESPeasy, make sure to check the switch type (normal switch or dimmer) and save the settings for the switch device again, even when nothing was changed.
Default configuration and new added switches will now work like intended.

When a controller is enabled (e.g. Domoticz MQTT or -HTTP) and the button is pressed multiple times, the ESP may reboot. See issue #674.

* ABC calibration feature added (#606)

* [Flash info] Detailed flash information (#678)

Last few days a number of issues and forum topic was about the type of flash used on the ESP boards.

This is an extension of the detailed information page.

Perhaps also merge with the newer and more clear layout of pull request #624?
That pull request was only merged to the mega branch.
I kept the changes local, but perhaps they should be placed in the "Storage" section introduced with #624.
Maybe also that pull request should get merged into the v2.0 branch.

* Bugfix/v2.0 crash switch (#682)

* [crashes] Added constructors to initialize all members in structs

Numerous structs are defined, but none of them have default constructors and there is no guarantee the members will be set when used. 
With these default constructors, the parameters at least have an initialized value.

* [PubSubClient] Add bound checks on the internal buffer

Not sure if this was really causing an issue, but proper bound checks are always a good thing.

* [Crash Switch] Disabled delayBackground and added yield() calls

Something really fishy is going on with the delayBackground function, which will result in crashes when pressing the switch multiple times, with Domoticz MQTT enabled as first controller.
Disabled for now and delay(1) added to give background tasks a chance to do their work and make sure the watchdog doesn't perform a reset.

* [CI build errors] Commented out some unused variables

Travis considers them as error and fails the checks.

* [CI check] Out-of-bounds check fix

* actually ignore MQTT messages that are too big.

* moved mqtt stuff outside of backgroundtasks(). fixes #683 in my test scenario

* [Adafruit MPR121] Change deprecated name setThreshholds to setThresholds (#685)

See #684

* fixed plugin id of "Communication - Kamstrup Multical 401". (accidental octal notation)

* changed devicecombobox handling to save a lot of memory on device page. fixes #654 #676 and could be triggered by #683 in some cases.

* [CPPcheck] v2.0 ControllerSettingsStruct some variables not initialized (#692)

Fixing these cppcheck errors:
101.43s$ cppcheck --enable=warning src/*.ino -q --force -I src --include=src/ESPEasy.ino --error-exitcode=1
[src/ESPEasy.ino:500]: (warning) Member variable 'ControllerSettingsStruct::HostName' is not initialized in the constructor.
[src/ESPEasy.ino:500]: (warning) Member variable 'ControllerSettingsStruct::Publish' is not initialized in the constructor.
[src/ESPEasy.ino:500]: (warning) Member variable 'ControllerSettingsStruct::Subscribe' is not initialized in the constructor.
2018-01-10 21:51:42 +01:00
GrovkillenandGitHub 8ce1aa0092 Update README.md
Re-arranged the date format to = the current code standard.
2018-01-10 16:01:27 +01:00
ESPEasy release bot d2e2522c07 automaticly updated release notes for mega-20180104 2018-01-04 03:13:01 +00:00
ESPEasy release bot 4a212302e0 changed date format of nightly builds 2018-01-03 14:51:40 +00:00
ESPEasy release bot 993dd7ade3 automaticly updated release notes for mega-01032018 2018-01-03 04:00:06 +00:00
Edwin Eefting d544fc84e8 changed readme to reflect mega branch and automated builds 2018-01-03 01:04:18 +01:00
Edwin Eefting e6dba4456c Merge branch 'v2.0' into mega 2018-01-03 00:52:03 +01:00
Edwin Eefting d2777a9b15 updated travis link to reflect v2.0 2018-01-03 00:50:49 +01:00
Edwin Eefting c7d12bb798 Merge branch 'v2.0' into mega 2018-01-03 00:48:13 +01:00
ESPEasy release bot ef912a4484 automaticly updated release notes for mega-01022018 2018-01-02 23:32:50 +00:00
ESPEasy release bot b4debd9559 created releasebot script 2018-01-02 23:30:53 +00:00
Edwin Eefting d7277649dd merged v2.0 branch. disabled memory checker (takes too long, perhaps enable it via a commit keyword?) 2018-01-03 00:28:22 +01:00
Edwin Eefting 33ec7e5240 Merge branch 'v2.0' into mega 2018-01-02 12:49:55 +01:00
Gijs NoorlanderandDatuX d62b692b3b [SDS011] Allow the sensor to sleep to extend sensor lifetime (#668)
* [SDS011] Add send commands to sensor

In the library used to communicate to the SDS011 sensor was only support to receive data from the sensor and not query the sensor or set another mode.
This is needed for #499 , to let the sensor sleep.

N.B. code is not yet tested, only implemented while reading the datasheet "Laser Dust Sensor Control Protocol V1.3"

* [SDS011] Lessen load on ESP by polling less frequent and use SoftSerial

The default setting were to set the delay to 0 and use an own software serial implementation.
This caused frequent timeouts on the web interface, WiFi reconnects, etc.
Now the already present SoftSerial is being used. This will gather all the data from the serial port and thus there is no need to poll 50 times a second.
Now the ESP is much more responsive.

* [SDS011] Allow the sensor to sleep to extend sensor lifetime

The internal laser of the SDS011 only will last for about 1 year when ran continuously.
When the RX of the sensor is connected, it can be set to sleep for N minutes between measurements. This will extend the lifetime of the sensor and reduce power consumption.
This sleep time is stored inside the flash of the sensor, so it can be set once and then the RX on the sensor could be disconnected again to be used for other purposes.
2018-01-02 12:22:57 +01:00
paulv888andDatuX 493bfd56b9 usesID = true (#666)
fixes #646
2018-01-02 11:41:01 +01:00
krikkandDatuX abbfa24ca6 added support for the TSL2591 Sensor based on Adafruit Library (#661)
* initial support for TSL2591 sensor

* return lux, visible, ir and full light separately

* better plugin init

* check sensor initialization before reading it..

* incorporated a few pending fixes for the adafruit library

* minor typo
2017-12-31 15:35:44 +01:00
Gijs NoorlanderandDatuX fae1edc859 [Security] Add IP-based filtering to web interface and http-commands. (#653)
* [mega] Detect client IP for SysInfo page and some cleanup

Added formatIP functions for readability and add client IP to SystemInfo page as preparation to detect origin just to get an idea of possibilities for #647.
Also added some reserve() statements to Strings to prevent heap fragmentation.

* [mega] Cleanup formatIP calls

* [security] #647 Add IP filtering to web interface and commands

As discussed in #647:
In the Config tab, a "Client IP filtering" section is added.
This allows for 3 levels of IP filtering:
* "Allow All" - does not imply any filtering based on IP address of the client.
* "Allow Local Subnet" - Allow only clients from within the local subnet, based on IP and subnetmask of the ESP.
* "Allow IP range" - Allow only clients within a range of IP-addresses.

Settings like these are very likely to lock out the rightful owner, so there are also two commands added, which can be sent via the serial connection.
* accessinfo
* clearaccessblock

The first one just displays the current active IP filtering.
The "clearaccessblock" command will temporarily disable the access filtering. This allows the user to login and reset the access filtering.

"Allow Local Subnet" is set as factory default.
Only when first loading a new firmware with this feature and existing configuration, the "All Allowed" is active (the old default)
2017-12-31 15:31:20 +01:00
s0170071andDatuX a9a741f775 fix chunking (#649)
* change chunking 

so that manual chunking is only done with core 2.3.0. 2.4.0rc2 and later do chunking web transfer implicitly

* Update WebServer.ino
2017-12-28 20:16:03 +01:00
Edwin Eefting c0d482e4fc merged v2.0 fixes 2017-12-28 19:01:16 +01:00
Bartłomiej ZimońandDatuX b5cabdc775 Update _C002.ino (#645)
related to #636
2017-12-18 23:14:11 +01:00
Gijs NoorlanderandDatuX c71a43c3a6 Reduce iRAM usage for plugins using SoftwareSerial (#631)
* [addLib] Added SoftwareSerial library

Added latest version from: https://github.com/plerup/espsoftwareserial

* [renLib] Renamed files to avoid conflicts with existing code

* [renLib] Changed include according to rename

* [renLib] Renamed all occurences and includes and removed unused pins

Renamed to make sure all plugins use the 'new' ESPeasySoftwareSerial.
Also added pinToIndex function to reduce memory footprint with about 150 Bytes, as described in issue #630

* [unused pins] Adjust indices in object list

Forgot to change the indices in the object list of SoftwareSerial

* Simple patch for timeouts

As mentioned in this issue: https://github.com/plerup/espsoftwareserial/issues/54

* [SoftSerial] Set ObjList static

Set the object list static to share all SoftwareSerial iRAM used as described in #630

* [revertLib] Revert to old version lib, since new version uses more iram

Just to test with old version, originally available in 2.3.0 library, to see if memory usage improves.

* [test] Reduce number of ports to 1 and lower buffer size to 18 for MHZ19

Just as a test, to see what happens to the iRAM usage, lower the number of concurrent softserial ports to 1.
Also the default buffer size = 64 Bytes. The MH-Z19 sensor can do with less, since a response will be up to 9 bytes, a 18-byte buffer allows for 2 messages to be stored.

* Enable usage of up to 10 concurrent softserial and reduce variable sizes

Re-enable use of up to 10 concurrent software serials.
Also reduce the variable sizes to smaller ranges. (e.g. uint8 instead of int)

* [test] Limit number of concurrent software serial devices

Earlier tests show the amount of iRAM used is somewhat related to the maximum number of allowed software serial ports.
In this test it is set to 3 and they are assigned through first come first served a slot.
2017-12-18 22:02:53 +01:00
Edwin Eefting cd01283ac6 Merge branch 'v2.0' into mega 2017-12-18 21:26:06 +01:00
M0ebiu5andDatuX 7ce1077bd6 P022_PCA9685 added change frequency - P038_NeoPixel added RGBW strips (SK6812) (#638)
* added change frequency

* rgbw test

* PCA9685 change frequency

* Cleanup RGBW implementation

* Added instructions
2017-12-18 21:18:39 +01:00
DaMandDatuX f9701d1c7b [Domoticz HTTP] Compatibility fix for BMP280 (#636) 2017-12-18 21:13:34 +01:00
GrovkillenandDatuX e764830113 Updated "/pinstates" page: Made the plugin number column display "P001" instead of "1" and "P012" instead of "12". 2017-12-18 21:11:00 +01:00
GHolliandDatuX 9646457b50 Cosmetics: fixing typos. (#628)
* Optimisation: save RAM.

* Another RAM optimisation (freeing RAM by moving static data from RAM to program memory).

* Fixing user-visible typos.

* Fixing typos in variables and comments.

* Fixing typos in comments.

* Revert changes of other pull request.
2017-12-08 14:18:24 +01:00
GrovkillenandDatuX 7346e55e0d Updated ESPTOOLS.exe from 0.4.6 to 0.4.12 (#627)
* Add files via upload

* Add files via upload

* Updated ESPTOOLS.exe from 0.4.6 to 0.4.12

See releases here: https://github.com/igrr/esptool-ck/releases
2017-12-08 13:57:04 +01:00
fensoftandDatuX ae38a8cb4f added #define FEATURE_SD (permit a flash size reduction of ~10k) (#568) 2017-12-08 13:56:13 +01:00
Sen HaerensandDatuX df46a4a5fc Enhanced system info layout (#624)
* Enhance sysinfo page layout

* Added hex notation for chip IDs

* Fixed comment
2017-12-08 13:48:17 +01:00
GrovkillenandDatuX 7c6797a141 Move "TTP229 keypad" and "Encoder" plugin from "testing" to "normal" (#619)
* Add files via upload

* Add files via upload
2017-12-04 21:58:25 +01:00
mvdbro 83abac8c5e Fix #599 2017-12-03 15:13:29 +01:00
s0170071andDatuX 5ba6b2f335 split IP addrress (#605)
The system variable %ip% truncates the last octet or so when printed on small displays. Now there are four new variables %ip1%, %ip2%... so that the octet printout can be distibuted across two lines.
2017-11-23 19:04:59 +01:00
Edwin Eefting 0d4ba7c6f1 testing for ds18b20 2017-11-22 03:35:29 +01:00
Edwin Eefting a1fc351183 fix #588. parseTemplate() now only checks enabled taskes for [] macros 2017-11-22 03:33:34 +01:00
GrovkillenandDatuX 33a6c39fc4 Changed bin file names to be more descriptive. (#597)
* Changed bin file names to be more descriptive.

* Fixed TRAVIS check
2017-11-21 23:40:19 +01:00
papperoneandDatuX f853f6ef25 deleted GPIO notes referring to 75HC595 not supported (#591) 2017-11-20 22:52:01 +01:00
Edwin Eefting 7a2d114360 fix illegal string manipulations in PLUGIN_WRITE for some plugins. fixes #347 and #460 2017-11-16 03:01:14 +01:00
Edwin Eefting 0157f387ee Merge branch 'v2.0' into mega 2017-11-16 02:02:22 +01:00
sakinitandDatuX c23be231e1 Fix p1 wifi gateway module (#587)
* Fix receiving illegal characters using Domoticz

* Update P1GatewayServer life-cycle
2017-11-16 00:24:34 +01:00
Gijs NoorlanderandDatuX 00f5c36919 [P039 Thermocouple] Handling negative values and proper error logging (#586)
Cppcheck warned for 'suspicious code':
[src\_P039_Thermocouple.ino:254]: (warning) Suspicious code: sign conversion of -1 in calculation because '-1' has a negative value

I agree with cppcheck that the code is at least suspicious and probably compiler dependent.
So in order to let cppcheck no longer output a warning and make it a bit more readable, I made this change.

Also added logs to indicate errors reported by the sensor.
2017-11-16 00:05:23 +01:00
Edwin Eefting c960175ec1 set lcd to NULL by default. #584 2017-11-15 23:57:01 +01:00
Gijs NoorlanderandDatuX e456604436 [LCD plugin] Added check of LCD object before dereferencing it (#584)
Possible fix for #581.
Just looking at the description of the problem, this may be causing the crashes,since the commands may be trying to dereference the LCD pointer while it still is NULL.
2017-11-15 23:55:29 +01:00
GrovkillenandDatuX ac4657e77f Added categories... (#552) 2017-11-14 21:28:53 +01:00
papperoneandDatuX 3817427e79 Update _P073_7DGT.ino (#553) 2017-11-13 00:49:28 +01:00
Edwin Eefting 0200b3c63e fix travis build errors. disable cpp checking for now 2017-11-13 00:26:21 +01:00
Edwin Eefting 972a1a5703 Merge branch 'mega' of github.com:letscontrolit/ESPEasy into mega 2017-11-12 23:10:27 +01:00
mvdbro 73c22176b8 ESP32 fixed chunked HTTP transfer 2017-11-05 09:19:26 +01:00
mvdbro 4db036f350 ESP32 fix UDP instability 2017-11-04 17:15:24 +01:00
mvdbro 52223f0a20 ESP32 Enabled OTA 2017-11-04 10:38:14 +01:00
mvdbro 907ad0faf6 ESP32 fix FreeRAM reporting 2017-10-29 14:34:46 +01:00
mvdbro 887e10c947 ESP32 Rules/ADC/PWM 2017-10-28 16:07:00 +02:00
mvdbro b4c463e452 ESP32 IRAM/Deepsleep 2017-10-27 17:04:45 +02:00
mvdbro 66ba9b1f46 First preparations for ESP32 2017-10-25 16:10:16 +02:00
Edwin Eefting 7db50811ba esptest stuff 2017-10-23 20:44:23 +02:00
Edwin Eefting 17d20705ff smooth out testing code 2017-10-23 00:44:00 +02:00
Edwin Eefting e3bd782a42 test fixes 2017-10-22 23:20:07 +02:00
Edwin Eefting b073379fff fixed bug in oled upstream lib 2017-10-16 17:29:26 +02:00
Edwin Eefting b89d8ff946 fix warnings 2017-10-16 17:19:48 +02:00
Gijs NoorlanderandDatuX 22ad971c8e Support both SSD1306 and SH1106 OLED in OLED_Framed plugin (#509)
* [SSD1306] Upgrade library to version 3.0

The library at https://github.com/squix78/esp8266-oled-ssd1306 has to be initialized differently in version 3.0

Known issue: The font for 3 lines is not working, so temporary used the same font as for 4 ilnes. The online font generator is currently unavailable at http://oleddisplay.squix.ch/

* OLED framed improve header footer

The header now has better visible WiFi bars indicator and alternates the device name and the connected WiFi SSID.

The bottom part now only shows dots for the pages with visible data instead of the maximum number of pages possible.

* [SSD1306] Upgrade library to version 3.2.7

Forgot to commit deletion of obsolete files in previous commit.

* [SSD1306] Added 12pt font for version 3.x of the library

The font generator is online again: http://oleddisplay.squix.ch/#/home 
Added Dialog Plain 12 font for the 3-line display mode.

* [OLED_Framed] Allow to use either SSD1306 or SH1106

The new OLED library  allows to use SH1106 and SSD1306 controler.
Added support for both with an selector to select the available controler.

* [OLED_Framed] Only destruct and construct display object when changed

* [OLED Framed] Add contrast setting to display

Both SSD1306 and SH1106 support setting the contrast.

* Update _P036_FrameOLED.ino
2017-10-16 16:55:22 +02:00
Edwin Eefting ab06cc3703 merged v2.0 fix for MHZ19 (was already fixed in a different way) 2017-10-16 01:54:37 +02:00
Edwin Eefting 8a5cc5f2bd fix plugin id (starting with a 0 makes it octal in c++ :( ) 2017-10-16 01:47:57 +02:00
papperoneandDatuX 6919baf23c Plugin 073 - 7-segment display plugin TM1637/MAX7219 2017-10-16 01:44:56 +02:00
Gijs NoorlanderandDatuX ddedb215c4 [MH-Z19] Allow for B-version and add filtering (#525)
* [MH-Z19] Allow for B-version and add filtering

The "B" version of the sensor does not output an S value, but does internally apply a dynamic response filter on the samples based on the amount of fluctiation in the data.
The implemented filter does something similar for the "A" version and for both adds the option for an extra delay filter to smooth the data.

Default filter setting ("off") is the old behavior, where only stable values are allowed.

* [MH-Z19] Improve label texts and logging

The first commit for the filtering had some confusing text labels.
Also it would be nice to see the effect of filtering in the logs.
2017-10-16 01:36:43 +02:00
Tomasz TorczandDatuX 08d4d817f6 retain MQTT LWT messages (#516)
Retaining will messages allows monitoring agent to receive full info about clients state.
Without retaining, the monitoring agent will only be informed about events (connect/connection lost) happening during agent's connection to broker. Any reconnect would cause monitoring agent to lose state.
2017-10-16 01:18:45 +02:00
Edwin Eefting e8bdcfbaf2 keep TASKS_PER_PAGE at default value of 4 2017-10-16 01:16:55 +02:00
Edwin Eefting 743fb4494e improvement: Configurable number of tasks for "Devices" page #510
(by hexenmeister)
2017-10-16 01:15:34 +02:00
MichaelandDatuX 0a4bc7fad6 src/Hardware.ino: make it possible to use GPIO-0 (D3) as Pin_sd_cs (#508) 2017-10-16 01:04:12 +02:00
MichaelandDatuX 49d0b16324 WebServer.ino: enhance handle_SDfilelist() (#507) 2017-10-16 01:03:42 +02:00
Gijs NoorlanderandDatuX de479d6188 [SSD1306] Feature/oled 1306 library upgrade (#501)
* [SSD1306] Upgrade library to version 3.0

The library at https://github.com/squix78/esp8266-oled-ssd1306 has to be initialized differently in version 3.0

Known issue: The font for 3 lines is not working, so temporary used the same font as for 4 ilnes. The online font generator is currently unavailable at http://oleddisplay.squix.ch/

* OLED framed improve header footer

The header now has better visible WiFi bars indicator and alternates the device name and the connected WiFi SSID.

The bottom part now only shows dots for the pages with visible data instead of the maximum number of pages possible.

* [SSD1306] Upgrade library to version 3.2.7

Forgot to commit deletion of obsolete files in previous commit.

* [SSD1306] Added 12pt font for version 3.x of the library

The font generator is online again: http://oleddisplay.squix.ch/#/home 
Added Dialog Plain 12 font for the 3-line display mode.
2017-10-16 01:00:30 +02:00
Gijs NoorlanderandDatuX 3fd3e13dc7 OLED framed improve header footer (#495)
The header now has better visible WiFi bars indicator and alternates the device name and the connected WiFi SSID.

The bottom part now only shows dots for the pages with visible data instead of the maximum number of pages possible.
2017-10-16 00:55:25 +02:00
BadWolf42andDatuX d7d913d439 Dallas Plugin enhanced : no more "delay()" (#488)
* Enhanced Dallas pooling to avoid use of delay(800)

DS_readTemp has been split in 2: DS_convertTemp and DS_readonlyTemp.
DS_convertTemp is first called after DS_setResolution.
Then DS_convertTemp is called after temp has been read.
DS_readTemp has been kept for compatibility.
The only downside is that you read the temperature of previous query (value set by Timer/TDT option).

* typo

* Moved to Environment + code cleaning

- Moved Plugin from Temperature to Environment
- Modified Plugin_004_DS_crc8 to check CRC8, not return it
- Renamed Plugin_004_DS_convertTemp to Plugin_004_DS_startConvertion and removed useless vars in it
- Removed unneed braces and empty lines
- Added comments
2017-10-16 00:51:05 +02:00
SightofSilenceandDatuX 5c4ae3820b Add System Variable for day, month and year / Fix for "Calculate" function to recognize minus-sign (#485)
* Add files via upload

* Update Misc.ino

* Add files via upload
2017-10-16 00:47:58 +02:00
Gijs NoorlanderandDatuX 38774a20c6 Single function for format to user defined number decimals (#482)
* Single function for format to user defined number decimals

In a number of files the same long definition was cut and paste a lot to format  values to a user defined number of decimals.

Now a new simple function is added to Misc to perform this formatting, which results in more clean code, less prone to errors and a reduction in use of resources.

* Single function for format to user defined number decimals

In a number of files the same long definition was cut and paste a lot to format  values to a user defined number of decimals.

Now a new simple function is added to Misc to perform this formatting, which results in more clean code, less prone to errors and a reduction in use of resources.
2017-10-16 00:42:14 +02:00
Gijs NoorlanderandDatuX 9fc58bb4df P028 to support both BME280 and BMP280 to reduce resource usage (#481)
* P028 now supports both BME280 and BMP280

Both plugins P028 and P030 had a lot of code duplication. This takes up resources and is hard to maintain.
Now the P028 plugin can detect and use both sensors so P030 may be removed.

Only caveat is that the BMP280 does not measure humidity and thus actually is a 2-value sensor. The Domotics MQTT controller did not distinguish between them, but other controllers may do so.
When needed, the P030 plugin can still be a mere stub for the output and plugin definition and still share all code with P028.

* [BME280] Add temperature offset and improve read stability

The BME280/BMP280 may heat up internally if read too often and too long.
Also when built in a small container along with other sensors and the ESP, the sensor may read values which are too high.
To compensate for these higher readings, a constant offset may be applied in the device parameters.
This value is a signed integer value representing the offset in 1/10th degree Celsius.

Since the humidity is a relative value, depending on the temperature, this should be adjusted also.

Only this computed dew point temperature is also too high, due to the fact the sensor is warmer than the air and thus the perceived humidity is off.
To correct for this, half the offset temperature is being used to compute the dew point temperature.

The other improvement is the routine to read the sensor.

Using this routine, the sensor is only active for about 1.6 seconds each minute.
This prevents the sensor to heat up from its own readings and also allows stable readings using some filtering. (slamming a door does not affect the readings)

* [BMx280] Auto detect connected chip ID and show in Device config tab

Detect connected chip (BME280/BMP280) automatically and show detected device immediately in the Device config page next to the I2C address selection.

* [BME/BMP280] Perform reset at init

Just to make the reading a bit more stable when the sensor stops responding.
This is also done in the "official" Bosch github: https://github.com/BoschSensortec/BME280_driver

* [BMx280] Allow for more than one sensor 

As suggested in #491 for another sensor, its I2Caddress was handled incorrectly. The same applied to this plugin.
2017-10-16 00:27:04 +02:00
SloMustiandDatuX ca936ca42f implemewnted web activity timer tracker (#462) 2017-10-16 00:23:05 +02:00
Edwin Eefting 840fb6b647 Merge branch 'v2.0' into mega 2017-10-16 00:16:25 +02:00
denisfrenchandDatuX c80b5d6d78 Set MQTT clientid to %sysname% +/- Settings.Unit (#431) (#436) 2017-10-16 00:12:09 +02:00
hatzlhofferandDatuX 40067c514f added new display size 128x32 (#545)
added font size optimization
2017-10-16 00:06:59 +02:00
Alexander Schulz 139ae36d3e improvement: Configurable number of tasks for "Devices" page (TASKS_P…
…ER_PAGE)
2017-09-16 23:24:15 +02:00
88 changed files with 7161 additions and 2926 deletions
+3 -1
View File
@@ -26,6 +26,8 @@ Also there are more people on the forum that can help you with support.
* Incomplete or unstable plugins should have a PLUGIN_BUILD_DEV #ifdef around them. Also add [DEVELOPMENT] to the name.
* New plugins that seem to be working correctly should have a PLUGIN_BUILD_TESTING around until they are tested enough.
* Do not modify any of the variables passed to your PLUGIN_WRITE handler.
* New plugins that seem to be working correctly should have a PLUGIN_BUILD_TESTING around until they are tested enough. Also add [TESTING] to the name
* Also see our general guidelines at: https://www.letscontrolit.com/wiki/index.php/ESPEasyDevelopmentGuidelines
+1 -1
View File
@@ -3,7 +3,7 @@
### Steps to reproduce
How can we trigger this problem?
Does the problem presist after powering off and on? (just resetting isnt enough sometimes)
Does the problem persists after powering off and on? (just resetting isn't enough sometimes)
### Expected behavior
Tell us what should happen?
+11
View File
@@ -1,7 +1,18 @@
## OS Specific Hidden Files ####
# MacOSX Finder *****
.DS_Store
# Fuse FileSystem ***
.fuse_hidden*
## PlatformIO ##################
.pioenvs
.clang_complete
.gcc-flags.json
.piolibdeps
## Project #####################
lib/readme.txt
src/Custom.h
+1 -1
View File
@@ -25,7 +25,7 @@ install:
- pip install -U platformio
script:
- cppcheck --enable=warning src/*.ino -q --force -I src --include=src/ESPEasy.ino --error-exitcode=1
# - cppcheck --enable=warning src/*.ino -q --force -I src --include=src/ESPEasy.ino --error-exitcode=1
# - ./memanalyzer.py ~/.platformio/packages/toolchain-xtensa/bin/xtensa-lx106-elf-objdump
- PLATFORMIO_BUILD_FLAGS="-D CONTINUOUS_INTEGRATION" platformio run
+18 -26
View File
@@ -1,44 +1,36 @@
# ESPEasy (v2.0 stable branch)
# ESPEasy (development branch)
Build status: [![Build Status](https://travis-ci.org/letscontrolit/ESPEasy.svg?branch=v2.0)](https://travis-ci.org/letscontrolit/ESPEasy)
Build status: [![Build Status](https://travis-ci.org/letscontrolit/ESPEasy.svg?branch=mega)](https://travis-ci.org/letscontrolit/ESPEasy)
Introduction and wiki: https://www.letscontrolit.com/wiki/index.php/ESPEasy#Introduction
**v2.0**
:warning:This is the stable branch for the next upcoming ESPeasy release (2.0.0).:warning:
**MEGA**
:warning:This is the development branch of ESPEasy. All new untested features go into this branch. If you want to do a bugfix, do it on the stable branch, we will merge the fix to the development branch as well.:warning:
If you're living on the edge and want the latest features and bugs, go to the development branch: https://github.com/letscontrolit/ESPEasy/tree/mega
If you're a developer: Bug fixes go into this v2.0 branch, we will merge them back to the development branch.
Next stable branch: https://github.com/letscontrolit/ESPEasy/tree/v2.0 (bug fixes only, since oct 2017))
Check here to learn how to use this branch and help us improving ESPEasy: http://www.letscontrolit.com/wiki/index.php/ESPEasy#Source_code_development
## Versions
* v2.0-YYYYMMDD: These are the nightly builds. Once a day this is automaticly released whenever there are new changes. (this replaces the manual v2.0-devX release system)
* v2.0.0-betaX: as soon as we THINK everything is fixed, we start beta testing.
* v2.0.0-rcX: release candidates (almost stable)
* v2.0.0: This will be the first stable release. After this we will use more standard numbering. Next bugfix release will probably be 2.0.1.
## Automated binary releases
## Firmware binary releases
Every night our build-bot will build a new binary release: https://github.com/letscontrolit/ESPEasy/releases
Binary development releases are here: https://github.com/letscontrolit/ESPEasy/releases
The releases are named something like 'mega-20180102' (last number is the build date)
Depending on your needs, we release different types of files.
This uses version v2.0-20181001 as an example.
Depending on your needs, we release different types of files:
Firmware name | Hardware | Included plugins |
----------------------------------------------|-------------------------|-----------------------------|
ESPEasy_v2.0-20181001_normal_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable |
ESPEasy_v2.0-20181001_test_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable + Test |
ESPEasy_v2.0-20181001_dev_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable + Test + Development |
ESPEasy_v2.0-20181001_normal_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable |
ESPEasy_v2.0-20181001_test_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable + Test |
ESPEasy_v2.0-20181001_dev_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable + Test + Development |
ESPEasy_v2.0-20181001_normal_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable |
ESPEasy_v2.0-20181001_test_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable + Test |
ESPEasy_v2.0-20181001_dev_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable + Test + Development |
ESPEasy_mega-20180102_normal_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable |
ESPEasy_mega-20180102_test_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable + Test |
ESPEasy_mega-20180102_dev_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable + Test + Development |
ESPEasy_mega-20180102_normal_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable |
ESPEasy_mega-20180102_test_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable + Test |
ESPEasy_mega-20180102_dev_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable + Test + Development |
ESPEasy_mega-20180102_normal_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable |
ESPEasy_mega-20180102_test_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable + Test |
ESPEasy_mega-20180102_dev_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable + Test + Development |
## More info
+1 -1
View File
@@ -10,7 +10,6 @@ for ENV in \
normal_ESP8266_1024 \
normal_ESP8266_4096 \
normal_ESP8285_1024 \
normal_ESP8266_1024_DOUT \
test_ESP8266_1024\
test_ESP8266_4096\
test_ESP8266_4096_VCC\
@@ -24,6 +23,7 @@ do
echo
echo "### Deploying environment $ENV for version $VERSION"
BIN=.pioenvs/$ENV/firmware.bin
python2 crc2.py $BIN
cp $BIN dist/"ESP_Easy_$VERSION""_$ENV.bin"
done
+116
View File
@@ -0,0 +1,116 @@
import sys
import binascii
import struct
import md5
import os
MD5DUMMY = "MD5_MD5_MD5_MD5_BoundariesOfTheSegmentsGoHere..." #48 chars
FILENAMEDUMMY = "ThisIsTheDummyPlaceHolderForTheBinaryFilename..." #48 chars
MemorySegmentStart,MemorySegmentEnd,MemoryContent=[],[],[]
##################################################################
# this subroutine shows the segments of a part
##################################################################
def showSegments (fileContent,offset):
global MemorySegmentStart, MemorySegmentEnd, MemoryContent
header = struct.unpack("ii", fileContent[offset:offset+8])
herestr =""
herestr2 =""
MemorySegmentStart.append(struct.pack("I",header[0]))
MemorySegmentEnd.append(struct.pack("I",header[0]+header[1]))
MemoryContent.append(fileContent[offset+8:offset+8+header[1]])
if fileContent.find( MD5DUMMY, offset+8, offset+8+header[1]) >0 :
herestr= " <-- CRC is here."
if fileContent.find( FILENAMEDUMMY, offset+8, offset+8+header[1]) >0 :
herestr2= " <-- filename is here."
print ("SEGMENT "+ str(len(MemorySegmentStart)-1)+ ": memory position: " + hex(header[0])+" to " + hex(header[0]+header[1]) + " length: " + hex(header[1])+herestr+herestr2)
#print ("first byte positoin in file: " + hex( offset+8))
#print ("last byte postion in file: " + hex(offset+8+header[1]-1))
return (8+offset+ header[1]); # return start of next segment
##################################################################
# this subroutine shows the parts of a binary file
##################################################################
def showParts(fileContent, offset):
header = struct.unpack("BBBBi", fileContent[offset:offset+8])
print ('\n\nBINARY PART\nSegments: ') + (hex(header[1]))
nextpos =offset+8
for x in range (0,header[1]):
nextpos = showSegments(fileContent,nextpos)
nextSegmentOffset = (fileContent.find("\xe9", nextpos))
return nextSegmentOffset
##################################################################
# MAIN
##################################################################
#if len(sys.argv) !=2 :
# print ("please give a filename")
# k=input("press close to exit")
# sys.exit(1)
FileName = sys.argv[1]#"C:/ArduinoPortable/sketchbooks/build/sketch_jan15a.ino.bin"
#FileName = "C:/ArduinoPortable/sketchbooks/build/sketch_jan15a.ino.bin"
print( "\n\nReplacing dummy MD5 checksum in .bin file")
with open(FileName, mode='rb') as file: # b is important -> binary
nextpos =0;
fileContent = file.read()
while nextpos >=0:
nextpos = showParts(fileContent,nextpos)
startArray,endArray,hashString = "","",""
includeStr = "hash includes segments:"
# memory sections:
# 0: bootloader (not readable)
# 1: program memory (SPI flash)
# 2: unknown but stable
# 3: RAM (initialized by bin file. Can be read but changes as you go :-( )
# 4: RAM
for i in (1,2 ): # use only stable segments, must be 4 in total. We use 2.
startArray =startArray + MemorySegmentStart[i]
endArray = endArray + MemorySegmentEnd[i]
hashString =hashString + MemoryContent[i]
with open(FileName+str(i), mode='wb') as file: # b is important -> binary
file.write(MemoryContent[i])
includeStr = includeStr +" "+ str(i)
print (includeStr)
# IMPORTANT: pad array with zeros if you use only 3 segments (see above)
while len(startArray) < 16 :
startArray =startArray + struct.pack("I",0)
endArray = endArray + struct.pack("I",0)
# debug print (binascii.hexlify(startArray))
# debug print (binascii.hexlify(endArray))
if (len(endArray) + len (startArray)) != 32 :
print("ERROR: please make sure you add / remove padding if you change the semgents.")
BinaryFileName = "";
if fileContent.find( FILENAMEDUMMY) < 0:
print("ERROR: FILENAMEDUMMY dummy not found in binary")
else:
BinaryFileName=os.path.basename(FileName) +"\0"
if len(BinaryFileName) >48: # check that filename is <48 chars
BinaryFileName=BinaryFileName[0:48] # truncate if necessary. 49th char in ESP is zero already
else:
BinaryFileName= BinaryFileName.ljust(48,'\0'); # pad with zeros.
if fileContent.find( MD5DUMMY) < 0:
print("ERROR: MD5 dummy not found in binary")
else:
hashString=hashString.replace (MD5DUMMY,"",1)
m = md5.new()
m.update (hashString) #use segment 1
md5hash = m.digest()
print("MD5 hash: "+ m.hexdigest())
print("\nwriting output file:\n" + FileName)
fileContent=fileContent.replace(MD5DUMMY,md5hash+startArray+endArray)
fileContent=fileContent.replace(FILENAMEDUMMY,BinaryFileName)
with open(FileName, mode='wb') as file: # b is important -> binary
file.write(fileContent)
#k=input("press close to exit")
+708 -300
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.
+154
View File
@@ -0,0 +1,154 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software< /span>
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Update by K. Townsend (Adafruit Industries) for lighter typedefs, and
* extended sensor support to include color, voltage and current */
#ifndef _ADAFRUIT_SENSOR_H
#define _ADAFRUIT_SENSOR_H
#if ARDUINO >= 100
#include "Arduino.h"
#include "Print.h"
#else
#include "WProgram.h"
#endif
/* Intentionally modeled after sensors.h in the Android API:
* https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */
/* Constants */
#define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */
#define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */
#define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */
#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH)
#define SENSORS_MAGFIELD_EARTH_MAX (60.0F) /**< Maximum magnetic field on Earth's surface */
#define SENSORS_MAGFIELD_EARTH_MIN (30.0F) /**< Minimum magnetic field on Earth's surface */
#define SENSORS_PRESSURE_SEALEVELHPA (1013.25F) /**< Average sea level pressure is 1013.25 hPa */
#define SENSORS_DPS_TO_RADS (0.017453293F) /**< Degrees/s to rad/s multiplier */
#define SENSORS_GAUSS_TO_MICROTESLA (100) /**< Gauss to micro-Tesla multiplier */
/** Sensor types */
typedef enum
{
SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */
SENSOR_TYPE_MAGNETIC_FIELD = (2),
SENSOR_TYPE_ORIENTATION = (3),
SENSOR_TYPE_GYROSCOPE = (4),
SENSOR_TYPE_LIGHT = (5),
SENSOR_TYPE_PRESSURE = (6),
SENSOR_TYPE_PROXIMITY = (8),
SENSOR_TYPE_GRAVITY = (9),
SENSOR_TYPE_LINEAR_ACCELERATION = (10), /**< Acceleration not including gravity */
SENSOR_TYPE_ROTATION_VECTOR = (11),
SENSOR_TYPE_RELATIVE_HUMIDITY = (12),
SENSOR_TYPE_AMBIENT_TEMPERATURE = (13),
SENSOR_TYPE_VOLTAGE = (15),
SENSOR_TYPE_CURRENT = (16),
SENSOR_TYPE_COLOR = (17)
} sensors_type_t;
/** struct sensors_vec_s is used to return a vector in a common format. */
typedef struct {
union {
float v[3];
struct {
float x;
float y;
float z;
};
/* Orientation sensors */
struct {
float roll; /**< Rotation around the longitudinal axis (the plane body, 'X axis'). Roll is positive and increasing when moving downward. -90°<=roll<=90° */
float pitch; /**< Rotation around the lateral axis (the wing span, 'Y axis'). Pitch is positive and increasing when moving upwards. -180°<=pitch<=180°) */
float heading; /**< Angle between the longitudinal axis (the plane body) and magnetic north, measured clockwise when viewing from the top of the device. 0-359° */
};
};
int8_t status;
uint8_t reserved[3];
} sensors_vec_t;
/** struct sensors_color_s is used to return color data in a common format. */
typedef struct {
union {
float c[3];
/* RGB color space */
struct {
float r; /**< Red component */
float g; /**< Green component */
float b; /**< Blue component */
};
};
uint32_t rgba; /**< 24-bit RGBA value */
} sensors_color_t;
/* Sensor event (36 bytes) */
/** struct sensor_event_s is used to provide a single sensor event in a common format. */
typedef struct
{
int32_t version; /**< must be sizeof(struct sensors_event_t) */
int32_t sensor_id; /**< unique sensor identifier */
int32_t type; /**< sensor type */
int32_t reserved0; /**< reserved */
int32_t timestamp; /**< time is in milliseconds */
union
{
float data[4];
sensors_vec_t acceleration; /**< acceleration values are in meter per second per second (m/s^2) */
sensors_vec_t magnetic; /**< magnetic vector values are in micro-Tesla (uT) */
sensors_vec_t orientation; /**< orientation values are in degrees */
sensors_vec_t gyro; /**< gyroscope values are in rad/s */
float temperature; /**< temperature is in degrees centigrade (Celsius) */
float distance; /**< distance in centimeters */
float light; /**< light in SI lux units */
float pressure; /**< pressure in hectopascal (hPa) */
float relative_humidity; /**< relative humidity in percent */
float current; /**< current in milliamps (mA) */
float voltage; /**< voltage in volts (V) */
sensors_color_t color; /**< color in RGB component values */
};
} sensors_event_t;
/* Sensor details (40 bytes) */
/** struct sensor_s is used to describe basic information about a specific sensor. */
typedef struct
{
char name[12]; /**< sensor name */
int32_t version; /**< version of the hardware + driver */
int32_t sensor_id; /**< unique sensor identifier */
int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */
float max_value; /**< maximum value of this sensor's value in SI units */
float min_value; /**< minimum value of this sensor's value in SI units */
float resolution; /**< smallest difference between two values reported by this sensor */
int32_t min_delay; /**< min delay in microseconds between events. zero = not a constant rate */
} sensor_t;
class Adafruit_Sensor {
public:
// Constructor(s)
Adafruit_Sensor() {}
virtual ~Adafruit_Sensor() {}
// These must be defined by the subclass
virtual void enableAutoRange(bool enabled) {};
virtual bool getEvent(sensors_event_t*) = 0;
virtual void getSensor(sensor_t*) = 0;
private:
bool _autoRange;
};
#endif
+221
View File
@@ -0,0 +1,221 @@
# Adafruit Unified Sensor Driver #
Many small embedded systems exist to collect data from sensors, analyse the data, and either take an appropriate action or send that sensor data to another system for processing.
One of the many challenges of embedded systems design is the fact that parts you used today may be out of production tomorrow, or system requirements may change and you may need to choose a different sensor down the road.
Creating new drivers is a relatively easy task, but integrating them into existing systems is both error prone and time consuming since sensors rarely use the exact same units of measurement.
By reducing all data to a single **sensors\_event\_t** 'type' and settling on specific, **standardised SI units** for each sensor family the same sensor types return values that are comparable with any other similar sensor. This enables you to switch sensor models with very little impact on the rest of the system, which can help mitigate some of the risks and problems of sensor availability and code reuse.
The unified sensor abstraction layer is also useful for data-logging and data-transmission since you only have one well-known type to log or transmit over the air or wire.
## Unified Sensor Drivers ##
The following drivers are based on the Adafruit Unified Sensor Driver:
**Accelerometers**
- [Adafruit\_ADXL345](https://github.com/adafruit/Adafruit_ADXL345)
- [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC)
- [Adafruit\_MMA8451\_Library](https://github.com/adafruit/Adafruit_MMA8451_Library)
**Gyroscope**
- [Adafruit\_L3GD20\_U](https://github.com/adafruit/Adafruit_L3GD20_U)
**Light**
- [Adafruit\_TSL2561](https://github.com/adafruit/Adafruit_TSL2561)
- [Adafruit\_TSL2591\_Library](https://github.com/adafruit/Adafruit_TSL2591_Library)
**Magnetometers**
- [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC)
- [Adafruit\_HMC5883\_Unified](https://github.com/adafruit/Adafruit_HMC5883_Unified)
**Barometric Pressure**
- [Adafruit\_BMP085\_Unified](https://github.com/adafruit/Adafruit_BMP085_Unified)
- [Adafruit\_BMP183\_Unified\_Library](https://github.com/adafruit/Adafruit_BMP183_Unified_Library)
**Humidity & Temperature**
- [DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library)
**Orientation**
- [Adafruit_BNO055](https://github.com/adafruit/Adafruit_BNO055)
## How Does it Work? ##
Any driver that supports the Adafruit unified sensor abstraction layer will implement the Adafruit\_Sensor base class. There are two main typedefs and one enum defined in Adafruit_Sensor.h that are used to 'abstract' away the sensor details and values:
**Sensor Types (sensors\_type\_t)**
These pre-defined sensor types are used to properly handle the two related typedefs below, and allows us determine what types of units the sensor uses, etc.
```
/** Sensor types */
typedef enum
{
SENSOR_TYPE_ACCELEROMETER = (1),
SENSOR_TYPE_MAGNETIC_FIELD = (2),
SENSOR_TYPE_ORIENTATION = (3),
SENSOR_TYPE_GYROSCOPE = (4),
SENSOR_TYPE_LIGHT = (5),
SENSOR_TYPE_PRESSURE = (6),
SENSOR_TYPE_PROXIMITY = (8),
SENSOR_TYPE_GRAVITY = (9),
SENSOR_TYPE_LINEAR_ACCELERATION = (10),
SENSOR_TYPE_ROTATION_VECTOR = (11),
SENSOR_TYPE_RELATIVE_HUMIDITY = (12),
SENSOR_TYPE_AMBIENT_TEMPERATURE = (13),
SENSOR_TYPE_VOLTAGE = (15),
SENSOR_TYPE_CURRENT = (16),
SENSOR_TYPE_COLOR = (17)
} sensors_type_t;
```
**Sensor Details (sensor\_t)**
This typedef describes the specific capabilities of this sensor, and allows us to know what sensor we are using beneath the abstraction layer.
```
/* Sensor details (40 bytes) */
/** struct sensor_s is used to describe basic information about a specific sensor. */
typedef struct
{
char name[12];
int32_t version;
int32_t sensor_id;
int32_t type;
float max_value;
float min_value;
float resolution;
int32_t min_delay;
} sensor_t;
```
The individual fields are intended to be used as follows:
- **name**: The sensor name or ID, up to a maximum of twelve characters (ex. "MPL115A2")
- **version**: The version of the sensor HW and the driver to allow us to differentiate versions of the board or driver
- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network
- **type**: The sensor type, based on **sensors\_type\_t** in sensors.h
- **max\_value**: The maximum value that this sensor can return (in the appropriate SI unit)
- **min\_value**: The minimum value that this sensor can return (in the appropriate SI unit)
- **resolution**: The smallest difference between two values that this sensor can report (in the appropriate SI unit)
- **min\_delay**: The minimum delay in microseconds between two sensor events, or '0' if there is no constant sensor rate
**Sensor Data/Events (sensors\_event\_t)**
This typedef is used to return sensor data from any sensor supported by the abstraction layer, using standard SI units and scales.
```
/* Sensor event (36 bytes) */
/** struct sensor_event_s is used to provide a single sensor event in a common format. */
typedef struct
{
int32_t version;
int32_t sensor_id;
int32_t type;
int32_t reserved0;
int32_t timestamp;
union
{
float data[4];
sensors_vec_t acceleration;
sensors_vec_t magnetic;
sensors_vec_t orientation;
sensors_vec_t gyro;
float temperature;
float distance;
float light;
float pressure;
float relative_humidity;
float current;
float voltage;
sensors_color_t color;
};
} sensors_event_t;
```
It includes the following fields:
- **version**: Contain 'sizeof(sensors\_event\_t)' to identify which version of the API we're using in case this changes in the future
- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network (must match the sensor\_id value in the corresponding sensor\_t enum above!)
- **type**: the sensor type, based on **sensors\_type\_t** in sensors.h
- **timestamp**: time in milliseconds when the sensor value was read
- **data[4]**: An array of four 32-bit values that allows us to encapsulate any type of sensor data via a simple union (further described below)
**Required Functions**
In addition to the two standard types and the sensor type enum, all drivers based on Adafruit_Sensor must also implement the following two functions:
```
bool getEvent(sensors_event_t*);
```
Calling this function will populate the supplied sensors\_event\_t reference with the latest available sensor data. You should call this function as often as you want to update your data.
```
void getSensor(sensor_t*);
```
Calling this function will provide some basic information about the sensor (the sensor name, driver version, min and max values, etc.
**Standardised SI values for sensors\_event\_t**
A key part of the abstraction layer is the standardisation of values on SI units of a particular scale, which is accomplished via the data[4] union in sensors\_event\_t above. This 16 byte union includes fields for each main sensor type, and uses the following SI units and scales:
- **acceleration**: values are in **meter per second per second** (m/s^2)
- **magnetic**: values are in **micro-Tesla** (uT)
- **orientation**: values are in **degrees**
- **gyro**: values are in **rad/s**
- **temperature**: values in **degrees centigrade** (Celsius)
- **distance**: values are in **centimeters**
- **light**: values are in **SI lux** units
- **pressure**: values are in **hectopascal** (hPa)
- **relative\_humidity**: values are in **percent**
- **current**: values are in **milliamps** (mA)
- **voltage**: values are in **volts** (V)
- **color**: values are in 0..1.0 RGB channel luminosity and 32-bit RGBA format
## The Unified Driver Abstraction Layer in Practice ##
Using the unified sensor abstraction layer is relatively easy once a compliant driver has been created.
Every compliant sensor can now be read using a single, well-known 'type' (sensors\_event\_t), and there is a standardised way of interrogating a sensor about its specific capabilities (via sensor\_t).
An example of reading the [TSL2561](https://github.com/adafruit/Adafruit_TSL2561) light sensor can be seen below:
```
Adafruit_TSL2561 tsl = Adafruit_TSL2561(TSL2561_ADDR_FLOAT, 12345);
...
/* Get a new sensor event */
sensors_event_t event;
tsl.getEvent(&event);
/* Display the results (light is measured in lux) */
if (event.light)
{
Serial.print(event.light); Serial.println(" lux");
}
else
{
/* If event.light = 0 lux the sensor is probably saturated
and no reliable data could be generated! */
Serial.println("Sensor overload");
}
```
Similarly, we can get the basic technical capabilities of this sensor with the following code:
```
sensor_t sensor;
sensor_t sensor;
tsl.getSensor(&sensor);
/* Display the sensor details */
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux");
Serial.println("------------------------------------");
Serial.println("");
```
+9
View File
@@ -0,0 +1,9 @@
name=Adafruit Unified Sensor
version=1.0.2
author=Adafruit <info@adafruit.com>
maintainer=Adafruit <info@adafruit.com>
sentence=Required for all Adafruit Unified Sensor based libraries.
paragraph=A unified sensor abstraction layer used by many Adafruit sensor libraries.
category=Sensors
url=https://github.com/adafruit/Adafruit_Sensor
architectures=*
+46
View File
@@ -0,0 +1,46 @@
Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:
- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use
the forums at http://forums.adafruit.com to ask questions and troubleshoot why
something isn't working as expected. In many cases the problem is a common issue
that you will more quickly receive help from the forum community. GitHub issues
are meant for known defects in the code. If you don't know if there is a defect
in the code then start with troubleshooting on the forum first.
- **If following a tutorial or guide be sure you didn't miss a step.** Carefully
check all of the steps and commands to run have been followed. Consult the
forum if you're unsure or have questions about steps in a guide/tutorial.
- **For Arduino projects check these very common issues to ensure they don't apply**:
- For uploading sketches or communicating with the board make sure you're using
a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes
very hard to tell the difference between a data and charge cable! Try using the
cable with other devices or swapping to another cable to confirm it is not
the problem.
- **Be sure you are supplying adequate power to the board.** Check the specs of
your board and plug in an external power supply. In many cases just
plugging a board into your computer is not enough to power it and other
peripherals.
- **Double check all soldering joints and connections.** Flakey connections
cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints.
- **Ensure you are using an official Arduino or Adafruit board.** We can't
guarantee a clone board will have the same functionality and work as expected
with this code and don't support them.
If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:
- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE**
- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO
VERSION HERE**
- List the steps to reproduce the problem below (if possible attach a sketch or
copy the sketch code in too): **LIST REPRO STEPS BELOW**
+26
View File
@@ -0,0 +1,26 @@
Thank you for creating a pull request to contribute to Adafruit's GitHub code!
Before you open the request please review the following guidelines and tips to
help it be more easily integrated:
- **Describe the scope of your change--i.e. what the change does and what parts
of the code were modified.** This will help us understand any risks of integrating
the code.
- **Describe any known limitations with your change.** For example if the change
doesn't apply to a supported platform of the library please mention it.
- **Please run any tests or examples that can exercise your modified code.** We
strive to not break users of the code and running tests/examples helps with this
process.
Thank you again for contributing! We will try to test and integrate the change
as soon as we can, but be aware we have many GitHub repositories to manage and
can't immediately respond to every request. There is no need to bump or check in
on a pull request (it will clutter the discussion of the request).
Also don't be worried if the request is closed or not integrated--sometimes the
priorities of Adafruit's GitHub code (education, ease of use) might not match the
priorities of the pull request. Don't fret, the open source community thrives on
forks and GitHub makes it easy to keep your changes in a forked repo.
After reviewing the guidelines above you can delete this text from the pull request.
+504
View File
@@ -0,0 +1,504 @@
/**************************************************************************/
/*!
@file Adafruit_TSL2591.cpp
@author KT0WN (adafruit.com)
This is a library for the Adafruit TSL2591 breakout board
This library works with the Adafruit TSL2591 breakout
----> https://www.adafruit.com/products/1980
Check out the links above for our tutorials and wiring diagrams
These chips use I2C to communicate
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2014 Adafruit Industries
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#if defined(ESP8266) || defined(ESP32)
#include <pgmspace.h>
#else
#include <avr/pgmspace.h>
#endif
#if defined(__AVR__)
#include <util/delay.h>
#endif
#include <stdlib.h>
#include "Adafruit_TSL2591.h"
Adafruit_TSL2591::Adafruit_TSL2591(int32_t sensorID)
{
_initialized = false;
_integration = TSL2591_INTEGRATIONTIME_100MS;
_gain = TSL2591_GAIN_MED;
_sensorID = sensorID;
// we cant do wire initialization till later, because we havent loaded Wire yet
}
boolean Adafruit_TSL2591::begin(void)
{
Wire.begin();
/*
for (uint8_t i=0; i<0x20; i++)
{
uint8_t id = read8(0x12);
Serial.print("$"); Serial.print(i, HEX);
Serial.print(" = 0x"); Serial.println(read8(i), HEX);
}
*/
uint8_t id = read8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_DEVICE_ID);
if (id == 0x50 )
{
// Serial.println("Found Adafruit_TSL2591");
}
else
{
return false;
}
_initialized = true;
// Set default integration time and gain
setTiming(_integration);
setGain(_gain);
// Note: by default, the device is in power down mode on bootup
disable();
return true;
}
void Adafruit_TSL2591::enable(void)
{
if (!_initialized)
{
if (!begin())
{
return;
}
}
// Enable the device by setting the control bit to 0x01
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWERON | TSL2591_ENABLE_AEN | TSL2591_ENABLE_AIEN | TSL2591_ENABLE_NPIEN);
}
void Adafruit_TSL2591::disable(void)
{
if (!_initialized)
{
if (!begin())
{
return;
}
}
// Disable the device by setting the control bit to 0x00
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_ENABLE, TSL2591_ENABLE_POWEROFF);
}
void Adafruit_TSL2591::setGain(tsl2591Gain_t gain)
{
if (!_initialized)
{
if (!begin())
{
return;
}
}
enable();
_gain = gain;
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL, _integration | _gain);
disable();
}
tsl2591Gain_t Adafruit_TSL2591::getGain()
{
return _gain;
}
void Adafruit_TSL2591::setTiming(tsl2591IntegrationTime_t integration)
{
if (!_initialized)
{
if (!begin())
{
return;
}
}
enable();
_integration = integration;
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CONTROL, _integration | _gain);
disable();
}
tsl2591IntegrationTime_t Adafruit_TSL2591::getTiming()
{
return _integration;
}
float Adafruit_TSL2591::calculateLuxf(uint16_t ch0, uint16_t ch1)
{
float atime, again;
float cpl, lux1, lux2, lux;
uint32_t chan0, chan1;
// Check for overflow conditions first
if ((ch0 == 0xFFFF) | (ch1 == 0xFFFF))
{
// Signal an overflow
return 0;
}
// Note: This algorithm is based on preliminary coefficients
// provided by AMS and may need to be updated in the future
switch (_integration)
{
case TSL2591_INTEGRATIONTIME_100MS :
atime = 100.0F;
break;
case TSL2591_INTEGRATIONTIME_200MS :
atime = 200.0F;
break;
case TSL2591_INTEGRATIONTIME_300MS :
atime = 300.0F;
break;
case TSL2591_INTEGRATIONTIME_400MS :
atime = 400.0F;
break;
case TSL2591_INTEGRATIONTIME_500MS :
atime = 500.0F;
break;
case TSL2591_INTEGRATIONTIME_600MS :
atime = 600.0F;
break;
default: // 100ms
atime = 100.0F;
break;
}
switch (_gain)
{
case TSL2591_GAIN_LOW :
again = 1.0F;
break;
case TSL2591_GAIN_MED :
again = 25.0F;
break;
case TSL2591_GAIN_HIGH :
again = 428.0F;
break;
case TSL2591_GAIN_MAX :
again = 9876.0F;
break;
default:
again = 1.0F;
break;
}
// cpl = (ATIME * AGAIN) / DF
cpl = (atime * again) / TSL2591_LUX_DF;
lux1 = (((float) ch0 - (float) ch1)) * (1.0F - ((float) ch1 / (float) ch0)) / cpl;//( (float)ch0 - (TSL2591_LUX_COEFB * (float)ch1) ) / cpl;
lux2 = ((TSL2591_LUX_COEFC * (float) ch0) - (TSL2591_LUX_COEFD * (float) ch1)) / cpl;
lux = lux1 > lux2 ? lux1 : lux2;
// Alternate lux calculation
//lux = ( (float)ch0 - ( 1.7F * (float)ch1 ) ) / cpl;
// Signal I2C had no errors
return lux;
}
uint32_t Adafruit_TSL2591::calculateLux(uint16_t ch0, uint16_t ch1)
{
return (uint32_t) calculateLuxf(ch0, ch1);
}
uint32_t Adafruit_TSL2591::getFullLuminosity (void)
{
if (!_initialized)
{
if (!begin())
{
return 0;
}
}
// Enable the device
enable();
// Wait x ms for ADC to complete
for (uint8_t d=0; d<=_integration; d++)
{
delay(120);
}
uint32_t x;
uint16_t y;
y |= read16(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN0_LOW);
x = read16(TSL2591_COMMAND_BIT | TSL2591_REGISTER_CHAN1_LOW);
x <<= 16;
x |= y;
disable();
return x;
}
uint16_t Adafruit_TSL2591::getLuminosity (uint8_t channel)
{
uint32_t x = getFullLuminosity();
if (channel == TSL2591_FULLSPECTRUM)
{
// Reads two byte value from channel 0 (visible + infrared)
return (x & 0xFFFF);
}
else if (channel == TSL2591_INFRARED)
{
// Reads two byte value from channel 1 (infrared)
return (x >> 16);
}
else if (channel == TSL2591_VISIBLE)
{
// Reads all and subtracts out just the visible!
return ( (x & 0xFFFF) - (x >> 16));
}
// unknown channel!
return 0;
}
void Adafruit_TSL2591::registerInterrupt(uint16_t lowerThreshold, uint16_t upperThreshold)
{
if (!_initialized)
{
if (!begin())
{
return;
}
}
enable();
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_NPAILTL, lowerThreshold);
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_NPAILTH, lowerThreshold >> 8);
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_NPAIHTL, upperThreshold);
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_NPAIHTH, upperThreshold >> 8);
disable();
}
void Adafruit_TSL2591::registerInterrupt(uint16_t lowerThreshold, uint16_t upperThreshold, tsl2591Persist_t persist)
{
if (!_initialized)
{
if (!begin())
{
return;
}
}
enable();
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_PERSIST_FILTER, persist);
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_AILTL, lowerThreshold);
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_AILTH, lowerThreshold >> 8);
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_AIHTL, upperThreshold);
write8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_THRESHOLD_AIHTH, upperThreshold >> 8);
disable();
}
void Adafruit_TSL2591::clearInterrupt()
{
if (!_initialized)
{
if (!begin())
{
return;
}
}
enable();
write8(TSL2591_CLEAR_INT);
disable();
}
uint8_t Adafruit_TSL2591::getStatus()
{
if (!_initialized)
{
if (!begin())
{
return 0;
}
}
// Enable the device
enable();
uint8_t x;
x = read8(TSL2591_COMMAND_BIT | TSL2591_REGISTER_DEVICE_STATUS);
disable();
return x;
}
uint8_t Adafruit_TSL2591::read8(uint8_t reg)
{
uint8_t x;
Wire.beginTransmission(TSL2591_ADDR);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.requestFrom(TSL2591_ADDR, 1);
#if ARDUINO >= 100
x = Wire.read();
#else
x = Wire.receive();
#endif
// while (! Wire.available());
// return Wire.read();
return x;
}
uint16_t Adafruit_TSL2591::read16(uint8_t reg)
{
uint16_t x;
uint16_t t;
Wire.beginTransmission(TSL2591_ADDR);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.requestFrom(TSL2591_ADDR, 2);
#if ARDUINO >= 100
t = Wire.read();
x = Wire.read();
#else
t = Wire.receive();
x = Wire.receive();
#endif
x <<= 8;
x |= t;
return x;
}
void Adafruit_TSL2591::write8 (uint8_t reg, uint8_t value)
{
Wire.beginTransmission(TSL2591_ADDR);
#if ARDUINO >= 100
Wire.write(reg);
Wire.write(value);
#else
Wire.send(reg);
Wire.send(value);
#endif
Wire.endTransmission();
}
void Adafruit_TSL2591::write8 (uint8_t reg)
{
Wire.beginTransmission(TSL2591_ADDR);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
}
/**************************************************************************/
/*!
@brief Gets the most recent sensor event
*/
/**************************************************************************/
bool Adafruit_TSL2591::getEvent(sensors_event_t *event)
{
uint16_t ir, full;
uint32_t lum = getFullLuminosity();
/* Early silicon seems to have issues when there is a sudden jump in */
/* light levels. :( To work around this for now sample the sensor 2x */
lum = getFullLuminosity();
ir = lum >> 16;
full = lum & 0xFFFF;
/* Clear the event */
memset(event, 0, sizeof(sensors_event_t));
event->version = sizeof(sensors_event_t);
event->sensor_id = _sensorID;
event->type = SENSOR_TYPE_LIGHT;
event->timestamp = millis();
/* Calculate the actual lux value */
/* 0 = sensor overflow (too much light) */
event->light = calculateLux(full, ir);
return true;
}
/**************************************************************************/
/*!
@brief Gets the sensor_t data
*/
/**************************************************************************/
void Adafruit_TSL2591::getSensor(sensor_t *sensor)
{
/* Clear the sensor_t object */
memset(sensor, 0, sizeof(sensor_t));
/* Insert the sensor name in the fixed length char array */
strncpy (sensor->name, "TSL2591", sizeof(sensor->name) - 1);
sensor->name[sizeof(sensor->name)- 1] = 0;
sensor->version = 1;
sensor->sensor_id = _sensorID;
sensor->type = SENSOR_TYPE_LIGHT;
sensor->min_delay = 0;
sensor->max_value = 88000.0;
sensor->min_value = 0.0;
sensor->resolution = 1.0;
}
+187
View File
@@ -0,0 +1,187 @@
/**************************************************************************/
/*!
@file Adafruit_TSL2591.h
@author KT0WN (adafruit.com)
This is a library for the Adafruit TSL2591 breakout board
This library works with the Adafruit TSL2591 breakout
----> https://www.adafruit.com/products/1980
Check out the links above for our tutorials and wiring diagrams
These chips use I2C to communicate
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2014 Adafruit Industries
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#ifndef _TSL2591_H_
#define _TSL2591_H_
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <Adafruit_Sensor.h>
#include <Wire.h>
#define TSL2591_VISIBLE (2) // channel 0 - channel 1
#define TSL2591_INFRARED (1) // channel 1
#define TSL2591_FULLSPECTRUM (0) // channel 0
#define TSL2591_ADDR (0x29)
#define TSL2591_READBIT (0x01)
#define TSL2591_COMMAND_BIT (0xA0) // 1010 0000: bits 7 and 5 for 'command normal'
#define TSL2591_CLEAR_INT (0xE7)
#define TSL2591_TEST_INT (0xE4)
#define TSL2591_WORD_BIT (0x20) // 1 = read/write word (rather than byte)
#define TSL2591_BLOCK_BIT (0x10) // 1 = using block read/write
#define TSL2591_ENABLE_POWEROFF (0x00)
#define TSL2591_ENABLE_POWERON (0x01)
#define TSL2591_ENABLE_AEN (0x02) // ALS Enable. This field activates ALS function. Writing a one activates the ALS. Writing a zero disables the ALS.
#define TSL2591_ENABLE_AIEN (0x10) // ALS Interrupt Enable. When asserted permits ALS interrupts to be generated, subject to the persist filter.
#define TSL2591_ENABLE_NPIEN (0x80) // No Persist Interrupt Enable. When asserted NP Threshold conditions will generate an interrupt, bypassing the persist filter
#define TSL2591_LUX_DF (408.0F)
#define TSL2591_LUX_COEFB (1.64F) // CH0 coefficient
#define TSL2591_LUX_COEFC (0.59F) // CH1 coefficient A
#define TSL2591_LUX_COEFD (0.86F) // CH2 coefficient B
enum
{
TSL2591_REGISTER_ENABLE = 0x00,
TSL2591_REGISTER_CONTROL = 0x01,
TSL2591_REGISTER_THRESHOLD_AILTL = 0x04, // ALS low threshold lower byte
TSL2591_REGISTER_THRESHOLD_AILTH = 0x05, // ALS low threshold upper byte
TSL2591_REGISTER_THRESHOLD_AIHTL = 0x06, // ALS high threshold lower byte
TSL2591_REGISTER_THRESHOLD_AIHTH = 0x07, // ALS high threshold upper byte
TSL2591_REGISTER_THRESHOLD_NPAILTL = 0x08, // No Persist ALS low threshold lower byte
TSL2591_REGISTER_THRESHOLD_NPAILTH = 0x09, // etc
TSL2591_REGISTER_THRESHOLD_NPAIHTL = 0x0A,
TSL2591_REGISTER_THRESHOLD_NPAIHTH = 0x0B,
TSL2591_REGISTER_PERSIST_FILTER = 0x0C,
TSL2591_REGISTER_PACKAGE_PID = 0x11,
TSL2591_REGISTER_DEVICE_ID = 0x12,
TSL2591_REGISTER_DEVICE_STATUS = 0x13,
TSL2591_REGISTER_CHAN0_LOW = 0x14,
TSL2591_REGISTER_CHAN0_HIGH = 0x15,
TSL2591_REGISTER_CHAN1_LOW = 0x16,
TSL2591_REGISTER_CHAN1_HIGH = 0x17
};
typedef enum
{
TSL2591_INTEGRATIONTIME_100MS = 0x00,
TSL2591_INTEGRATIONTIME_200MS = 0x01,
TSL2591_INTEGRATIONTIME_300MS = 0x02,
TSL2591_INTEGRATIONTIME_400MS = 0x03,
TSL2591_INTEGRATIONTIME_500MS = 0x04,
TSL2591_INTEGRATIONTIME_600MS = 0x05,
}
tsl2591IntegrationTime_t;
typedef enum
{
// bit 7:4: 0
TSL2591_PERSIST_EVERY = 0x00, // Every ALS cycle generates an interrupt
TSL2591_PERSIST_ANY = 0x01, // Any value outside of threshold range
TSL2591_PERSIST_2 = 0x02, // 2 consecutive values out of range
TSL2591_PERSIST_3 = 0x03, // 3 consecutive values out of range
TSL2591_PERSIST_5 = 0x04, // 5 consecutive values out of range
TSL2591_PERSIST_10 = 0x05, // 10 consecutive values out of range
TSL2591_PERSIST_15 = 0x06, // 15 consecutive values out of range
TSL2591_PERSIST_20 = 0x07, // 20 consecutive values out of range
TSL2591_PERSIST_25 = 0x08, // 25 consecutive values out of range
TSL2591_PERSIST_30 = 0x09, // 30 consecutive values out of range
TSL2591_PERSIST_35 = 0x0A, // 35 consecutive values out of range
TSL2591_PERSIST_40 = 0x0B, // 40 consecutive values out of range
TSL2591_PERSIST_45 = 0x0C, // 45 consecutive values out of range
TSL2591_PERSIST_50 = 0x0D, // 50 consecutive values out of range
TSL2591_PERSIST_55 = 0x0E, // 55 consecutive values out of range
TSL2591_PERSIST_60 = 0x0F, // 60 consecutive values out of range
}
tsl2591Persist_t;
typedef enum
{
TSL2591_GAIN_LOW = 0x00, // low gain (1x)
TSL2591_GAIN_MED = 0x10, // medium gain (25x)
TSL2591_GAIN_HIGH = 0x20, // medium gain (428x)
TSL2591_GAIN_MAX = 0x30, // max gain (9876x)
}
tsl2591Gain_t;
class Adafruit_TSL2591 : public Adafruit_Sensor
{
public:
Adafruit_TSL2591(int32_t sensorID = -1);
boolean begin ( void );
void enable ( void );
void disable ( void );
void write8 ( uint8_t r);
void write8 ( uint8_t r, uint8_t v );
uint16_t read16 ( uint8_t reg );
uint8_t read8 ( uint8_t reg );
uint32_t calculateLux ( uint16_t ch0, uint16_t ch1 );
float calculateLuxf ( uint16_t ch0, uint16_t ch1 );
void setGain ( tsl2591Gain_t gain );
void setTiming ( tsl2591IntegrationTime_t integration );
uint16_t getLuminosity (uint8_t channel );
uint32_t getFullLuminosity ( );
tsl2591IntegrationTime_t getTiming();
tsl2591Gain_t getGain();
// Interrupt
void clearInterrupt(void);
void registerInterrupt(uint16_t lowerThreshold, uint16_t upperThreshold);
void registerInterrupt(uint16_t lowerThreshold, uint16_t upperThreshold, tsl2591Persist_t persist);
uint8_t getStatus();
/* Unified Sensor API Functions */
bool getEvent ( sensors_event_t* );
void getSensor ( sensor_t* );
private:
tsl2591IntegrationTime_t _integration;
tsl2591Gain_t _gain;
int32_t _sensorID;
boolean _initialized;
};
#endif
+9
View File
@@ -0,0 +1,9 @@
This is an Arduino library for the TSL2591 digital luminosity (light) sensors.
Pick one up at http://www.adafruit.com/products/1980
To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder Adafruit_TSL2591. Check that the Adafruit_TSL2591 folder contains Adafruit_TSL2591.cpp and Adafruit_TSL2591.h
Place the Adafruit_TSL2591 library folder your <arduinosketchfolder>/libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE.
You'll also need the Adafruit_Sensor library from https://github.com/adafruit/Adafruit_Sensor
@@ -0,0 +1,200 @@
/* TSL2591 Digital Light Sensor */
/* Dynamic Range: 600M:1 */
/* Maximum Lux: 88K */
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"
// Example for demonstrating the TSL2591 library - public domain!
// connect SCL to analog 5
// connect SDA to analog 4
// connect Vin to 3.3-5V DC
// connect GROUND to common ground
Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)
/**************************************************************************/
/*
Displays some basic information on this sensor from the unified
sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/
void displaySensorDetails(void)
{
sensor_t sensor;
tsl.getSensor(&sensor);
Serial.println(F("------------------------------------"));
Serial.print (F("Sensor: ")); Serial.println(sensor.name);
Serial.print (F("Driver Ver: ")); Serial.println(sensor.version);
Serial.print (F("Unique ID: ")); Serial.println(sensor.sensor_id);
Serial.print (F("Max Value: ")); Serial.print(sensor.max_value); Serial.println(F(" lux"));
Serial.print (F("Min Value: ")); Serial.print(sensor.min_value); Serial.println(F(" lux"));
Serial.print (F("Resolution: ")); Serial.print(sensor.resolution); Serial.println(F(" lux"));
Serial.println(F("------------------------------------"));
Serial.println(F(""));
delay(500);
}
/**************************************************************************/
/*
Configures the gain and integration time for the TSL2591
*/
/**************************************************************************/
void configureSensor(void)
{
// You can change the gain on the fly, to adapt to brighter/dimmer light situations
//tsl.setGain(TSL2591_GAIN_LOW); // 1x gain (bright light)
tsl.setGain(TSL2591_GAIN_MED); // 25x gain
// tsl.setGain(TSL2591_GAIN_HIGH); // 428x gain
// Changing the integration time gives you a longer time over which to sense light
// longer timelines are slower, but are good in very low light situtations!
tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS); // shortest integration time (bright light)
// tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS); // longest integration time (dim light)
/* Display the gain and integration time for reference sake */
Serial.println(F("------------------------------------"));
Serial.print (F("Gain: "));
tsl2591Gain_t gain = tsl.getGain();
switch(gain)
{
case TSL2591_GAIN_LOW:
Serial.println(F("1x (Low)"));
break;
case TSL2591_GAIN_MED:
Serial.println(F("25x (Medium)"));
break;
case TSL2591_GAIN_HIGH:
Serial.println(F("428x (High)"));
break;
case TSL2591_GAIN_MAX:
Serial.println(F("9876x (Max)"));
break;
}
Serial.print (F("Timing: "));
Serial.print((tsl.getTiming() + 1) * 100, DEC);
Serial.println(F(" ms"));
Serial.println(F("------------------------------------"));
Serial.println(F(""));
}
/**************************************************************************/
/*
Program entry point for the Arduino sketch
*/
/**************************************************************************/
void setup(void)
{
Serial.begin(9600);
Serial.println(F("Starting Adafruit TSL2591 Test!"));
if (tsl.begin())
{
Serial.println(F("Found a TSL2591 sensor"));
}
else
{
Serial.println(F("No sensor found ... check your wiring?"));
while (1);
}
/* Display some basic information on this sensor */
displaySensorDetails();
/* Configure the sensor */
configureSensor();
// Now we're ready to get readings ... move on to loop()!
}
/**************************************************************************/
/*
Shows how to perform a basic read on visible, full spectrum or
infrared light (returns raw 16-bit ADC values)
*/
/**************************************************************************/
void simpleRead(void)
{
// Simple data read example. Just read the infrared, fullspecrtrum diode
// or 'visible' (difference between the two) channels.
// This can take 100-600 milliseconds! Uncomment whichever of the following you want to read
uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
//uint16_t x = tsl.getLuminosity(TSL2591_FULLSPECTRUM);
//uint16_t x = tsl.getLuminosity(TSL2591_INFRARED);
Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
Serial.print(F("Luminosity: "));
Serial.println(x, DEC);
}
/**************************************************************************/
/*
Show how to read IR and Full Spectrum at once and convert to lux
*/
/**************************************************************************/
void advancedRead(void)
{
// More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
// That way you can do whatever math and comparisons you want!
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
Serial.print(F("IR: ")); Serial.print(ir); Serial.print(F(" "));
Serial.print(F("Full: ")); Serial.print(full); Serial.print(F(" "));
Serial.print(F("Visible: ")); Serial.print(full - ir); Serial.print(F(" "));
Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir));
}
/**************************************************************************/
/*
Performs a read using the Adafruit Unified Sensor API.
*/
/**************************************************************************/
void unifiedSensorAPIRead(void)
{
/* Get a new sensor event */
sensors_event_t event;
tsl.getEvent(&event);
/* Display the results (light is measured in lux) */
Serial.print(F("[ ")); Serial.print(event.timestamp); Serial.print(F(" ms ] "));
if ((event.light == 0) |
(event.light > 4294966000.0) |
(event.light <-4294966000.0))
{
/* If event.light = 0 lux the sensor is probably saturated */
/* and no reliable data could be generated! */
/* if event.light is +/- 4294967040 there was a float over/underflow */
Serial.println(F("Invalid data (adjust gain or timing)"));
}
else
{
Serial.print(event.light); Serial.println(F(" lux"));
}
}
/**************************************************************************/
/*
Arduino loop function, called once 'setup' is complete (your own code
should go here)
*/
/**************************************************************************/
void loop(void)
{
//simpleRead();
advancedRead();
// unifiedSensorAPIRead();
delay(500);
}
@@ -0,0 +1,229 @@
/* TSL2591 Digital Light Sensor, example with (simple) interrupt support */
/* Dynamic Range: 600M:1 */
/* Maximum Lux: 88K */
/* This example shows how the interrupt system on the TLS2591
* can be used to detect a meaningful change in light levels.
*
* Two thresholds can be set:
*
* Lower Threshold - Any light sample on CHAN0 below this value
* will trigger an interrupt
* Upper Threshold - Any light sample on CHAN0 above this value
* will trigger an interrupt
*
* If CHAN0 (full light) crosses below the low threshold specified,
* or above the higher threshold, an interrupt is asserted on the interrupt
* pin. The use of the HW pin is optional, though, since the change can
* also be detected in software by looking at the status byte via
* tsl.getStatus().
*
* An optional third parameter can be used in the .registerInterrupt
* function to indicate the number of samples that must stay outside
* the threshold window before the interrupt fires, providing some basic
* debouncing of light level data.
*
* For example, the following code will fire an interrupt on any and every
* sample outside the window threshold (meaning a sample below 100 or above
* 1500 on CHAN0 or FULL light):
*
* tsl.registerInterrupt(100, 1500, TSL2591_PERSIST_ANY);
*
* This code would require five consecutive changes before the interrupt
* fires though (see tls2591Persist_t in Adafruit_TLS2591.h for possible
* values):
*
* tsl.registerInterrupt(100, 1500, TSL2591_PERSIST_5);
*/
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"
// Example for demonstrating the TSL2591 library - public domain!
// connect SCL to analog 5
// connect SDA to analog 4
// connect Vin to 3.3-5V DC
// connect GROUND to common ground
// Interrupt thresholds and persistance
#define TLS2591_INT_THRESHOLD_LOWER (100)
#define TLS2591_INT_THRESHOLD_UPPER (1500)
//#define TLS2591_INT_PERSIST (TSL2591_PERSIST_ANY) // Fire on any valid change
#define TLS2591_INT_PERSIST (TSL2591_PERSIST_60) // Require at least 60 samples to fire
Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)
/**************************************************************************/
/*
Displays some basic information on this sensor from the unified
sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/
void displaySensorDetails(void)
{
sensor_t sensor;
tsl.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux");
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}
/**************************************************************************/
/*
Configures the gain and integration time for the TSL2591
*/
/**************************************************************************/
void configureSensor(void)
{
// You can change the gain on the fly, to adapt to brighter/dimmer light situations
//tsl.setGain(TSL2591_GAIN_LOW); // 1x gain (bright light)
tsl.setGain(TSL2591_GAIN_MED); // 25x gain
// tsl.setGain(TSL2591_GAIN_HIGH); // 428x gain
// Changing the integration time gives you a longer time over which to sense light
// longer timelines are slower, but are good in very low light situtations!
tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS); // shortest integration time (bright light)
// tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS); // longest integration time (dim light)
/* Display the gain and integration time for reference sake */
Serial.println("------------------------------------");
Serial.print ("Gain: ");
tsl2591Gain_t gain = tsl.getGain();
switch (gain)
{
case TSL2591_GAIN_LOW:
Serial.println("1x (Low)");
break;
case TSL2591_GAIN_MED:
Serial.println("25x (Medium)");
break;
case TSL2591_GAIN_HIGH:
Serial.println("428x (High)");
break;
case TSL2591_GAIN_MAX:
Serial.println("9876x (Max)");
break;
}
Serial.print ("Timing: ");
Serial.print((tsl.getTiming() + 1) * 100, DEC);
Serial.println(" ms");
Serial.println("------------------------------------");
Serial.println("");
/* Setup the SW interrupt to trigger between 100 and 1500 lux */
/* Threshold values are defined at the top of this sketch */
tsl.clearInterrupt();
tsl.registerInterrupt(TLS2591_INT_THRESHOLD_LOWER,
TLS2591_INT_THRESHOLD_UPPER,
TLS2591_INT_PERSIST);
/* Display the interrupt threshold window */
Serial.print("Interrupt Threshold Window: -");
Serial.print(TLS2591_INT_THRESHOLD_LOWER, DEC);
Serial.print(" to +");
Serial.println(TLS2591_INT_THRESHOLD_LOWER, DEC);
Serial.println("");
}
/**************************************************************************/
/*
Program entry point for the Arduino sketch
*/
/**************************************************************************/
void setup(void)
{
Serial.begin(9600);
// Enable this line for Flora, Zero and Feather boards with no FTDI chip
// Waits for the serial port to connect before sending data out
// while (!Serial) { delay(1); }
Serial.println("Starting Adafruit TSL2591 interrupt Test!");
if (tsl.begin())
{
Serial.println("Found a TSL2591 sensor");
}
else
{
Serial.println("No sensor found ... check your wiring?");
while (1);
}
/* Display some basic information on this sensor */
displaySensorDetails();
/* Configure the sensor (including the interrupt threshold) */
configureSensor();
// Now we're ready to get readings ... move on to loop()!
}
/**************************************************************************/
/*
Show how to read IR and Full Spectrum at once and convert to lux
*/
/**************************************************************************/
void advancedRead(void)
{
// More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
// That way you can do whatever math and comparisons you want!
uint32_t lum = tsl.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
Serial.print("[ "); Serial.print(millis()); Serial.print(" ms ] ");
Serial.print("IR: "); Serial.print(ir); Serial.print(" ");
Serial.print("Full: "); Serial.print(full); Serial.print(" ");
Serial.print("Visible: "); Serial.print(full - ir); Serial.print(" ");
Serial.print("Lux: "); Serial.println(tsl.calculateLux(full, ir));
}
void getStatus(void)
{
uint8_t x = tsl.getStatus();
// bit 4: ALS Interrupt occured
// bit 5: No-persist Interrupt occurence
if (x & 0x10) {
Serial.print("[ "); Serial.print(millis()); Serial.print(" ms ] ");
Serial.println("ALS Interrupt occured");
}
if (x & 0x20) {
Serial.print("[ "); Serial.print(millis()); Serial.print(" ms ] ");
Serial.println("No-persist Interrupt occured");
}
// Serial.print("[ "); Serial.print(millis()); Serial.print(" ms ] ");
Serial.print("Status: ");
Serial.println(x, BIN);
tsl.clearInterrupt();
}
/**************************************************************************/
/*
Arduino loop function, called once 'setup' is complete (your own code
should go here)
*/
/**************************************************************************/
void loop(void)
{
advancedRead();
getStatus();
delay(500);
}
+9
View File
@@ -0,0 +1,9 @@
name=Adafruit TSL2591 Library
version=1.0.2
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Library for the TSL2591 digital luminosity (light) sensors.
paragraph=Library for the TSL2591 digital luminosity (light) sensors.
category=Sensors
url=https://github.com/adafruit/Adafruit_TSL2591_Library
architectures=*
+74
View File
@@ -0,0 +1,74 @@
/*
Name: PingTest.ino
Created: 05/08/2017 10:20:19
Author: pbecc
*/
#undef PROVA_
#include <WiFi.h>
#include "esp32_ping.h"
// the setup function runs once when you press reset or power the board
const char ssid[] = "TP-LINK_C20B"; // your network SSID (name)
const char password[] = "paolo-48"; // your network password
void setup() {
Serial.begin(115200);
Serial.print("Connecting t ");
Serial.println(ssid);
// WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Pinging address: 192.168.1.1");
}
// the loop function runs over and over again until power down or reset
void loop() {
int ia[4] = { 192,168,1,1 };
int i = 0;
while (Serial.available()) {
char c = Serial.read();
delay(100);
int val = 0;
while (c != '.' && c != 10 && c!=255) {
if (c >= '0'&& c<='9') {
val = val*10+(c-'0');
}
c = Serial.read();
}
ia[i++] =val ;
}
IPAddress adr = IPAddress(ia[0], ia[1], ia[2], ia[3]);
Serial.printf("Ping : %d . %d . %d . %d ->", ia[0], ia[1], ia[2], ia[3]);
if (ping_start(adr, 4, 0, 0, 5))
Serial.println("OK");
else
Serial.println("FAILED");
delay(10000);
}
int readnu(char s) {
char c = Serial.read();
Serial.print(c);
int digit = 1,val=0;
while (c != s && c != 10&&c>0) {
if(c>'0') val += digit*(c - '0');
digit *= 10;
c=Serial.read();
Serial.print(int(c));
}
Serial.println(digit);
return digit;
}
+4
View File
@@ -0,0 +1,4 @@
# ESP32_ping
Ping library for ESP32
WORK IN PROGRESS
+366
View File
@@ -0,0 +1,366 @@
/*
* ESP32 Ping library
*
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purpose and without fee is hereby
* granted, provided that the above copyright notice appear in all
* copies and that both that the copyright notice and this
* permission notice and warranty disclaimer appear in supporting
* documentation, and that the name of the author not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
*
* The author disclaim all warranties with regard to this
* software, including all implied warranties of merchantability
* and fitness. In no event shall the author be liable for any
* special, indirect or consequential damages or any damages
* whatsoever resulting from loss of use, data or profits, whether
* in an action of contract, negligence or other tortious action,
* arising out of or in connection with the use or performance of
* this software.
*
* --------------------------------------------------------------------------------
* Ping Library is based on the following source code:
*
* Lua RTOS, ping utility
*
*
* Author: Jaume Oliv (jolive@iberoxarxa.com / jolive@whitecatboard.org)
*
* --------------------------------------------------------------------------------
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
*/
#ifdef ESP32
#include <Arduino.h>
#include <math.h>
#include <float.h>
#include <signal.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include "esp32_ping.h"
#include "lwip/inet_chksum.h"
#include "lwip/ip.h"
#include "lwip/ip4.h"
#include "lwip/err.h"
#include "lwip/icmp.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "lwip/dns.h"
static uint16_t ping_seq_num;
static uint8_t stopped = 0;
/*
* Statistics
*/
static uint32_t transmitted = 0;
static uint32_t received = 0;
static float min_time = 0;
static float max_time = 0;
static float mean_time = 0;
static float last_mean_time = 0;
static float var_time = 0;
#define PING_ID 0xAFAF
#define PING_DEFAULT_COUNT 10
#define PING_DEFAULT_INTERVAL 1
#define PING_DEFAULT_SIZE 32
#define PING_DEFAULT_TIMEOUT 1
/*
* Helper functions
*
*/
static void ping_prepare_echo(struct icmp_echo_hdr *iecho, uint16_t len) {
size_t i;
size_t data_len = len - sizeof(struct icmp_echo_hdr);
ICMPH_TYPE_SET(iecho, ICMP_ECHO);
ICMPH_CODE_SET(iecho, 0);
iecho->chksum = 0;
iecho->id = PING_ID;
iecho->seqno = htons(++ping_seq_num);
/* fill the additional data buffer with some data */
for (i = 0; i < data_len; i++) {
((char*)iecho)[sizeof(struct icmp_echo_hdr) + i] = (char)i;
}
iecho->chksum = inet_chksum(iecho, len);
}
static err_t ping_send(int s, ip4_addr_t *addr, int size) {
struct icmp_echo_hdr *iecho;
struct sockaddr_in to;
size_t ping_size = sizeof(struct icmp_echo_hdr) + size;
int err;
iecho = (struct icmp_echo_hdr *)mem_malloc((mem_size_t)ping_size);
if (!iecho) {
return ERR_MEM;
}
ping_prepare_echo(iecho, (uint16_t)ping_size);
to.sin_len = sizeof(to);
to.sin_family = AF_INET;
inet_addr_from_ipaddr(&to.sin_addr, addr);
if ((err = sendto(s, iecho, ping_size, 0, (struct sockaddr*)&to, sizeof(to)))) {
transmitted++;
}
return (err ? ERR_OK : ERR_VAL);
}
static void ping_recv(int s) {
char buf[64];
int fromlen, len;
struct sockaddr_in from;
struct ip_hdr *iphdr;
struct icmp_echo_hdr *iecho = NULL;
char ipa[16];
struct timeval begin;
struct timeval end;
uint64_t micros_begin;
uint64_t micros_end;
float elapsed;
// Register begin time
gettimeofday(&begin, NULL);
// Send
while ((len = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*)&from, (socklen_t*)&fromlen)) > 0) {
if (len >= (int)(sizeof(struct ip_hdr) + sizeof(struct icmp_echo_hdr))) {
// Register end time
gettimeofday(&end, NULL);
/// Get from IP address
ip4_addr_t fromaddr;
inet_addr_to_ipaddr(&fromaddr, &from.sin_addr);
strcpy(ipa, inet_ntoa(fromaddr));
// Get echo
iphdr = (struct ip_hdr *)buf;
iecho = (struct icmp_echo_hdr *)(buf + (IPH_HL(iphdr) * 4));
// Print ....
if ((iecho->id == PING_ID) && (iecho->seqno == htons(ping_seq_num))) {
received++;
// Get elapsed time in milliseconds
micros_begin = begin.tv_sec * 1000000;
micros_begin += begin.tv_usec;
micros_end = end.tv_sec * 1000000;
micros_end += end.tv_usec;
elapsed = (float)(micros_end - micros_begin) / (float)1000.0;
// Update statistics
// Mean and variance are computed in an incremental way
if (elapsed < min_time) {
min_time = elapsed;
}
if (elapsed > max_time) {
max_time = elapsed;
}
last_mean_time = mean_time;
mean_time = (((received - 1) * mean_time) + elapsed) / received;
if (received > 1) {
var_time = var_time + ((elapsed - last_mean_time) * (elapsed - mean_time));
}
// Print ...
log_d("%d bytes from %s: icmp_seq=%d time=%.3f ms\r\n", len, ipa,
ntohs(iecho->seqno), elapsed
);
return;
}
else {
// TODO
}
}
}
if (len < 0) {
log_d("Request timeout for icmp_seq %d\r\n", ping_seq_num);
}
}
/*
static void stop_action(int i) {
signal(i, SIG_DFL);
stopped = 1;
}
+/
/*
* Operation functions
*
*/
void ping(const char *name, int count, int interval, int size, int timeout) {
// Resolve name
hostent * target = gethostbyname(name);
IPAddress adr = *target->h_addr_list[0];
if (target->h_length == 0) {
// TODO: error not found target?????
return;
}
ping_start(adr, count, interval, size, timeout);
}
bool ping_start(struct ping_option *ping_o) {
return ping_start(ping_o->ip,ping_o->count,0,0,0);
}
bool ping_start(IPAddress adr, int count=0, int interval=0, int size=0, int timeout=0) {
// driver_error_t *error;
struct sockaddr_in address;
ip4_addr_t ping_target;
int s;
// Get default values if argument are not provided
if (count == 0) {
count = PING_DEFAULT_COUNT;
}
if (interval == 0) {
interval = PING_DEFAULT_INTERVAL;
}
if (size == 0) {
size = PING_DEFAULT_SIZE;
}
if (timeout == 0) {
timeout = PING_DEFAULT_TIMEOUT;
}
// Create socket
if ((s = socket(AF_INET, SOCK_RAW, IP_PROTO_ICMP)) < 0) {
// TODO: error
return false;
}
address.sin_addr.s_addr = adr;
ping_target.addr = address.sin_addr.s_addr;
// Setup socket
struct timeval tout;
// Timeout
tout.tv_sec = timeout;
tout.tv_usec = 0;
if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tout, sizeof(tout)) < 0) {
closesocket(s);
// TODO: error
return false;
}
stopped = 0;
transmitted = 0;
received = 0;
min_time = 1.E+9;// FLT_MAX;
max_time = 0.0;
mean_time = 0.0;
var_time = 0.0;
// Register signal for stop ping
//signal(SIGINT, stop_action);
// Begin ping ...
char ipa[16];
strcpy(ipa, inet_ntoa(ping_target));
log_i("PING %s: %d data bytes\r\n", ipa, size);
ping_seq_num = 0;
while ((ping_seq_num < count) && (!stopped)) {
if (ping_send(s, &ping_target, size) == ERR_OK) {
ping_recv(s);
}
delay( interval*1000L);
}
closesocket(s);
log_i("%d packets transmitted, %d packets received, %.1f%% packet loss\r\n",
transmitted,
received,
((((float)transmitted - (float)received) / (float)transmitted) * 100.0)
);
if (received) {
ping_resp pingresp;
log_i("round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\r\n", min_time, mean_time, max_time, sqrt(var_time / received));
pingresp.total_count = 10;
pingresp.timeout_count = 10;
pingresp.total_bytes = 1;
pingresp.total_time = mean_time;
pingresp.ping_err = 0;
return true;
// ping_o->sent_function(ping_o, (uint8*)&pingresp);
}
return false;
}
bool ping_regist_recv(struct ping_option *ping_opt, ping_recv_function ping_recv)
{
if (ping_opt == NULL)
return false;
ping_opt->recv_function = ping_recv;
return true;
}
bool ping_regist_sent(struct ping_option *ping_opt, ping_sent_function ping_sent)
{
if (ping_opt == NULL)
return false;
ping_opt->sent_function = ping_sent;
return true;
}
#endif
+36
View File
@@ -0,0 +1,36 @@
#ifndef _PING_
#define _PING_
#include <Arduino.h>
#ifdef ESP32
typedef void(*ping_recv_function)(void* arg, void *pdata);
typedef void(*ping_sent_function)(void* arg, void *pdata);
struct ping_option {
uint32_t count;
uint32_t ip;
uint32_t coarse_time;
ping_recv_function recv_function;
ping_sent_function sent_function;
void* reverse;
};
struct ping_resp {
uint32_t total_count;
uint32_t resp_time;
uint32_t seqno;
uint32_t timeout_count;
uint32_t bytes;
uint32_t total_bytes;
uint32_t total_time;
int8_t ping_err;
};
bool ping_start(struct ping_option *ping_opt);
void ping(const char *name, int count, int interval, int size, int timeout);
bool ping_start(IPAddress adr, int count, int interval, int size, int timeout);
#endif
#endif
@@ -20,6 +20,7 @@
#ifndef ESP8266Ping_H
#define ESP8266Ping_H
#if defined(ESP8266)
#include <Arduino.h>
#include <ESP8266WiFi.h>
@@ -57,3 +58,4 @@ class PingClass {
PingClass Ping;
#endif
#endif
@@ -17,6 +17,7 @@
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
extern "C" void esp_schedule();
extern "C" void esp_yield();
+45
View File
@@ -168,6 +168,51 @@ void ICACHE_FLASH_ATTR IRsend::sendNEC (unsigned long data, int nbits,
}
}
void ICACHE_FLASH_ATTR IRsend::sendPioneer (unsigned long data, int nbits,
unsigned int repeat, unsigned long secondData) {
// Details about timings can be found at:
// http://www.sbprojects.com/knowledge/ir/nec.php
// More about the pioneer format:
// http://www.adrian-kingston.com/IRFormatPioneer.htm
// Set IR carrier frequency
enableIROut(40);
IRtimer usecs = IRtimer();
for (unsigned int i = 0; i <= repeat; i++) {
usecs.reset();
// Header
mark(PIONEER_HDR_MARK);
space(PIONEER_HDR_SPACE);
sendData(PIONEER_BIT_MARK, PIONEER_ONE_SPACE, PIONEER_BIT_MARK, PIONEER_ZERO_SPACE,
data, nbits, true);
// Footer
mark(PIONEER_BIT_MARK);
space(PIONEER_ONE_SPACE);
// Gap till next command.
space(max(0ul, PIONEER_MIN_COMMAND_LENGTH - usecs.elapsed()));
// Some Pioneer signals have two 32 bit commands
if (secondData) {
usecs.reset();
// Header
mark(PIONEER_HDR_MARK);
space(PIONEER_HDR_SPACE);
sendData(PIONEER_BIT_MARK, PIONEER_ONE_SPACE, PIONEER_BIT_MARK, PIONEER_ZERO_SPACE,
secondData, nbits, true);
// Footer
mark(PIONEER_BIT_MARK);
space(PIONEER_ONE_SPACE);
// Gap till next command.
space(max(0ul, PIONEER_MIN_COMMAND_LENGTH - usecs.elapsed()));
}
}
}
void ICACHE_FLASH_ATTR IRsend::sendLG (unsigned long data, int nbits,
unsigned int repeat) {
// Args:
+4
View File
@@ -53,6 +53,7 @@ enum decode_type_t {
RC5,
RC6,
NEC,
PIONEER,
SONY,
PANASONIC,
JVC,
@@ -92,6 +93,7 @@ public:
#define REPEAT 0xffffffff
#define SEND_PROTOCOL_NEC case NEC: sendNEC(data, nbits); break;
#define SEND_PROTOCOL_PIONEER case PIONEER: sendPioneer(data, nbits, 1, 0ul); break;
#define SEND_PROTOCOL_SONY case SONY: sendSony(data, nbits); break;
#define SEND_PROTOCOL_RC5 case RC5: sendRC5(data, nbits); break;
#define SEND_PROTOCOL_RC6 case RC6: sendRC6(data, nbits); break;
@@ -162,6 +164,7 @@ public:
void send(int type, unsigned long data, int nbits) {
switch (type) {
SEND_PROTOCOL_NEC
SEND_PROTOCOL_PIONEER
SEND_PROTOCOL_SONY
SEND_PROTOCOL_RC5
SEND_PROTOCOL_RC6
@@ -179,6 +182,7 @@ public:
void sendCOOLIX(unsigned long data, int nbits);
void sendWhynter(unsigned long data, int nbits);
void sendNEC(unsigned long data, int nbits=32, unsigned int repeat=0);
void sendPioneer(unsigned long data, int nbits=32, unsigned int repeat=0, unsigned long secondData=0ul);
void sendLG(unsigned long data, int nbits=28, unsigned int repeat=0);
// sendSony() should typically be called with repeat=2 as Sony devices
// expect the code to be sent at least 3 times. (code + 2 repeats = 3 codes)
+8
View File
@@ -60,6 +60,14 @@
#define NEC_RPT_SPACE 2250
#define NEC_MIN_COMMAND_LENGTH 108000UL
#define PIONEER_HDR_MARK 8000
#define PIONEER_HDR_SPACE 4000
#define PIONEER_BIT_MARK 500
#define PIONEER_ONE_SPACE 1500
#define PIONEER_ZERO_SPACE 500
#define PIONEER_RPT_SPACE 2250
#define PIONEER_MIN_COMMAND_LENGTH 90000UL
// Timings based on http://www.sbprojects.com/knowledge/ir/sirc.php
#define SONY_HDR_MARK 2400
#define SONY_HDR_SPACE 600
+116 -29
View File
@@ -25,7 +25,7 @@
#include "jkSDS011.h"
CjkSDS011::CjkSDS011(int16_t pinRX, int16_t pinTX) : _serial(pinRX, pinTX)
CjkSDS011::CjkSDS011(int16_t pinRX, int16_t pinTX)
{
_sws = ! ( pinRX < 0 || pinRX == 3 );
_pm2_5 = NAN;
@@ -35,43 +35,131 @@ CjkSDS011::CjkSDS011(int16_t pinRX, int16_t pinTX) : _serial(pinRX, pinTX)
_pm10_avr = 0;
_avr = 0;
_data.SetPacketLength(10);
_command.SetPacketLength(19);
_working_period = -1;
_sleepmode_active = false;
_serial = new ESPeasySoftwareSerial(pinRX, pinTX);
_serial->begin(9600);
}
_serial.begin(9600);
CjkSDS011::~CjkSDS011() {
delete _serial;
}
void CjkSDS011::SendCommand(byte byte1, byte byte2, byte byte3) {
_command[0] = 0xAA; // Head
_command[1] = 0xB4; // Command ID
_command[2] = byte1; // Data Byte 1
_command[3] = byte2; // Data Byte 2
_command[4] = byte3; // Data Byte 3
_command[5] = 0; // Data Byte 4
_command[6] = 0; // Data Byte 5
_command[7] = 0; // Data Byte 6
_command[8] = 0; // Data Byte 7
_command[9] = 0; // Data Byte 8
_command[10] = 0; // Data Byte 9
_command[11] = 0; // Data Byte 10
_command[12] = 0; // Data Byte 11
_command[13] = 0; // Data Byte 12
_command[14] = 0; // Data Byte 13
_command[15] = 0xFF; // Device ID byte 1, FF: All sensor response
_command[16] = 0xFF; // Device ID byte 2, FF: All sensor response
byte checksum = 0;
for (byte i=2; i< 17; ++i) {
checksum += _command[i];
}
_command[17] = checksum; // Checksum
_command[18] = 0xAB; // Tail
for (int i = 0; i < 19; ++i) {
_serial->write(_command[i]);
}
}
void CjkSDS011::SetSleepMode(bool enabled) {
byte databyte3 = enabled ? 0 : 1;
SendCommand(6, 1, databyte3);
}
void CjkSDS011::SetWorkingPeriod(int minutes) {
// Data byte 1: 8
// Data byte 2: 0: query the current mode
// 1: set mode
// Data byte 3: 0continuous(default)
// 1-30minutework 30 seconds and sleep n*60-30 seconds
if (minutes < 0 || minutes > 30) return;
// Working period is stored in the flash of the sensor. Only write to change.
const int currentWorkingPeriod = GetWorkingPeriod();
if (minutes != currentWorkingPeriod)
SendCommand(8, 1, minutes);
}
int CjkSDS011::GetWorkingPeriod() {
// Data byte 1: 8
// Data byte 2: 0: query the current mode
// 1: set mode
// Data byte 3: 0continuous(default)
// 1-30minutework 30 seconds and sleep n*60-30 seconds
SendCommand(8, 0, 0);
Process();
return _working_period;
}
void CjkSDS011::ParseCommandReply() {
switch(_data[2]) {
case 6: // Enable/Disable sleep mode.
if (_data[3] == 0)
_sleepmode_active = _data[4];
break;
case 8: // Set/Get working period
if (_data[3] == 0)
_working_period = _data[4];
break;
default:
// Not implemented.
break;
}
}
void CjkSDS011::Process()
{
while (_serial.available())
while (_serial->available())
{
_data.AddData(_serial.read());
_data.AddData(_serial->read());
if (_data[0] == 0xAA && _data[9] == 0xAB && (_data[1] == 0xC0 || _data[1] == 0xCF)) // correct packet frame?
if (_data[0] == 0xAA && _data[9] == 0xAB) // correct packet frame?
{
byte checksum = 0;
for (byte i=2; i<= 7; i++)
checksum += _data[i];
checksum += _data[i];
if (checksum != _data[8])
continue;
if (_data[1] == 0xC0) // SDS011 or SDS018?
{
_pm2_5 = (float)((_data[3] << 8) | _data[2]) * 0.1;
_pm10_ = (float)((_data[5] << 8) | _data[4]) * 0.1;
_available = true;
switch(_data[1]) {
case 0xC0: // SDS011 or SDS018?
_pm2_5 = (float)((_data[3] << 8) | _data[2]) * 0.1;
_pm10_ = (float)((_data[5] << 8) | _data[4]) * 0.1;
_available = true;
break;
case 0xCF: // SDS198?
_pm2_5 = (float)((_data[5] << 8) | _data[4]);
_pm10_ = (float)((_data[3] << 8) | _data[2]);
_available = true;
break;
case 0xC5: // Reply on command ID 0xB4
ParseCommandReply();
break;
default:
break;
}
else if (_data[1] == 0xCF) // SDS198?
{
_pm2_5 = (float)((_data[5] << 8) | _data[4]);
_pm10_ = (float)((_data[3] << 8) | _data[2]);
_available = true;
if (_available) {
_pm2_5avr += _pm2_5;
_pm10_avr += _pm10_;
_avr++;
_data.Clear();
return;
}
else
continue;
_pm2_5avr += _pm2_5;
_pm10_avr += _pm10_;
_avr++;
return;
}
}
}
@@ -83,7 +171,7 @@ boolean CjkSDS011::available()
return ret;
}
void CjkSDS011::ReadAverage(float &pm25, float &pm10)
boolean CjkSDS011::ReadAverage(float &pm25, float &pm10)
{
if (_avr)
{
@@ -92,10 +180,9 @@ void CjkSDS011::ReadAverage(float &pm25, float &pm10)
_pm2_5avr = 0;
_pm10_avr = 0;
_avr = 0;
return true;
}
else
{
pm25 = NAN;
pm10 = NAN;
}
pm25 = NAN;
pm10 = NAN;
return false;
}
+24 -3
View File
@@ -27,13 +27,15 @@
#define _jkSDS011_H_
#include "Arduino.h"
#include "SensorSerial.h"
//#include "SensorSerial.h"
#include "SensorSerialBuffer.h"
#include "ESPeasySoftwareSerial.h"
class CjkSDS011
{
public:
CjkSDS011(int16_t pinRX, int16_t pinTX);
virtual ~CjkSDS011();
void Process();
@@ -42,11 +44,28 @@ public:
float GetPM2_5() { return _pm2_5; };
float GetPM10_() { return _pm10_; };
void ReadAverage(float &pm25, float &pm10);
// Return true when there are valid samples.
boolean ReadAverage(float &pm25, float &pm10);
void SetSleepMode(bool enabled);
// Set interval to get new data, 0 .. 30 minutes.
// Minutes = 0 => continous mode.
// The setting is still effective after power off(factory default is continuous measurement)
void SetWorkingPeriod(int minutes);
// Get the working period in minutes (0 = continuous reading)
// Negative return value indicates error during communication.
int GetWorkingPeriod();
private:
SensorSerial _serial;
void SendCommand(byte byte1, byte byte2, byte byte3);
void ParseCommandReply();
// SensorSerial _serial;
ESPeasySoftwareSerial *_serial;
CSensorSerialBuffer _data;
CSensorSerialBuffer _command;
float _pm2_5;
float _pm10_;
float _pm2_5avr;
@@ -54,6 +73,8 @@ private:
uint16_t _avr;
boolean _available;
boolean _sws;
int _working_period;
boolean _sleepmode_active;
};
#endif
@@ -22,10 +22,6 @@ SOFTWARE.
See more at http://blog.squix.ch
*/
#ifndef DIALOG_PLAIN_FONT_H
#define DIALOG_PLAIN_FONT_H
// OLED library version >= 3.0.0
// Created by http://oleddisplay.squix.ch/ Consider a donation
// In case of problems make sure that you are using the font file with the correct version!
@@ -485,6 +481,3 @@ const char Dialog_plain_12[] PROGMEM = {
0x00,0x00,0xFC,0x7F,0x40,0x04,0x20,0x08,0x20,0x08,0x60,0x0C,0xC0,0x07, // 254
0x00,0x00,0xE0,0x40,0x04,0x47,0x00,0x38,0x84,0x07,0xE0 // 255
};
#endif
@@ -1,6 +1,3 @@
#ifndef OLED_SSD1306_SH1106_IMAGES_H
#define OLED_SSD1306_SH1106_IMAGES_H
#define espeasy_logo_width 36
#define espeasy_logo_height 36
const char espeasy_logo_bits[] PROGMEM= {
@@ -41,5 +38,3 @@ const char inactiveSymbole[] PROGMEM = {
B00000000,
B00000000
};
#endif
+10
View File
@@ -125,6 +125,16 @@ board = esp12e
upload_speed=460800
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D PLUGIN_BUILD_TESTING -D PLUGIN_BUILD_DEV
#version with additional plugins (and dependend code) that is in development (probably broken or incomplete) 4096k
# Use latest ESP8266 core 2.4.0
[env:dev_ESP8266_4096_core2_4_0]
platform = espressif8266
framework = arduino
board = esp12e
upload_speed=460800
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D PLUGIN_BUILD_TESTING -D PLUGIN_BUILD_DEV
#version with additional plugins (and dependend code) that is in development (probably broken or incomplete) 4096k for esp8285
[env:dev_ESP8285_1024]
platform = espressif8266@1.5.0
+62 -37
View File
@@ -42,6 +42,7 @@ bool safeReadStringUntil(Stream &input, String &str, char terminator, unsigned i
#define INPUT_COMMAND_SIZE 80
void ExecuteCommand(byte source, const char *Line)
{
checkRAM(F("ExecuteCommand"));
String status = "";
boolean success = false;
char TmpStr1[80];
@@ -127,7 +128,7 @@ void ExecuteCommand(byte source, const char *Line)
SendUDPCommand(Par1, (char*)event.c_str(), event.length());
}
}
#ifdef FEATURE_SD
if (strcasecmp_P(Command, PSTR("sdcard")) == 0)
{
success = true;
@@ -146,6 +147,7 @@ void ExecuteCommand(byte source, const char *Line)
Serial.println(fname.c_str());
SD.remove((char*)fname.c_str());
}
#endif
if (strcasecmp_P(Command, PSTR("lowmem")) == 0)
{
@@ -178,6 +180,21 @@ void ExecuteCommand(byte source, const char *Line)
delay(60000);
}
if (strcasecmp_P(Command, PSTR("accessinfo")) == 0)
{
success = true;
Serial.print(F("Allowed IP range : "));
Serial.println(describeAllowedIPrange());
}
if (strcasecmp_P(Command, PSTR("clearaccessblock")) == 0)
{
success = true;
clearAccessBlock();
Serial.print(F("Allowed IP range : "));
Serial.println(describeAllowedIPrange());
}
if (strcasecmp_P(Command, PSTR("meminfo")) == 0)
{
success = true;
@@ -429,41 +446,42 @@ void ExecuteCommand(byte source, const char *Line)
}
}
// ****************************************
// special commands for Blynk
// ****************************************
#ifdef CPLUGIN_012
//FIXME: this should go to PLUGIN_WRITE in _C012.ino
if (strcasecmp_P(Command, PSTR("BlynkGet")) == 0)
{
byte first_enabled_blynk_controller = firstEnabledBlynkController();
if (first_enabled_blynk_controller == -1) {
status = F("Controller not enabled");
} else {
String strLine = Line;
strLine = strLine.substring(9);
int index = strLine.indexOf(',');
if (index > 0)
{
int index = strLine.lastIndexOf(',');
String blynkcommand = strLine.substring(index+1);
float value = 0;
if (Blynk_get(blynkcommand, first_enabled_blynk_controller, &value))
{
UserVar[(VARS_PER_TASK * (Par1 - 1)) + Par2 - 1] = value;
}
else
status = F("Error getting data");
}
else
{
if (!Blynk_get(strLine, first_enabled_blynk_controller))
{
status = F("Error getting data");
}
}
}
}
// ****************************************
// special commands for Blynk
// ****************************************
#ifdef CPLUGIN_012
//FIXME: this should go to PLUGIN_WRITE in _C012.ino
if (strcasecmp_P(Command, PSTR("BlynkGet")) == 0)
{
byte first_enabled_blynk_controller = firstEnabledBlynkController();
if (first_enabled_blynk_controller == -1) {
status = F("Controller not enabled");
} else {
String strLine = Line;
strLine = strLine.substring(9);
int index = strLine.indexOf(',');
if (index > 0)
{
int index = strLine.lastIndexOf(',');
String blynkcommand = strLine.substring(index+1);
float value = 0;
if (Blynk_get(blynkcommand, first_enabled_blynk_controller, &value))
{
UserVar[(VARS_PER_TASK * (Par1 - 1)) + Par2 - 1] = value;
}
else
status = F("Error getting data");
}
else
{
if (!Blynk_get(strLine, first_enabled_blynk_controller))
{
status = F("Error getting data");
}
}
}
}
#endif
// ****************************************
@@ -542,7 +560,12 @@ void ExecuteCommand(byte source, const char *Line)
pinMode(0, INPUT);
pinMode(2, INPUT);
pinMode(15, INPUT);
ESP.reset();
#if defined(ESP8266)
ESP.reset();
#endif
#if defined(ESP32)
ESP.restart();
#endif
}
if (strcasecmp_P(Command, PSTR("Restart")) == 0)
@@ -628,6 +651,7 @@ void ExecuteCommand(byte source, const char *Line)
yield();
}
#ifdef FEATURE_SD
void printDirectory(File dir, int numTabs) {
while (true) {
@@ -651,3 +675,4 @@ void printDirectory(File dir, int numTabs) {
entry.close();
}
}
#endif
+7 -3
View File
@@ -3,10 +3,14 @@
//********************************************************************************
void sendData(struct EventStruct *event)
{
LoadTaskSettings(event->TaskIndex);
checkRAM(F("sendData"));
LoadTaskSettings(event->TaskIndex);
if (Settings.UseRules)
createRuleEvents(event->TaskIndex);
if (Settings.GlobalSync && Settings.TaskDeviceGlobalSync[event->TaskIndex])
SendUDPTaskData(0, event->TaskIndex, event->TaskIndex);
if (Settings.UseValueLogger && Settings.InitSPI && Settings.Pin_sd_cs >= 0)
SendValueLogger(event->TaskIndex);
@@ -134,7 +138,7 @@ bool MQTTConnect(int controller_idx)
String LWTTopic = ControllerSettings.Subscribe;
LWTTopic.replace(F("/#"), F("/status"));
parseSystemVariables(LWTTopic, false);
LWTTopic.replace(F("%sysname%"), Settings.Name);
LWTTopic += F("/LWT"); // Extend the topic for status updates of connected/disconnected status.
boolean MQTTresult = false;
@@ -243,7 +247,7 @@ void MQTTStatus(String& status)
LoadControllerSettings(enabledMqttController, (byte*)&ControllerSettings, sizeof(ControllerSettings));
String pubname = ControllerSettings.Subscribe;
pubname.replace(F("/#"), F("/status"));
parseSystemVariables(pubname, false);
pubname.replace(F("%sysname%"), Settings.Name);
MQTTpublish(enabledMqttController, pubname.c_str(), status.c_str(),Settings.MQTTRetainFlag);
}
}
-985
View File
@@ -1,985 +0,0 @@
#ifndef ESPEASY_GLOBALS_H_
#define ESPEASY_GLOBALS_H_
// ********************************************************************************
// User specific configuration
// ********************************************************************************
// Set default configuration settings if you want (not mandatory)
// You can always change these during runtime and save to eeprom
// After loading firmware, issue a 'reset' command to load the defaults.
// --- Basic Config Settings ------------------------------------------------------------------------
#define DEFAULT_NAME "ESP_Easy" // Enter your device friendly name
#define UNIT 0 // Unit Number
#define DEFAULT_DELAY 60 // Sleep Delay in seconds
// --- Wifi AP Mode (when your Wifi Network is not reachable) ----------------------------------------
#define DEFAULT_AP_IP 192,168,4,1 // Enter IP address (comma separated) for AP (config) mode
#define DEFAULT_AP_KEY "configesp" // Enter network WPA key for AP (config) mode
// --- Wifi Client Mode -----------------------------------------------------------------------------
#define DEFAULT_SSID "ssid" // Enter your Wifi network SSID
#define DEFAULT_KEY "wpakey" // Enter your Wifi network WPA key
#define DEFAULT_USE_STATIC_IP false // (true|false) enabled or disabled static IP
#define DEFAULT_IP "192.168.0.50" // Enter your IP address
#define DEFAULT_DNS "192.168.0.1" // Enter your DNS
#define DEFAULT_GW "192.168.0.1" // Enter your Gateway
#define DEFAULT_SUBNET "255.255.255.0" // Enter your Subnet
#define DEFAULT_WIFI_CONNECTION_TIMEOUT 10000 // minimum timeout in ms for WiFi to be connected.
// --- Default Controller ------------------------------------------------------------------------------
#define DEFAULT_CONTROLLER false // true or false enabled or disabled, set 1st controller defaults
// using a default template, you also need to set a DEFAULT PROTOCOL to a suitable MQTT protocol !
#define DEFAULT_PUB "sensors/espeasy/%sysname%/%tskname%/%valname%" // Enter your pub
#define DEFAULT_SUB "sensors/espeasy/%sysname%/#" // Enter your sub
#define DEFAULT_SERVER "192.168.0.8" // Enter your Server IP address
#define DEFAULT_PORT 8080 // Enter your Server port value
#define DEFAULT_PROTOCOL 1 // Protocol used for controller communications
// 1 = Domoticz HTTP
// 2 = Domoticz MQTT
// 3 = Nodo Telnet
// 4 = ThingSpeak
// 5 = OpenHAB MQTT
// 6 = PiDome MQTT
// 7 = EmonCMS
// 8 = Generic HTTP
// 9 = FHEM HTTP
// --- Advanced Settings ---------------------------------------------------------------------------------
#define DEFAULT_USE_RULES false // (true|false) Enable Rules?
#define DEFAULT_MQTT_RETAIN false // (true|false) Retain MQTT messages?
#define DEFAULT_MQTT_DELAY 1000 // Time in milliseconds to retain MQTT messages
#define DEFAULT_USE_NTP false // (true|false) Use NTP Server
#define DEFAULT_NTP_HOST "" // NTP Server Hostname
#define DEFAULT_TIME_ZONE 0 // Time Offset (in minutes)
#define DEFAULT_USE_DST false // (true|false) Use Daily Time Saving
#define LOG_TO_SERIAL 1
#define LOG_TO_SYSLOG 2
#define LOG_TO_WEBLOG 3
#define LOG_TO_SDCARD 4
#define DEFAULT_SYSLOG_IP "" // Syslog IP Address
#define DEFAULT_SYSLOG_LEVEL 0 // Syslog Log Level
#define DEFAULT_SERIAL_LOG_LEVEL LOG_LEVEL_INFO // Serial Log Level
#define DEFAULT_WEB_LOG_LEVEL LOG_LEVEL_INFO // Web Log Level
#define DEFAULT_SD_LOG_LEVEL 0 // SD Card Log Level
#define DEFAULT_USE_SD_LOG false // (true|false) Enable Logging to the SD card
#define DEFAULT_USE_SERIAL true // (true|false) Enable Logging to the Serial Port
#define DEFAULT_SERIAL_BAUD 115200 // Serial Port Baud Rate
/*
// --- Experimental Advanced Settings (NOT ACTIVES at this time) ------------------------------------
#define DEFAULT_USE_GLOBAL_SYNC false // (true|false)
#define DEFAULT_SYNC_UDP_PORT 0 //
#define DEFAULT_IP_OCTET 0 //
#define DEFAULT_WD_IC2_ADDRESS 0 //
#define DEFAULT_USE_SSDP false // (true|false)
#define DEFAULT_CON_FAIL_THRES 0 //
#define DEFAULT_I2C_CLOCK_LIMIT 0 //
*/
// Enable FEATURE_ADC_VCC to measure supply voltage using the analog pin
// Please note that the TOUT pin has to be disconnected in this mode
// Use the "System Info" device to read the VCC value
#ifndef FEATURE_ADC_VCC
#define FEATURE_ADC_VCC false
#endif
//enable Arduino OTA updating.
//Note: This adds around 10kb to the firmware size, and 1kb extra ram.
// #define FEATURE_ARDUINO_OTA
//enable mDNS mode (adds about 6kb ram and some bytes IRAM)
// #define FEATURE_MDNS
//enable reporting status to ESPEasy developers.
//this informs us of crashes and stability issues.
// not finished yet!
// #define FEATURE_REPORTING
//Select which plugin sets you want to build.
//These are normally automaticly set via the Platformio build environment.
//If you use ArduinoIDE you might need to uncomment some of them, depending on your needs
//If you dont select any, a version with a minimal number of plugins will be biult for 512k versions.
//(512k is NOT finsihed or tested yet as of v2.0.0-dev6)
//build all the normal stable plugins (on by default)
#define PLUGIN_BUILD_NORMAL
//build all plugins that are in test stadium
//#define PLUGIN_BUILD_TESTING
//build all plugins that still are being developed and are broken or incomplete
//#define PLUGIN_BUILD_DEV
// ********************************************************************************
// DO NOT CHANGE ANYTHING BELOW THIS LINE
// ********************************************************************************
#include "core_version.h"
#ifndef ARDUINO_ESP8266_RELEASE_2_3_0
#error ESPEasy v2.0 only support Arduino core 2.3.0. (Use the ESPEasy development branch to fix this)
#endif
#define ESP_PROJECT_PID 2016110801L
#define VERSION 2 // config file version (not ESPEasy version). increase if you make incompatible changes to config system.
#define BUILD 20000 // git version 2.0.0
#define BUILD_NOTES " - Mega"
#ifndef BUILD_GIT
#define BUILD_GIT "(custom)"
#endif
#define MAX_FLASHWRITES_PER_DAY 100 // per 24 hour window
#define NODE_TYPE_ID_ESP_EASY_STD 1
#define NODE_TYPE_ID_ESP_EASYM_STD 17
#define NODE_TYPE_ID_ESP_EASY32_STD 33
#define NODE_TYPE_ID_ARDUINO_EASY_STD 65
#define NODE_TYPE_ID_NANO_EASY_STD 81
#define NODE_TYPE_ID NODE_TYPE_ID_ESP_EASYM_STD
#define PLUGIN_INIT_ALL 1
#define PLUGIN_INIT 2
#define PLUGIN_READ 3
#define PLUGIN_ONCE_A_SECOND 4
#define PLUGIN_TEN_PER_SECOND 5
#define PLUGIN_DEVICE_ADD 6
#define PLUGIN_EVENTLIST_ADD 7
#define PLUGIN_WEBFORM_SAVE 8
#define PLUGIN_WEBFORM_LOAD 9
#define PLUGIN_WEBFORM_SHOW_VALUES 10
#define PLUGIN_GET_DEVICENAME 11
#define PLUGIN_GET_DEVICEVALUENAMES 12
#define PLUGIN_WRITE 13
#define PLUGIN_EVENT_OUT 14
#define PLUGIN_WEBFORM_SHOW_CONFIG 15
#define PLUGIN_SERIAL_IN 16
#define PLUGIN_UDP_IN 17
#define PLUGIN_CLOCK_IN 18
#define PLUGIN_TIMER_IN 19
#define PLUGIN_FIFTY_PER_SECOND 20
#define PLUGIN_SET_CONFIG 21
#define PLUGIN_GET_DEVICEGPIONAMES 22
#define PLUGIN_EXIT 23
#define PLUGIN_GET_CONFIG 24
#define CPLUGIN_PROTOCOL_ADD 1
#define CPLUGIN_PROTOCOL_TEMPLATE 2
#define CPLUGIN_PROTOCOL_SEND 3
#define CPLUGIN_PROTOCOL_RECV 4
#define CPLUGIN_GET_DEVICENAME 5
#define CPLUGIN_WEBFORM_SAVE 6
#define CPLUGIN_WEBFORM_LOAD 7
#define CPLUGIN_GET_PROTOCOL_DISPLAY_NAME 8
#define CPLUGIN_TASK_CHANGE_NOTIFICATION 9
#define CPLUGIN_INIT 10
#define CPLUGIN_UDP_IN 11
#define CONTROLLER_HOSTNAME 1
#define CONTROLLER_IP 2
#define CONTROLLER_PORT 3
#define CONTROLLER_USER 4
#define CONTROLLER_PASS 5
#define CONTROLLER_SUBSCRIBE 6
#define CONTROLLER_PUBLISH 7
#define NPLUGIN_PROTOCOL_ADD 1
#define NPLUGIN_GET_DEVICENAME 2
#define NPLUGIN_WEBFORM_SAVE 3
#define NPLUGIN_WEBFORM_LOAD 4
#define NPLUGIN_WRITE 5
#define NPLUGIN_NOTIFY 6
#define NPLUGIN_NOT_FOUND 255
#define LOG_LEVEL_ERROR 1
#define LOG_LEVEL_INFO 2
#define LOG_LEVEL_DEBUG 3
#define LOG_LEVEL_DEBUG_MORE 4
#define LOG_LEVEL_DEBUG_DEV 9 // use for testing/debugging only, not for regular use
#define CMD_REBOOT 89
#define CMD_WIFI_DISCONNECT 135
#if defined(PLUGIN_BUILD_TESTING) || defined(PLUGIN_BUILD_DEV)
#define DEVICES_MAX 72
#else
#define DEVICES_MAX 64
#endif
#if defined(ESP8266)
#define TASKS_MAX 12 // max 12!
#endif
#if defined(ESP32)
#define TASKS_MAX 32
#endif
#define CONTROLLER_MAX 3 // max 4!
#define NOTIFICATION_MAX 3 // max 4!
#define VARS_PER_TASK 4
#define PLUGIN_MAX DEVICES_MAX
#define PLUGIN_CONFIGVAR_MAX 8
#define PLUGIN_CONFIGFLOATVAR_MAX 4
#define PLUGIN_CONFIGLONGVAR_MAX 4
#define PLUGIN_EXTRACONFIGVAR_MAX 16
#define CPLUGIN_MAX 16
#define NPLUGIN_MAX 4
#define UNIT_MAX 32 // Only relevant for UDP unicast message 'sweeps' and the nodelist.
#define RULES_TIMER_MAX 8
#define SYSTEM_TIMER_MAX 8
#define SYSTEM_CMD_TIMER_MAX 2
#define PINSTATE_TABLE_MAX 32
#define RULES_MAX_SIZE 2048
#define RULES_MAX_NESTING_LEVEL 3
#define RULESETS_MAX 4
#define RULES_BUFFER_SIZE 64
#define PIN_MODE_UNDEFINED 0
#define PIN_MODE_INPUT 1
#define PIN_MODE_OUTPUT 2
#define PIN_MODE_PWM 3
#define PIN_MODE_SERVO 4
#define SEARCH_PIN_STATE true
#define NO_SEARCH_PIN_STATE false
#define DEVICE_TYPE_SINGLE 1 // connected through 1 datapin
#define DEVICE_TYPE_DUAL 2 // connected through 2 datapins
#define DEVICE_TYPE_TRIPLE 3 // connected through 3 datapins
#define DEVICE_TYPE_ANALOG 10 // AIN/tout pin
#define DEVICE_TYPE_I2C 20 // connected through I2C
#define DEVICE_TYPE_DUMMY 99 // Dummy device, has no physical connection
#define SENSOR_TYPE_SINGLE 1
#define SENSOR_TYPE_TEMP_HUM 2
#define SENSOR_TYPE_TEMP_BARO 3
#define SENSOR_TYPE_TEMP_HUM_BARO 4
#define SENSOR_TYPE_DUAL 5
#define SENSOR_TYPE_TRIPLE 6
#define SENSOR_TYPE_QUAD 7
#define SENSOR_TYPE_SWITCH 10
#define SENSOR_TYPE_DIMMER 11
#define SENSOR_TYPE_LONG 20
#define SENSOR_TYPE_WIND 21
#define VALUE_SOURCE_SYSTEM 1
#define VALUE_SOURCE_SERIAL 2
#define VALUE_SOURCE_HTTP 3
#define VALUE_SOURCE_MQTT 4
#define VALUE_SOURCE_UDP 5
#define BOOT_CAUSE_MANUAL_REBOOT 0
#define BOOT_CAUSE_COLD_BOOT 1
#define BOOT_CAUSE_DEEP_SLEEP 2
#define BOOT_CAUSE_EXT_WD 10
#define DAT_TASKS_SIZE 2048
#define DAT_TASKS_CUSTOM_OFFSET 1024
#define DAT_CUSTOM_CONTROLLER_SIZE 1024
#define DAT_CONTROLLER_SIZE 1024
#define DAT_NOTIFICATION_SIZE 1024
#define DAT_OFFSET_TASKS 4096 // each task = 2k, (1024 basic + 1024 bytes custom), 12 max
#define DAT_OFFSET_CONTROLLER 28672 // each controller = 1k, 4 max
#define DAT_OFFSET_CUSTOM_CONTROLLER 32768 // each custom controller config = 1k, 4 max.
/*
To modify the stock configuration without changing this repo file :
- define USE_CUSTOM_H as a build flags. ie : export PLATFORMIO_BUILD_FLAGS="'-DUSE_CUSTOM_H'"
- add a "Custom.h" file in this folder.
*/
#ifdef USE_CUSTOM_H
#include "Custom.h"
#endif
#define FILE_CONFIG "config.dat"
#define FILE_SECURITY "security.dat"
#define FILE_NOTIFICATION "notification.dat"
#define FILE_RULES "rules1.dat"
#include "ESPEasyTimeTypes.h"
#include "lwip/tcp_impl.h"
#include <ESP8266WiFi.h>
#include <ESP8266Ping.h>
#include <DNSServer.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#ifdef FEATURE_MDNS
#include <ESP8266mDNS.h>
#endif
#include <Wire.h>
#include <SPI.h>
#include <PubSubClient.h>
// #include <ArduinoJson.h>
// #include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define FS_NO_GLOBALS
#include <FS.h>
#include <SD.h>
#include <ESP8266HTTPUpdateServer.h>
ESP8266HTTPUpdateServer httpUpdater(true);
#include <base64.h>
#if FEATURE_ADC_VCC
ADC_MODE(ADC_VCC);
#endif
#ifndef LWIP_OPEN_SRC
#define LWIP_OPEN_SRC
#endif
#include "lwip/opt.h"
#include "lwip/udp.h"
#include "lwip/igmp.h"
#include "include/UdpContext.h"
#include "limits.h"
extern "C" {
#include "user_interface.h"
}
#ifdef FEATURE_ARDUINO_OTA
#include <ArduinoOTA.h>
#include <ESP8266mDNS.h>
bool ArduinoOTAtriggered=false;
#endif
// Setup DNS, only used if the ESP has no valid WiFi config
const byte DNS_PORT = 53;
IPAddress apIP(DEFAULT_AP_IP);
DNSServer dnsServer;
#ifdef FEATURE_MDNS
MDNSResponder mdns;
#endif
// MQTT client
WiFiClient mqtt;
PubSubClient MQTTclient(mqtt);
bool MQTTclient_should_reconnect = true;
// WebServer
ESP8266WebServer WebServer(80);
// udp protocol stuff (syslog, global sync, node info list, ntp time)
WiFiUDP portUDP;
// Forward declarations.
bool WiFiConnected(uint32_t timeout_ms);
bool hostReachable(const IPAddress& ip);
bool hostReachable(const String& hostname);
extern "C" {
#include "spi_flash.h"
}
extern "C" uint32_t _SPIFFS_start;
extern "C" uint32_t _SPIFFS_end;
extern "C" uint32_t _SPIFFS_page;
extern "C" uint32_t _SPIFFS_block;
struct SecurityStruct
{
SecurityStruct() {
memset(WifiSSID, 0, sizeof(WifiSSID));
memset(WifiKey, 0, sizeof(WifiKey));
memset(WifiSSID2, 0, sizeof(WifiSSID2));
memset(WifiKey2, 0, sizeof(WifiKey2));
memset(WifiAPKey, 0, sizeof(WifiAPKey));
for (byte i = 0; i < CONTROLLER_MAX; ++i) {
memset(ControllerUser[i], 0, sizeof(ControllerUser[i]));
memset(ControllerPassword[i], 0, sizeof(ControllerPassword[i]));
}
memset(Password, 0, sizeof(Password));
}
char WifiSSID[32];
char WifiKey[64];
char WifiSSID2[32];
char WifiKey2[64];
char WifiAPKey[64];
char ControllerUser[CONTROLLER_MAX][26];
char ControllerPassword[CONTROLLER_MAX][64];
char Password[26];
//its safe to extend this struct, up to 4096 bytes, default values in config are 0
} SecuritySettings;
struct SettingsStruct
{
SettingsStruct() :
PID(0), Version(0), Build(0), IP_Octet(0), Unit(0), Delay(0),
Pin_i2c_sda(-1), Pin_i2c_scl(-1), Pin_status_led(-1), Pin_sd_cs(-1),
UDPPort(0), SyslogLevel(0), SerialLogLevel(0), WebLogLevel(0), SDLogLevel(0),
BaudRate(0), MessageDelay(0), deepSleep(0),
CustomCSS(false), DST(false), WDI2CAddress(0),
UseRules(false), UseSerial(false), UseSSDP(false), UseNTP(false),
WireClockStretchLimit(0), ConnectionFailuresThreshold(0),
TimeZone(0), MQTTRetainFlag(false), InitSPI(false),
Pin_status_led_Inversed(false), deepSleepOnFail(false), UseValueLogger(false),
DST_Start(0), DST_End(0)
{
for (byte i = 0; i < CONTROLLER_MAX; ++i) {
Protocol[i] = 0;
ControllerEnabled[i] = false;
for (byte task = 0; task < TASKS_MAX; ++task) {
TaskDeviceID[i][task] = 0;
TaskDeviceSendData[i][task] = false;
}
}
for (byte task = 0; task < TASKS_MAX; ++task) {
TaskDeviceNumber[task] = 0;
OLD_TaskDeviceID[task] = 0;
TaskDevicePin1PullUp[task] = false;
for (byte cv = 0; cv < PLUGIN_CONFIGVAR_MAX; ++cv) {
TaskDevicePluginConfig[task][cv] = 0;
}
TaskDevicePin1Inversed[task] = false;
for (byte cv = 0; cv < PLUGIN_CONFIGFLOATVAR_MAX; ++cv) {
TaskDevicePluginConfigFloat[task][cv] = 0.0;
}
for (byte cv = 0; cv < PLUGIN_CONFIGLONGVAR_MAX; ++cv) {
TaskDevicePluginConfigLong[task][cv] = 0;
}
OLD_TaskDeviceSendData[task] = false;
TaskDeviceGlobalSync[task] = false;
TaskDeviceDataFeed[task] = 0;
TaskDeviceTimer[task] = 0;
TaskDeviceEnabled[task] = false;
}
}
unsigned long PID;
int Version;
int16_t Build;
byte IP[4];
byte Gateway[4];
byte Subnet[4];
byte DNS[4];
byte IP_Octet;
byte Unit;
char Name[26];
char NTPHost[64];
unsigned long Delay;
int8_t Pin_i2c_sda;
int8_t Pin_i2c_scl;
int8_t Pin_status_led;
int8_t Pin_sd_cs;
int8_t PinBootStates[17];
byte Syslog_IP[4];
unsigned int UDPPort;
byte SyslogLevel;
byte SerialLogLevel;
byte WebLogLevel;
byte SDLogLevel;
unsigned long BaudRate;
unsigned long MessageDelay;
byte deepSleep;
boolean CustomCSS;
boolean DST;
byte WDI2CAddress;
boolean UseRules;
boolean UseSerial;
boolean UseSSDP;
boolean UseNTP;
unsigned long WireClockStretchLimit;
boolean _GlobalSync; // obsolete!
unsigned long ConnectionFailuresThreshold;
int16_t TimeZone;
boolean MQTTRetainFlag;
boolean InitSPI;
byte Protocol[CONTROLLER_MAX];
byte Notification[NOTIFICATION_MAX]; //notifications, point to a NPLUGIN id
byte TaskDeviceNumber[TASKS_MAX];
unsigned int OLD_TaskDeviceID[TASKS_MAX];
union {
struct {
int8_t TaskDevicePin1[TASKS_MAX];
int8_t TaskDevicePin2[TASKS_MAX];
int8_t TaskDevicePin3[TASKS_MAX];
byte TaskDevicePort[TASKS_MAX];
};
int8_t TaskDevicePin[4][TASKS_MAX];
};
boolean TaskDevicePin1PullUp[TASKS_MAX];
int16_t TaskDevicePluginConfig[TASKS_MAX][PLUGIN_CONFIGVAR_MAX];
boolean TaskDevicePin1Inversed[TASKS_MAX];
float TaskDevicePluginConfigFloat[TASKS_MAX][PLUGIN_CONFIGFLOATVAR_MAX];
long TaskDevicePluginConfigLong[TASKS_MAX][PLUGIN_CONFIGLONGVAR_MAX];
boolean OLD_TaskDeviceSendData[TASKS_MAX];
boolean TaskDeviceGlobalSync[TASKS_MAX];
byte TaskDeviceDataFeed[TASKS_MAX];
unsigned long TaskDeviceTimer[TASKS_MAX];
boolean TaskDeviceEnabled[TASKS_MAX];
boolean ControllerEnabled[CONTROLLER_MAX];
boolean NotificationEnabled[NOTIFICATION_MAX];
unsigned int TaskDeviceID[CONTROLLER_MAX][TASKS_MAX];
boolean TaskDeviceSendData[CONTROLLER_MAX][TASKS_MAX];
boolean Pin_status_led_Inversed;
boolean deepSleepOnFail;
boolean UseValueLogger;
uint16_t DST_Start;
uint16_t DST_End;
//its safe to extend this struct, up to several bytes, default values in config are 0
//look in misc.ino how config.dat is used because also other stuff is stored in it at different offsets.
//TODO: document config.dat somewhere here
} Settings;
struct ControllerSettingsStruct
{
ControllerSettingsStruct() : UseDNS(false), Port(0) {
for (byte i = 0; i < 4; ++i) {
IP[i] = 0;
}
memset(HostName, 0, sizeof(HostName));
memset(Publish, 0, sizeof(Publish));
memset(Subscribe, 0, sizeof(Subscribe));
}
boolean UseDNS;
byte IP[4];
unsigned int Port;
char HostName[65];
char Publish[129];
char Subscribe[129];
IPAddress getIP() const {
IPAddress host(IP[0], IP[1], IP[2], IP[3]);
return host;
}
String getHost() const {
if (UseDNS) {
return HostName;
}
return getIP().toString();
}
void setHostname(const String& controllerhostname) {
strncpy(HostName, controllerhostname.c_str(), sizeof(HostName));
updateIPcache();
}
boolean checkHostReachable(bool quick) {
if (!WiFiConnected(10)) {
return false; // Not connected, so no use in wasting time to connect to a host.
}
if (quick && ipSet()) return true;
if (UseDNS) {
if (!updateIPcache()) {
return false;
}
}
return hostReachable(getIP());
}
boolean connectToHost(WiFiClient &client) {
if (!checkHostReachable(true)) {
return false; // Host not reachable
}
byte retry = 2;
bool connected = false;
while (retry > 0 && !connected) {
--retry;
connected = client.connect(getIP(), Port);
if (connected) return true;
if (!checkHostReachable(false))
return false;
}
return false;
}
int beginPacket(WiFiUDP &client) {
if (!checkHostReachable(true)) {
return 0; // Host not reachable
}
byte retry = 2;
int connected = 0;
while (retry > 0 && !connected) {
--retry;
connected = client.beginPacket(getIP(), Port);
if (connected != 0) return connected;
if (!checkHostReachable(false))
return false;
delay(10);
}
return false;
}
String getHostPortString() const {
String result = getHost();
result += ":";
result += Port;
return result;
}
private:
bool ipSet() {
for (byte i = 0; i < 4; ++i) {
if (IP[i] != 0) return true;
}
return false;
}
bool updateIPcache() {
if (!UseDNS) {
return true;
}
IPAddress tmpIP;
if (WiFi.hostByName(HostName, tmpIP)) {
for (byte x = 0; x < 4; x++) {
IP[x] = tmpIP[x];
}
return true;
}
return false;
}
};
struct NotificationSettingsStruct
{
NotificationSettingsStruct() : Port(0), Pin1(0), Pin2(0) {
memset(Server, 0, sizeof(Server));
memset(Domain, 0, sizeof(Domain));
memset(Sender, 0, sizeof(Sender));
memset(Receiver, 0, sizeof(Receiver));
memset(Subject, 0, sizeof(Subject));
memset(Body, 0, sizeof(Body));
memset(User, 0, sizeof(User));
memset(Pass, 0, sizeof(Pass));
}
char Server[65];
unsigned int Port;
char Domain[65];
char Sender[65];
char Receiver[65];
char Subject[129];
char Body[513];
byte Pin1;
byte Pin2;
char User[49];
char Pass[33];
//its safe to extend this struct, up to 4096 bytes, default values in config are 0
};
struct ExtraTaskSettingsStruct
{
ExtraTaskSettingsStruct() : TaskIndex(0) {
TaskDeviceName[0] = 0;
for (byte i = 0; i < VARS_PER_TASK; ++i) {
for (byte j = 0; j < 41; ++j) {
TaskDeviceFormula[i][j] = 0;
TaskDeviceValueNames[i][j] = 0;
TaskDeviceValueDecimals[i] = 0;
}
}
for (byte i = 0; i < PLUGIN_EXTRACONFIGVAR_MAX; ++i) {
TaskDevicePluginConfigLong[i] = 0;
TaskDevicePluginConfig[i] = 0;
}
}
byte TaskIndex;
char TaskDeviceName[41];
char TaskDeviceFormula[VARS_PER_TASK][41];
char TaskDeviceValueNames[VARS_PER_TASK][41];
long TaskDevicePluginConfigLong[PLUGIN_EXTRACONFIGVAR_MAX];
byte TaskDeviceValueDecimals[VARS_PER_TASK];
int16_t TaskDevicePluginConfig[PLUGIN_EXTRACONFIGVAR_MAX];
} ExtraTaskSettings;
struct EventStruct
{
EventStruct() :
Source(0), TaskIndex(0), ControllerIndex(0), ProtocolIndex(0), NotificationIndex(0),
BaseVarIndex(0), idx(0), sensorType(0), Par1(0), Par2(0), Par3(0), Par4(0), Par5(0),
OriginTaskIndex(0), Data(NULL) {}
byte Source;
byte TaskIndex; // index position in TaskSettings array, 0-11
byte ControllerIndex; // index position in Settings.Controller, 0-3
byte ProtocolIndex; // index position in protocol array, depending on which controller plugins are loaded.
byte NotificationIndex; // index position in Settings.Notification, 0-3
//Edwin: Not needed, and wasnt used. We can determine the protocol index with getNotificationProtocolIndex(NotificationIndex)
// byte NotificationProtocolIndex; // index position in notification array, depending on which controller plugins are loaded.
byte BaseVarIndex;
int idx;
byte sensorType;
int Par1;
int Par2;
int Par3;
int Par4;
int Par5;
byte OriginTaskIndex;
String String1;
String String2;
String String3;
byte *Data;
};
#define LOG_STRUCT_MESSAGE_SIZE 128
#define LOG_STRUCT_MESSAGE_LINES 20
struct LogStruct {
LogStruct() : write_idx(0), read_idx(0) {
for (int i = 0; i < LOG_STRUCT_MESSAGE_LINES; ++i) {
memset(Message[i], 0, LOG_STRUCT_MESSAGE_SIZE);
timeStamp[i] = 0;
}
}
void add(const char *line) {
write_idx = (write_idx + 1) % LOG_STRUCT_MESSAGE_LINES;
if (write_idx == read_idx) {
// Buffer full, move read_idx to overwrite oldest entry.
read_idx = (read_idx + 1) % LOG_STRUCT_MESSAGE_LINES;
}
timeStamp[write_idx] = millis();
strncpy(Message[write_idx], line, LOG_STRUCT_MESSAGE_SIZE-1);
}
// Read the next item and append it to the given string.
// Returns whether new lines are available.
bool get(String& output, const String& lineEnd) {
if (!isEmpty()) {
read_idx = (read_idx + 1) % LOG_STRUCT_MESSAGE_LINES;
output += formatLine(read_idx, lineEnd);
}
return !isEmpty();
}
bool get(String& output, const String& lineEnd, int line) {
int tmpread((write_idx + 1+line) % LOG_STRUCT_MESSAGE_LINES);
if (timeStamp[tmpread] != 0) {
output += formatLine(tmpread, lineEnd);
}
return !isEmpty();
}
bool getAll(String& output, const String& lineEnd) {
int tmpread((write_idx + 1) % LOG_STRUCT_MESSAGE_LINES);
bool someAdded = false;
while (tmpread != write_idx) {
if (timeStamp[tmpread] != 0) {
output += formatLine(tmpread, lineEnd);
someAdded = true;
}
tmpread = (tmpread + 1)% LOG_STRUCT_MESSAGE_LINES;
}
return someAdded;
}
bool isEmpty() {
return (write_idx == read_idx);
}
private:
String formatLine(int index, const String& lineEnd) {
String output;
output += timeStamp[index];
output += " : ";
output += Message[index];
output += lineEnd;
return output;
}
int write_idx;
int read_idx;
unsigned long timeStamp[LOG_STRUCT_MESSAGE_LINES];
char Message[LOG_STRUCT_MESSAGE_LINES][LOG_STRUCT_MESSAGE_SIZE];
} Logging;
struct DeviceStruct
{
DeviceStruct() :
Number(0), Type(0), VType(0), Ports(0),
PullUpOption(false), InverseLogicOption(false), FormulaOption(false),
ValueCount(0), Custom(false), SendDataOption(false), GlobalSyncOption(false),
TimerOption(false), TimerOptional(false), DecimalsOnly(false) {}
byte Number;
byte Type;
byte VType;
byte Ports;
boolean PullUpOption;
boolean InverseLogicOption;
boolean FormulaOption;
byte ValueCount;
boolean Custom;
boolean SendDataOption;
boolean GlobalSyncOption;
boolean TimerOption;
boolean TimerOptional;
boolean DecimalsOnly;
} Device[DEVICES_MAX + 1]; // 1 more because first device is empty device
struct ProtocolStruct
{
ProtocolStruct() :
Number(0), usesMQTT(false), usesAccount(false), usesPassword(false),
defaultPort(0), usesTemplate(false), usesID(false), Custom(false) {}
byte Number;
boolean usesMQTT;
boolean usesAccount;
boolean usesPassword;
int defaultPort;
boolean usesTemplate;
boolean usesID;
boolean Custom;
} Protocol[CPLUGIN_MAX];
struct NotificationStruct
{
NotificationStruct() :
Number(0), usesMessaging(false), usesGPIO(0) {}
byte Number;
boolean usesMessaging;
byte usesGPIO;
} Notification[NPLUGIN_MAX];
struct NodeStruct
{
NodeStruct() :
age(0), build(0), nodeName(NULL), nodeType(0)
{
for (byte i = 0; i < 4; ++i) ip[i] = 0;
}
byte ip[4];
byte age;
uint16_t build;
char* nodeName;
byte nodeType;
} Nodes[UNIT_MAX];
struct systemTimerStruct
{
systemTimerStruct() :
timer(0), plugin(0), Par1(0), Par2(0), Par3(0) {}
unsigned long timer;
byte plugin;
byte Par1;
byte Par2;
byte Par3;
} systemTimers[SYSTEM_TIMER_MAX];
struct systemCMDTimerStruct
{
systemCMDTimerStruct() : timer(0) {}
unsigned long timer;
String action;
} systemCMDTimers[SYSTEM_CMD_TIMER_MAX];
struct pinStatesStruct
{
byte plugin;
byte index;
byte mode;
uint16_t value;
} pinStates[PINSTATE_TABLE_MAX];
// this offsets are in blocks, bytes = blocks * 4
#define RTC_BASE_STRUCT 64
#define RTC_BASE_USERVAR 74
//max 40 bytes: ( 74 - 64 ) * 4
struct RTCStruct
{
byte ID1;
byte ID2;
boolean unused1;
byte factoryResetCounter;
byte deepSleepState;
byte unused2;
byte flashDayCounter;
unsigned long flashCounter;
unsigned long bootCounter;
} RTC;
int deviceCount = -1;
int protocolCount = -1;
int notificationCount = -1;
boolean printToWeb = false;
String printWebString = "";
boolean printToWebJSON = false;
float UserVar[VARS_PER_TASK * TASKS_MAX];
unsigned long RulesTimer[RULES_TIMER_MAX];
unsigned long timerSensor[TASKS_MAX];
unsigned long timer100ms;
unsigned long timer20ms;
unsigned long timer1s;
unsigned long timerwd;
unsigned long timermqtt;
unsigned long timermqtt_interval;
unsigned long lastSend;
unsigned long lastWeb;
unsigned int NC_Count = 0;
unsigned int C_Count = 0;
byte cmd_within_mainloop = 0;
unsigned long connectionFailures;
unsigned long wdcounter = 0;
unsigned long timerAPoff = 0;
unsigned long timerAwakeFromDeepSleep = 0;
#if FEATURE_ADC_VCC
float vcc = -1.0;
#endif
boolean WebLoggedIn = false;
int WebLoggedInTimer = 300;
boolean (*Plugin_ptr[PLUGIN_MAX])(byte, struct EventStruct*, String&);
byte Plugin_id[PLUGIN_MAX];
boolean (*CPlugin_ptr[CPLUGIN_MAX])(byte, struct EventStruct*, String&);
byte CPlugin_id[CPLUGIN_MAX];
boolean (*NPlugin_ptr[NPLUGIN_MAX])(byte, struct EventStruct*, String&);
byte NPlugin_id[NPLUGIN_MAX];
String dummyString = "";
byte lastBootCause = BOOT_CAUSE_MANUAL_REBOOT;
boolean wifiSetup = false;
boolean wifiSetupConnect = false;
uint8_t lastBSSID[6] = {0};
boolean wifiConnected = false;
unsigned long wifi_connect_timer = 0;
unsigned int wifi_connect_attempt = 0;
uint8_t lastWiFiSettings = 0;
unsigned long start = 0;
unsigned long elapsed = 0;
unsigned long loopCounter = 0;
unsigned long loopCounterLast = 0;
unsigned long loopCounterMax = 1;
unsigned long dailyResetCounter = 0;
String eventBuffer = "";
uint16_t lowestRAM = 0;
String lowestRAMfunction = "";
bool shouldReboot=false;
bool firstLoop=true;
boolean activeRuleSets[RULESETS_MAX];
#endif /* ESPEASY_GLOBALS_H_ */
+1117 -30
View File
File diff suppressed because it is too large Load Diff
-8
View File
@@ -1,6 +1,3 @@
#ifndef ESPEASY_TIMETYPES_H_
#define ESPEASY_TIMETYPES_H_
#include <stdint.h>
struct timeStruct {
@@ -62,8 +59,3 @@ struct TimeChangeRule {
void applyTimeZone(uint32_t curTime = 0);
void setTimeZone(const TimeChangeRule& dstStart, const TimeChangeRule& stdStart, uint32_t curTime = 0);
uint32_t calcTimeChangeForRule(const TimeChangeRule& r, int yr);
String getTimeString(char delimiter, bool show_seconds=true);
String getTimeString_ampm(char delimiter, bool show_seconds=true);
#endif /* ESPEASY_TIMETYPES_H_ */
+9 -5
View File
@@ -1,5 +1,5 @@
/********************************************************************************************\
* Initialize specific hardware setings (only global ones, others are set through devices)
* Initialize specific hardware settings (only global ones, others are set through devices)
\*********************************************************************************************/
void hardwareInit()
@@ -37,7 +37,9 @@ void hardwareInit()
String log = F("INIT : I2C custom clockstretchlimit:");
log += Settings.WireClockStretchLimit;
addLog(LOG_LEVEL_INFO, log);
Wire.setClockStretchLimit(Settings.WireClockStretchLimit);
#if defined(ESP8266)
Wire.setClockStretchLimit(Settings.WireClockStretchLimit);
#endif
}
}
@@ -49,7 +51,7 @@ void hardwareInit()
Wire.write(0x83); // command to set pointer
Wire.write(17); // pointer value to status byte
Wire.endTransmission();
Wire.requestFrom(Settings.WDI2CAddress, (uint8_t)1);
if (Wire.available())
{
@@ -62,7 +64,7 @@ void hardwareInit()
}
}
}
// SPI Init
if (Settings.InitSPI)
{
@@ -77,7 +79,8 @@ void hardwareInit()
addLog(LOG_LEVEL_INFO, log);
}
if (Settings.Pin_sd_cs > 0)
#ifdef FEATURE_SD
if (Settings.Pin_sd_cs >= 0)
{
if (SD.begin(Settings.Pin_sd_cs))
{
@@ -90,6 +93,7 @@ void hardwareInit()
addLog(LOG_LEVEL_ERROR, log);
}
}
#endif
}
+436 -95
View File
@@ -50,6 +50,7 @@ bool readyForSleep()
void deepSleep(int delay)
{
checkRAM(F("deepSleep"));
if (!isDeepSleepEnabled())
{
//Deep sleep canceled by GPIO16(D0)=LOW
@@ -86,11 +87,18 @@ void deepSleepStart(int delay)
delay = 4294; //max sleep time ~1.2h
addLog(LOG_LEVEL_INFO, F("SLEEP: Powering down to deepsleep..."));
ESP.deepSleep((uint32_t)delay * 1000000, WAKE_RF_DEFAULT);
#if defined(ESP8266)
ESP.deepSleep((uint32_t)delay * 1000000, WAKE_RF_DEFAULT);
#endif
#if defined(ESP32)
esp_sleep_enable_timer_wakeup((uint32_t)delay * 1000000);
esp_deep_sleep_start();
#endif
}
boolean remoteConfig(struct EventStruct *event, String& string)
{
checkRAM(F("remoteConfig"));
boolean success = false;
String command = parseString(string, 1);
@@ -142,6 +150,7 @@ void flashCount()
String flashGuard()
{
checkRAM(F("flashGuard"));
if (RTC.flashDayCounter > MAX_FLASHWRITES_PER_DAY)
{
String log = F("FS : Daily flash write rate exceeded! (powercycle to reset this)");
@@ -223,6 +232,7 @@ boolean hasPinState(byte plugin, byte index)
\*********************************************************************************************/
String getPinStateJSON(boolean search, byte plugin, byte index, String& log, uint16_t noSearchValue)
{
checkRAM(F("getPinStateJSON"));
printToWebJSON = true;
byte mode = PIN_MODE_INPUT;
uint16_t value = noSearchValue;
@@ -280,6 +290,9 @@ String getPinStateJSON(boolean search, byte plugin, byte index, String& log, uin
/********************************************************************************************\
Status LED
\*********************************************************************************************/
#if defined(ESP32)
#define PWMRANGE 1024
#endif
#define STATUS_PWM_NORMALVALUE (PWMRANGE>>2)
#define STATUS_PWM_NORMALFADE (PWMRANGE>>8)
#define STATUS_PWM_TRAFFICRISE (PWMRANGE>>1)
@@ -337,7 +350,9 @@ void statusLED(boolean traffic)
if (Settings.Pin_status_led_Inversed)
pwm = PWMRANGE-pwm;
analogWrite(Settings.Pin_status_led, pwm);
#if defined(ESP8266)
analogWrite(Settings.Pin_status_led, pwm);
#endif
}
}
@@ -358,6 +373,7 @@ void delayBackground(unsigned long delay)
\*********************************************************************************************/
void parseCommandString(struct EventStruct *event, const String& string)
{
checkRAM(F("parseCommandString"));
char command[80];
command[0] = 0;
char TmpStr1[80];
@@ -382,6 +398,7 @@ void parseCommandString(struct EventStruct *event, const String& string)
\*********************************************************************************************/
void taskClear(byte taskIndex, boolean save)
{
checkRAM(F("taskClear"));
Settings.TaskDeviceNumber[taskIndex] = 0;
ExtraTaskSettings.TaskDeviceName[0] = 0;
Settings.TaskDeviceDataFeed[taskIndex] = 0;
@@ -443,6 +460,7 @@ String FileError(int line, const char * fname)
\*********************************************************************************************/
String BuildFixes()
{
checkRAM(F("BuildFixes"));
Serial.println(F("\nBuild changed!"));
if (Settings.Build < 145)
@@ -470,17 +488,20 @@ String BuildFixes()
\*********************************************************************************************/
void fileSystemCheck()
{
checkRAM(F("fileSystemCheck"));
addLog(LOG_LEVEL_INFO, F("FS : Mounting..."));
if (SPIFFS.begin())
{
fs::FSInfo fs_info;
SPIFFS.info(fs_info);
#if defined(ESP8266)
fs::FSInfo fs_info;
SPIFFS.info(fs_info);
String log = F("FS : Mount successful, used ");
log=log+fs_info.usedBytes;
log=log+F(" bytes of ");
log=log+fs_info.totalBytes;
addLog(LOG_LEVEL_INFO, log);
String log = F("FS : Mount successful, used ");
log=log+fs_info.usedBytes;
log=log+F(" bytes of ");
log=log+fs_info.totalBytes;
addLog(LOG_LEVEL_INFO, log);
#endif
fs::File f = SPIFFS.open(FILE_CONFIG, "r");
if (!f)
@@ -600,31 +621,138 @@ boolean GetArgv(const char *string, char *argv, unsigned int argc)
/********************************************************************************************\
check the program memory hash
The const MD5_MD5_MD5_MD5_BoundariesOfTheSegmentsGoHere... needs to remain unchanged as it will be replaced by
- 16 bytes md5 hash, followed by
- 4 * uint32_t start of memory segment 1-4
- 4 * uint32_t end of memory segment 1-4
currently there are only two segemts included in the hash. Unused segments have start adress 0.
Execution time 520kb @80Mhz: 236ms
Returns: 0 if hash compare fails, number of checked bytes otherwise.
The reference hash is calculated by a .py file and injected into the binary.
Caution: currently the hash sits in an unchecked segment. If it ever moves to a checked segment, make sure
it is excluded from the calculation !
\*********************************************************************************************/
#if defined(ARDUINO_ESP8266_RELEASE_2_3_0)
void dump (uint32_t addr) { //Seems already included in core 2.4 ...
Serial.print (addr, HEX);
Serial.print(": ");
for (uint32_t a = addr; a < addr + 16; a++)
{
Serial.print ( pgm_read_byte(a), HEX);
Serial.print (" ");
}
Serial.println("");
}
#endif
uint32_t progMemMD5check(){
checkRAM(F("progMemMD5check"));
#define BufSize 10
uint32_t calcBuffer[BufSize];
CRCValues.numberOfCRCBytes = 0;
memcpy (calcBuffer,CRCValues.compileTimeMD5,16); // is there still the dummy in memory ? - the dummy needs to be replaced by the real md5 after linking.
if( memcmp (calcBuffer, "MD5_MD5_MD5_",12)==0){ // do not memcmp with CRCdummy directly or it will get optimized away.
addLog(LOG_LEVEL_INFO, F("CRC : No program memory checksum found. Check output of crc2.py"));
return 0;
}
MD5Builder md5;
md5.begin();
for (int l = 0; l<4; l++){ // check max segments, if the pointer is not 0
uint32_t *ptrStart = (uint32_t *)&CRCValues.compileTimeMD5[16+l*4];
uint32_t *ptrEnd = (uint32_t *)&CRCValues.compileTimeMD5[16+4*4+l*4];
if ((*ptrStart) == 0) break; // segment not used.
for (uint32_t i = *ptrStart; i< (*ptrEnd) ; i=i+sizeof(calcBuffer)){ // "<" includes last byte
for (int buf = 0; buf < BufSize; buf ++){
calcBuffer[buf] = pgm_read_dword((uint32_t*)i+buf); // read 4 bytes
CRCValues.numberOfCRCBytes+=sizeof(calcBuffer[0]);
}
md5.add((uint8_t *)&calcBuffer[0],(*ptrEnd-i)<sizeof(calcBuffer) ? (*ptrEnd-i):sizeof(calcBuffer) ); // add buffer to md5. At the end not the whole buffer. md5 ptr to data in ram.
}
}
md5.calculate();
md5.getBytes(CRCValues.runTimeMD5);
if ( CRCValues.checkPassed()) {
addLog(LOG_LEVEL_INFO, F("CRC : program checksum ...OK"));
return CRCValues.numberOfCRCBytes;
}
addLog(LOG_LEVEL_INFO, F("CRC : program checksum ...FAIL"));
return 0;
}
/********************************************************************************************\
Save settings to SPIFFS
\*********************************************************************************************/
String SaveSettings(void)
{
checkRAM(F("SaveSettings"));
MD5Builder md5;
memcpy( Settings.ProgmemMd5, CRCValues.runTimeMD5, 16);
md5.begin();
md5.add((uint8_t *)&Settings, sizeof(Settings)-16);
md5.calculate();
md5.getBytes(Settings.md5);
String err;
err=SaveToFile((char*)FILE_CONFIG, 0, (byte*)&Settings, sizeof(struct SettingsStruct));
if (err.length())
return(err);
return(err);
return(SaveToFile((char*)FILE_SECURITY, 0, (byte*)&SecuritySettings, sizeof(struct SecurityStruct)));
memcpy( SecuritySettings.ProgmemMd5, CRCValues.runTimeMD5, 16);
md5.begin();
md5.add((uint8_t *)&SecuritySettings, sizeof(SecuritySettings)-16);
md5.calculate();
md5.getBytes(SecuritySettings.md5);
err=SaveToFile((char*)FILE_SECURITY, 0, (byte*)&SecuritySettings, sizeof(struct SecurityStruct));
return (err);
}
/********************************************************************************************\
Load settings from SPIFFS
\*********************************************************************************************/
String LoadSettings()
{
checkRAM(F("LoadSettings"));
String err;
err=LoadFromFile((char*)FILE_CONFIG, 0, (byte*)&Settings, sizeof(struct SettingsStruct));
uint8_t calculatedMd5[16];
MD5Builder md5;
err=LoadFromFile((char*)FILE_CONFIG, 0, (byte*)&Settings, sizeof( SettingsStruct));
if (err.length())
return(err);
return(LoadFromFile((char*)FILE_SECURITY, 0, (byte*)&SecuritySettings, sizeof(struct SecurityStruct)));
md5.begin();
md5.add((uint8_t *)&Settings, sizeof(Settings)-16);
md5.calculate();
md5.getBytes(calculatedMd5);
if (memcmp (calculatedMd5, Settings.md5,16)==0){
addLog(LOG_LEVEL_INFO, F("CRC : Settings CRC ...OK"));
if (memcmp(Settings.ProgmemMd5, CRCValues.runTimeMD5, 16)!=0)
addLog(LOG_LEVEL_INFO, F("CRC : binary has changed since last save of Settings"));
}
else{
addLog(LOG_LEVEL_ERROR, F("CRC : Settings CRC ...FAIL"));
}
err=LoadFromFile((char*)FILE_SECURITY, 0, (byte*)&SecuritySettings, sizeof( SecurityStruct));
md5.begin();
md5.add((uint8_t *)&SecuritySettings, sizeof(SecuritySettings)-16);
md5.calculate();
md5.getBytes(calculatedMd5);
if (memcmp (calculatedMd5, SecuritySettings.md5, 16)==0){
addLog(LOG_LEVEL_INFO, F("CRC : SecuritySettings CRC ...OK "));
if (memcmp(SecuritySettings.ProgmemMd5,CRCValues.runTimeMD5, 16)!=0)
addLog(LOG_LEVEL_INFO, F("CRC : binary has changed since last save of Settings"));
}
else{
addLog(LOG_LEVEL_ERROR, F("CRC : SecuritySettings CRC ...FAIL"));
}
return(err);
}
@@ -633,6 +761,7 @@ String LoadSettings()
\*********************************************************************************************/
String SaveTaskSettings(byte TaskIndex)
{
checkRAM(F("SaveTaskSettings"));
ExtraTaskSettings.TaskIndex = TaskIndex;
return(SaveToFile((char*)FILE_CONFIG, DAT_OFFSET_TASKS + (TaskIndex * DAT_TASKS_SIZE), (byte*)&ExtraTaskSettings, sizeof(struct ExtraTaskSettingsStruct)));
}
@@ -643,6 +772,7 @@ String SaveTaskSettings(byte TaskIndex)
\*********************************************************************************************/
String LoadTaskSettings(byte TaskIndex)
{
checkRAM(F("LoadTaskSettings"));
//already loaded
if (ExtraTaskSettings.TaskIndex == TaskIndex)
return(String());
@@ -659,6 +789,7 @@ String LoadTaskSettings(byte TaskIndex)
\*********************************************************************************************/
String SaveCustomTaskSettings(int TaskIndex, byte* memAddress, int datasize)
{
checkRAM(F("SaveCustomTaskSettings"));
if (datasize > DAT_TASKS_SIZE)
return F("SaveCustomTaskSettings too big");
return(SaveToFile((char*)FILE_CONFIG, DAT_OFFSET_TASKS + (TaskIndex * DAT_TASKS_SIZE) + DAT_TASKS_CUSTOM_OFFSET, memAddress, datasize));
@@ -679,6 +810,7 @@ String ClearCustomTaskSettings(int TaskIndex)
\*********************************************************************************************/
String LoadCustomTaskSettings(int TaskIndex, byte* memAddress, int datasize)
{
checkRAM(F("LoadCustomTaskSettings"));
if (datasize > DAT_TASKS_SIZE)
return (String(F("LoadCustomTaskSettings too big")));
return(LoadFromFile((char*)FILE_CONFIG, DAT_OFFSET_TASKS + (TaskIndex * DAT_TASKS_SIZE) + DAT_TASKS_CUSTOM_OFFSET, memAddress, datasize));
@@ -689,6 +821,7 @@ String LoadCustomTaskSettings(int TaskIndex, byte* memAddress, int datasize)
\*********************************************************************************************/
String SaveControllerSettings(int ControllerIndex, byte* memAddress, int datasize)
{
checkRAM(F("SaveControllerSettings"));
if (datasize > DAT_CONTROLLER_SIZE)
return F("SaveControllerSettings too big");
return SaveToFile((char*)FILE_CONFIG, DAT_OFFSET_CONTROLLER + (ControllerIndex * DAT_CONTROLLER_SIZE), memAddress, datasize);
@@ -700,6 +833,7 @@ String SaveControllerSettings(int ControllerIndex, byte* memAddress, int datasiz
\*********************************************************************************************/
String LoadControllerSettings(int ControllerIndex, byte* memAddress, int datasize)
{
checkRAM(F("LoadControllerSettings"));
if (datasize > DAT_CONTROLLER_SIZE)
return F("LoadControllerSettings too big");
@@ -712,6 +846,7 @@ String LoadControllerSettings(int ControllerIndex, byte* memAddress, int datasiz
\*********************************************************************************************/
String ClearCustomControllerSettings(int ControllerIndex)
{
checkRAM(F("ClearCustomControllerSettings"));
// addLog(LOG_LEVEL_DEBUG, F("Clearing custom controller settings"));
return(ClearInFile((char*)FILE_CONFIG, DAT_OFFSET_CUSTOM_CONTROLLER + (ControllerIndex * DAT_CUSTOM_CONTROLLER_SIZE), DAT_CUSTOM_CONTROLLER_SIZE));
}
@@ -722,6 +857,7 @@ String ClearCustomControllerSettings(int ControllerIndex)
\*********************************************************************************************/
String SaveCustomControllerSettings(int ControllerIndex,byte* memAddress, int datasize)
{
checkRAM(F("SaveCustomControllerSettings"));
if (datasize > DAT_CUSTOM_CONTROLLER_SIZE)
return F("SaveCustomControllerSettings too big");
return SaveToFile((char*)FILE_CONFIG, DAT_OFFSET_CUSTOM_CONTROLLER + (ControllerIndex * DAT_CUSTOM_CONTROLLER_SIZE), memAddress, datasize);
@@ -733,6 +869,7 @@ String SaveCustomControllerSettings(int ControllerIndex,byte* memAddress, int da
\*********************************************************************************************/
String LoadCustomControllerSettings(int ControllerIndex,byte* memAddress, int datasize)
{
checkRAM(F("LoadCustomControllerSettings"));
if (datasize > DAT_CUSTOM_CONTROLLER_SIZE)
return(F("LoadCustomControllerSettings too big"));
return(LoadFromFile((char*)FILE_CONFIG, DAT_OFFSET_CUSTOM_CONTROLLER + (ControllerIndex * DAT_CUSTOM_CONTROLLER_SIZE), memAddress, datasize));
@@ -743,6 +880,7 @@ String LoadCustomControllerSettings(int ControllerIndex,byte* memAddress, int da
\*********************************************************************************************/
String SaveNotificationSettings(int NotificationIndex, byte* memAddress, int datasize)
{
checkRAM(F("SaveNotificationSettings"));
if (datasize > DAT_NOTIFICATION_SIZE)
return F("SaveNotificationSettings too big");
return SaveToFile((char*)FILE_NOTIFICATION, NotificationIndex * DAT_NOTIFICATION_SIZE, memAddress, datasize);
@@ -754,6 +892,7 @@ String SaveNotificationSettings(int NotificationIndex, byte* memAddress, int dat
\*********************************************************************************************/
String LoadNotificationSettings(int NotificationIndex, byte* memAddress, int datasize)
{
checkRAM(F("LoadNotificationSettings"));
if (datasize > DAT_NOTIFICATION_SIZE)
return(F("LoadNotificationSettings too big"));
return(LoadFromFile((char*)FILE_NOTIFICATION, NotificationIndex * DAT_NOTIFICATION_SIZE, memAddress, datasize));
@@ -767,7 +906,7 @@ String LoadNotificationSettings(int NotificationIndex, byte* memAddress, int dat
\*********************************************************************************************/
String InitFile(const char* fname, int datasize)
{
checkRAM(F("InitFile"));
FLASH_GUARD();
fs::File f = SPIFFS.open(fname, "w");
@@ -788,7 +927,7 @@ String InitFile(const char* fname, int datasize)
\*********************************************************************************************/
String SaveToFile(char* fname, int index, byte* memAddress, int datasize)
{
checkRAM(F("SaveToFile"));
FLASH_GUARD();
fs::File f = SPIFFS.open(fname, "r+");
@@ -815,6 +954,7 @@ String SaveToFile(char* fname, int index, byte* memAddress, int datasize)
\*********************************************************************************************/
String ClearInFile(char* fname, int index, int datasize)
{
checkRAM(F("ClearInFile"));
FLASH_GUARD();
fs::File f = SPIFFS.open(fname, "r+");
@@ -838,7 +978,6 @@ String ClearInFile(char* fname, int index, int datasize)
String LoadFromFile(char* fname, int index, byte* memAddress, int datasize)
{
checkRAM(F("LoadFromFile"));
// addLog(LOG_LEVEL_INFO, String(F("FILE : Load size "))+datasize);
fs::File f = SPIFFS.open(fname, "r+");
SPIFFS_CHECK(f, fname);
@@ -855,9 +994,15 @@ String LoadFromFile(char* fname, int index, byte* memAddress, int datasize)
\*********************************************************************************************/
int SpiffsSectors()
{
uint32_t _sectorStart = ((uint32_t)&_SPIFFS_start - 0x40200000) / SPI_FLASH_SEC_SIZE;
uint32_t _sectorEnd = ((uint32_t)&_SPIFFS_end - 0x40200000) / SPI_FLASH_SEC_SIZE;
return _sectorEnd - _sectorStart;
checkRAM(F("SpiffsSectors"));
#if defined(ESP8266)
uint32_t _sectorStart = ((uint32_t)&_SPIFFS_start - 0x40200000) / SPI_FLASH_SEC_SIZE;
uint32_t _sectorEnd = ((uint32_t)&_SPIFFS_end - 0x40200000) / SPI_FLASH_SEC_SIZE;
return _sectorEnd - _sectorStart;
#endif
#if defined(ESP32)
return 32;
#endif
}
@@ -867,6 +1012,7 @@ int SpiffsSectors()
void ResetFactory(void)
{
checkRAM(F("ResetFactory"));
// Direct Serial is allowed here, since this is only an emergency task.
Serial.println(F("RESET: Resetting factory defaults..."));
delay(1000);
@@ -906,7 +1052,7 @@ void ResetFactory(void)
String fname;
fname=F(FILE_CONFIG);
InitFile(fname.c_str(), 65536);
InitFile(fname.c_str(), CONFIG_FILE_SIZE);
fname=F(FILE_SECURITY);
InitFile(fname.c_str(), 4096);
@@ -914,7 +1060,7 @@ void ResetFactory(void)
fname=F(FILE_NOTIFICATION);
InitFile(fname.c_str(), 4096);
fname=F("rules1.txt");
fname=F(FILE_RULES);
InitFile(fname.c_str(), 0);
LoadSettings();
@@ -934,6 +1080,11 @@ void ResetFactory(void)
strcpy_P(SecuritySettings.WifiKey, PSTR(DEFAULT_KEY));
strcpy_P(SecuritySettings.WifiAPKey, PSTR(DEFAULT_AP_KEY));
SecuritySettings.Password[0] = 0;
// TD-er Reset access control
str2ip((char*)DEFAULT_IPRANGE_LOW, SecuritySettings.AllowedIPrangeLow);
str2ip((char*)DEFAULT_IPRANGE_HIGH, SecuritySettings.AllowedIPrangeHigh);
SecuritySettings.IPblockLevel = DEFAULT_IP_BLOCK_LEVEL;
Settings.Delay = DEFAULT_DELAY;
Settings.Pin_i2c_sda = 4;
Settings.Pin_i2c_scl = 5;
@@ -1007,14 +1158,19 @@ void ResetFactory(void)
ControllerSettings.Port = DEFAULT_PORT;
SaveControllerSettings(0, (byte*)&ControllerSettings, sizeof(ControllerSettings));
#endif
checkRAM(F("ResetFactory2"));
Serial.println("RESET: Succesful, rebooting. (you might need to press the reset button if you've justed flashed the firmware)");
//NOTE: this is a known ESP8266 bug, not our fault. :)
delay(1000);
WiFi.persistent(true); // use SDK storage of SSID/WPA parameters
WiFi.disconnect(); // this will store empty ssid/wpa into sdk storage
WiFi.persistent(false); // Do not use SDK storage of SSID/WPA parameters
ESP.reset();
#if defined(ESP8266)
ESP.reset();
#endif
#if defined(ESP32)
ESP.restart();
#endif
}
@@ -1044,7 +1200,12 @@ void emergencyReset()
\*********************************************************************************************/
unsigned long FreeMem(void)
{
return system_get_free_heap_size();
#if defined(ESP8266)
return system_get_free_heap_size();
#endif
#if defined(ESP32)
return ESP.getFreeHeap();
#endif
}
@@ -1128,13 +1289,16 @@ void addLog(byte loglevel, String& string)
void addLog(byte logLevel, const __FlashStringHelper* flashString)
{
checkRAM(F("addLog"));
String s(flashString);
addLog(logLevel, s.c_str());
}
bool SerialAvailableForWrite() {
if (!Settings.UseSerial) return false;
if (!Serial.availableForWrite()) return false; // UART FIFO overflow or TX disabled.
#if defined(ESP8266)
if (!Serial.availableForWrite()) return false; // UART FIFO overflow or TX disabled.
#endif
return true;
}
@@ -1180,12 +1344,15 @@ void addLog(byte logLevel, const char *line)
if (loglevelActiveFor(LOG_TO_WEBLOG, logLevel)) {
Logging.add(line);
}
#ifdef FEATURE_SD
if (loglevelActiveFor(LOG_TO_SDCARD, logLevel)) {
File logFile = SD.open("log.dat", FILE_WRITE);
if (logFile)
logFile.println(line);
logFile.close();
}
#endif
}
@@ -1202,7 +1369,12 @@ void delayedReboot(int rebootDelay)
rebootDelay--;
delay(1000);
}
ESP.reset();
#if defined(ESP8266)
ESP.reset();
#endif
#if defined(ESP32)
ESP.restart();
#endif
}
@@ -1211,15 +1383,20 @@ void delayedReboot(int rebootDelay)
\*********************************************************************************************/
boolean saveToRTC()
{
if (!system_rtc_mem_write(RTC_BASE_STRUCT, (byte*)&RTC, sizeof(RTC)) || !readFromRTC())
{
addLog(LOG_LEVEL_ERROR, F("RTC : Error while writing to RTC"));
return(false);
}
else
{
return(true);
}
#if defined(ESP8266)
if (!system_rtc_mem_write(RTC_BASE_STRUCT, (byte*)&RTC, sizeof(RTC)) || !readFromRTC())
{
addLog(LOG_LEVEL_ERROR, F("RTC : Error while writing to RTC"));
return(false);
}
else
{
return(true);
}
#endif
#if defined(ESP32)
boolean ret = false;
#endif
}
@@ -1242,13 +1419,18 @@ void initRTC()
\*********************************************************************************************/
boolean readFromRTC()
{
if (!system_rtc_mem_read(RTC_BASE_STRUCT, (byte*)&RTC, sizeof(RTC)))
return(false);
#if defined(ESP8266)
if (!system_rtc_mem_read(RTC_BASE_STRUCT, (byte*)&RTC, sizeof(RTC)))
return(false);
if (RTC.ID1 == 0xAA && RTC.ID2 == 0x55)
return true;
else
return false;
if (RTC.ID1 == 0xAA && RTC.ID2 == 0x55)
return true;
else
return false;
#endif
#if defined(ESP32)
boolean ret = false;
#endif
}
@@ -1257,12 +1439,17 @@ boolean readFromRTC()
\*********************************************************************************************/
boolean saveUserVarToRTC()
{
//addLog(LOG_LEVEL_DEBUG, F("RTCMEM: saveUserVarToRTC"));
byte* buffer = (byte*)&UserVar;
size_t size = sizeof(UserVar);
uint32 sum = getChecksum(buffer, size);
boolean ret = system_rtc_mem_write(RTC_BASE_USERVAR, buffer, size);
ret &= system_rtc_mem_write(RTC_BASE_USERVAR+(size>>2), (byte*)&sum, 4);
#if defined(ESP8266)
//addLog(LOG_LEVEL_DEBUG, F("RTCMEM: saveUserVarToRTC"));
byte* buffer = (byte*)&UserVar;
size_t size = sizeof(UserVar);
uint32_t sum = getChecksum(buffer, size);
boolean ret = system_rtc_mem_write(RTC_BASE_USERVAR, buffer, size);
ret &= system_rtc_mem_write(RTC_BASE_USERVAR+(size>>2), (byte*)&sum, 4);
#endif
#if defined(ESP32)
boolean ret = false;
#endif
return ret;
}
@@ -1272,36 +1459,42 @@ boolean saveUserVarToRTC()
\*********************************************************************************************/
boolean readUserVarFromRTC()
{
//addLog(LOG_LEVEL_DEBUG, F("RTCMEM: readUserVarFromRTC"));
byte* buffer = (byte*)&UserVar;
size_t size = sizeof(UserVar);
boolean ret = system_rtc_mem_read(RTC_BASE_USERVAR, buffer, size);
uint32 sumRAM = getChecksum(buffer, size);
uint32 sumRTC = 0;
ret &= system_rtc_mem_read(RTC_BASE_USERVAR+(size>>2), (byte*)&sumRTC, 4);
if (!ret || sumRTC != sumRAM)
{
addLog(LOG_LEVEL_ERROR, F("RTC : Checksum error on reading RTC user var"));
memset(buffer, 0, size);
}
#if defined(ESP8266)
//addLog(LOG_LEVEL_DEBUG, F("RTCMEM: readUserVarFromRTC"));
byte* buffer = (byte*)&UserVar;
size_t size = sizeof(UserVar);
boolean ret = system_rtc_mem_read(RTC_BASE_USERVAR, buffer, size);
uint32_t sumRAM = getChecksum(buffer, size);
uint32_t sumRTC = 0;
ret &= system_rtc_mem_read(RTC_BASE_USERVAR+(size>>2), (byte*)&sumRTC, 4);
if (!ret || sumRTC != sumRAM)
{
addLog(LOG_LEVEL_ERROR, F("RTC : Checksum error on reading RTC user var"));
memset(buffer, 0, size);
}
#endif
#if defined(ESP32)
boolean ret = false;
#endif
return ret;
}
uint32 getChecksum(byte* buffer, size_t size)
uint32_t getChecksum(byte* buffer, size_t size)
{
uint32 sum = 0x82662342; //some magic to avoid valid checksum on new, uninitialized ESP
uint32_t sum = 0x82662342; //some magic to avoid valid checksum on new, uninitialized ESP
for (size_t i=0; i<size; i++)
sum += buffer[i];
return sum;
}
/********************************************************************************************\
Parse string template
\*********************************************************************************************/
String parseTemplate(String &tmpString, byte lineSize)
{
checkRAM(F("parseTemplate"));
String newString = "";
String tmpStringMid = "";
newString.reserve(lineSize);
@@ -1320,21 +1513,29 @@ String parseTemplate(String &tmpString, byte lineSize)
newString += tmpString.substring(0, leftBracketIndex);
tmpString = tmpString.substring(leftBracketIndex + 1);
int rightBracketIndex = tmpString.indexOf(']');
if (rightBracketIndex >= 0)
if (rightBracketIndex)
{
tmpStringMid = tmpString.substring(0, rightBracketIndex);
tmpString = tmpString.substring(rightBracketIndex + 1);
int hashtagIndex = tmpStringMid.indexOf('#');
if (hashtagIndex >= 0) {
String deviceName = tmpStringMid.substring(0, hashtagIndex);
String valueName = tmpStringMid.substring(hashtagIndex + 1);
String valueFormat = "";
hashtagIndex = valueName.indexOf('#');
if (hashtagIndex >= 0)
{
valueFormat = valueName.substring(hashtagIndex + 1);
valueName = valueName.substring(0, hashtagIndex);
}
String deviceName = tmpStringMid.substring(0, hashtagIndex);
String valueName = tmpStringMid.substring(hashtagIndex + 1);
String valueFormat = "";
hashtagIndex = valueName.indexOf('#');
if (hashtagIndex >= 0)
{
valueFormat = valueName.substring(hashtagIndex + 1);
valueName = valueName.substring(0, hashtagIndex);
}
if (deviceName.equalsIgnoreCase("Plugin"))
{
String tmpString = tmpStringMid.substring(7);
tmpString.replace("#", ",");
if (PluginCall(PLUGIN_REQUEST, 0, tmpString))
newString += tmpString;
}
else
for (byte y = 0; y < TASKS_MAX; y++)
{
if (Settings.TaskDeviceEnabled[y])
@@ -1358,16 +1559,16 @@ String parseTemplate(String &tmpString, byte lineSize)
value = toString(UserVar[y * VARS_PER_TASK + z], ExtraTaskSettings.TaskDeviceValueDecimals[z]);
int oidx;
if ((oidx = valueFormat.indexOf('O'))>=0) // Output
if ((oidx = valueFormat.indexOf('O')) >= 0) // Output
{
valueFormat.remove(oidx);
oidx = valueFormat.indexOf('!'); // inverted or active low
float val = value.toFloat();
if (oidx >= 0) {
valueFormat.remove(oidx);
value = val == 0 ? " ON" : "OFF";
valueFormat.remove(oidx);
value = val == 0 ? " ON" : "OFF";
} else {
value = val == 0 ? "OFF" : " ON";
value = val == 0 ? "OFF" : " ON";
}
}
@@ -1393,14 +1594,14 @@ String parseTemplate(String &tmpString, byte lineSize)
}
}
}
}
}
leftBracketIndex = tmpString.indexOf('[');
count++;
}
checkRAM(F("parseTemplate2"));
newString += tmpString;
if (currentTaskIndex!=255)
if (currentTaskIndex != 255)
LoadTaskSettings(currentTaskIndex);
}
@@ -1410,7 +1611,7 @@ String parseTemplate(String &tmpString, byte lineSize)
// padding spaces
while (newString.length() < lineSize)
newString += " ";
checkRAM(F("parseTemplate3"));
return newString;
}
@@ -1448,7 +1649,7 @@ float pop()
if (sp != (globalstack - 1)) // empty
return *(sp--);
else
return(0);
return 0.0;
}
float apply_operator(char op, float first, float second)
@@ -1551,6 +1752,7 @@ unsigned int op_arg_count(const char c)
int Calculate(const char *input, float* result)
{
checkRAM(F("Calculate"));
const char *strpos = input, *strend = input + strlen(input);
char token[25];
char c, oc, *TokenPos = token;
@@ -1683,6 +1885,7 @@ int Calculate(const char *input, float* result)
return error;
}
*result = *sp;
checkRAM(F("Calculate2"));
return CALCULATE_OK;
}
@@ -1716,6 +1919,7 @@ for (byte x=0; x < RULESETS_MAX; x++){
\*********************************************************************************************/
void rulesProcessing(String& event)
{
checkRAM(F("rulesProcessing"));
unsigned long timer = millis();
String log = "";
@@ -1808,11 +2012,10 @@ String rulesProcessingFile(String fileName, String& event)
// This to avoid waisting CPU time...
line = parseTemplate(line, line.length());
}
line.trim();
String lineOrg = line; // store original line for future use
line.toLowerCase(); // convert all to lower case to make checks easier
line.trim();
String eventTrigger = "";
String action = "";
@@ -1856,9 +2059,9 @@ String rulesProcessingFile(String fileName, String& event)
{
isCommand = false;
codeBlock = false;
match = false;
match = false;
}
if (Settings.SerialLogLevel == LOG_LEVEL_DEBUG_DEV){
Serial.print(F("RuleDebug: "));
Serial.print(codeBlock);
@@ -1867,7 +2070,7 @@ String rulesProcessingFile(String fileName, String& event)
Serial.print(": ");
Serial.println(line);
}
if (match) // rule matched for one action or a block of actions
{
int split = lcAction.indexOf("if "); // check for optional "if" condition
@@ -1938,7 +2141,8 @@ String rulesProcessingFile(String fileName, String& event)
}
nestingLevel--;
return(String());
checkRAM(F("rulesProcessingFile2"));
return (String());
}
@@ -1947,6 +2151,7 @@ String rulesProcessingFile(String fileName, String& event)
\*********************************************************************************************/
boolean ruleMatch(String& event, String& rule)
{
checkRAM(F("ruleMatch"));
boolean match = false;
String tmpEvent = event;
String tmpRule = rule;
@@ -2063,7 +2268,7 @@ boolean ruleMatch(String& event, String& rule)
match = true;
break;
}
checkRAM(F("ruleMatch2"));
return match;
}
@@ -2275,17 +2480,118 @@ void SendValueLogger(byte TaskIndex)
addLog(LOG_LEVEL_DEBUG, logger);
#ifdef FEATURE_SD
String filename = F("VALUES.CSV");
File logFile = SD.open(filename, FILE_WRITE);
if (logFile)
logFile.print(logger);
logFile.close();
#endif
}
#define TRACES 3 // number of memory traces
#define TRACEENTRIES 15 // entries per trace
class RamTracker{
private:
String traces[TRACES] ; // trace of latest memory checks
unsigned int tracesMemory[TRACES] ; // lowest memory for that trace
unsigned int readPtr, writePtr; // pointer to cyclic buffer
String nextAction[TRACEENTRIES]; // buffer to record the names of functions before they are transfered to a trace
unsigned int nextActionStartMemory[TRACEENTRIES]; // memory levels for the functions.
unsigned int bestCaseTrace (void){ // find highest the trace with the largest minimum memory (gets replaced by worse one)
unsigned int lowestMemoryInTrace = 0;
unsigned int lowestMemoryInTraceIndex=0;
for (int i = 0; i<TRACES; i++) {
if (tracesMemory[i] > lowestMemoryInTrace){
lowestMemoryInTrace= tracesMemory[i];
lowestMemoryInTraceIndex=i;
}
}
//Serial.println(lowestMemoryInTraceIndex);
return lowestMemoryInTraceIndex;
}
public:
RamTracker(void){ // constructor
readPtr=0;
writePtr=0;
for (int i = 0; i< TRACES; i++) {
traces[i]="";
tracesMemory[i]=0xffff; // init with best case memory values, so they get replaced if memory goes lower
}
for (int i = 0; i< TRACEENTRIES; i++) {
nextAction[i]="startup";
nextActionStartMemory[i] = ESP.getFreeHeap(); // init with best case memory values, so they get replaced if memory goes lower
}
};
void registerRamState(String &s){ // store function
nextAction[writePtr]=s; // name and mem
nextActionStartMemory[writePtr]=ESP.getFreeHeap(); // in cyclic buffer.
int bestCase = bestCaseTrace(); // find best case memory trace
if ( ESP.getFreeHeap() < tracesMemory[bestCase]){ // compare to current memory value
traces[bestCase]="";
readPtr = writePtr+1; // read out buffer, oldest value first
if (readPtr>=TRACEENTRIES) readPtr=0; // read pointer wrap around
tracesMemory[bestCase] = ESP.getFreeHeap(); // store new lowest value of that trace
for (int i = 0; i<TRACEENTRIES; i++) { // tranfer cyclic buffer strings and mem values to this trace
traces[bestCase]+= nextAction[readPtr];
traces[bestCase]+= "-> ";
traces[bestCase]+= String(nextActionStartMemory[readPtr]);
traces[bestCase]+= " ";
readPtr++;
if (readPtr >=TRACEENTRIES) readPtr=0; // wrap around read pointer
}
}
writePtr++;
if (writePtr >= TRACEENTRIES) writePtr=0; // inc write pointer and wrap around too.
};
void getTraceBuffer(){ // return giant strings, one line per trace. Add stremToWeb method to avoid large strings.
String retval="Memtrace\n";
for (int i = 0; i< TRACES; i++){
retval += String(i);
retval += ": lowest: ";
retval += String(tracesMemory[i]);
retval += " ";
retval += traces[i];
addLog(LOG_LEVEL_DEBUG_DEV, retval);
retval="";
}
}
}myRamTracker; // instantiate class. (is global now)
void checkRAMtoLog(void){
myRamTracker.getTraceBuffer();
}
void checkRAM(const __FlashStringHelper* flashString, int a ) {
String s=String(a);
checkRAM(flashString,s);
}
void checkRAM(const __FlashStringHelper* flashString, String &a ) {
String s = flashString;
checkRAM(s,a);
}
void checkRAM(String &flashString, String &a ) {
String s = flashString;
s+=" (";
s+=a;
s+=")";
checkRAM(s);
}
void checkRAM( const __FlashStringHelper* flashString)
{
uint16_t freeRAM = FreeMem();
String s = flashString;
myRamTracker.registerRamState(s);
uint32_t freeRAM = FreeMem();
if (freeRAM < lowestRAM)
{
@@ -2294,6 +2600,11 @@ void checkRAM( const __FlashStringHelper* flashString)
}
}
void checkRAM( String &a ) {
myRamTracker.registerRamState(a);
}
#ifdef PLUGIN_BUILD_TESTING
#define isdigit(n) (n >= '0' && n <= '9')
@@ -2312,12 +2623,13 @@ void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) {
/********************************************************************************************\
Play RTTTL string on specified pin
\*********************************************************************************************/
void play_rtttl(uint8_t _pin, char *p )
void play_rtttl(uint8_t _pin, const char *p )
{
checkRAM(F("play_rtttl"));
#define OCTAVE_OFFSET 0
// Absolutely no error checking in here
// FIXME: Absolutely no error checking in here
const int notes[] = { 0,
int notes[] = { 0,
262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494,
523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988,
1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976,
@@ -2464,6 +2776,7 @@ void play_rtttl(uint8_t _pin, char *p )
delay(duration/10);
}
}
checkRAM(F("play_rtttl2"));
}
#endif
@@ -2476,6 +2789,7 @@ void play_rtttl(uint8_t _pin, char *p )
void ArduinoOTAInit()
{
checkRAM(F("ArduinoOTAInit"));
// Default port is 8266
ArduinoOTA.setPort(8266);
ArduinoOTA.setHostname(Settings.Name);
@@ -2494,7 +2808,12 @@ void ArduinoOTAInit()
//so dont touch device until restart is complete
Serial.println(F("\nOTA : DO NOT RESET OR POWER OFF UNTIL BOOT+FLASH IS COMPLETE."));
delay(100);
ESP.reset();
#if defined(ESP8266)
ESP.reset();
#endif
#if defined(ESP32)
ESP.restart();
#endif
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
@@ -2510,7 +2829,12 @@ void ArduinoOTAInit()
else if (error == OTA_END_ERROR) Serial.println(F("End Failed"));
delay(100);
ESP.reset();
#if defined(ESP8266)
ESP.reset();
#endif
#if defined(ESP32)
ESP.restart();
#endif
});
ArduinoOTA.begin();
@@ -2520,3 +2844,20 @@ void ArduinoOTAInit()
}
#endif
// Compute the dew point temperature, given temperature and humidity (temp in Celcius)
// Formula: http://www.ajdesigner.com/phphumidity/dewpoint_equation_dewpoint_temperature.php
// Td = (f/100)^(1/8) * (112 + 0.9*T) + 0.1*T - 112
float compute_dew_point_temp(float temperature, float humidity_percentage) {
return pow(humidity_percentage / 100.0, 0.125) *
(112.0 + 0.9*temperature) + 0.1*temperature - 112.0;
}
// Compute the humidity given temperature and dew point temperature (temp in Celcius)
// Formula: http://www.ajdesigner.com/phphumidity/dewpoint_equation_relative_humidity.php
// f = 100 * ((112 - 0.1*T + Td) / (112 + 0.9 * T))^8
float compute_humidity_from_dewpoint(float temperature, float dew_temperature) {
return 100.0 * pow((112.0 - 0.1 * temperature + dew_temperature) /
(112.0 + 0.9 * temperature), 8);
}
+195 -15
View File
@@ -2,6 +2,10 @@
// Syslog
// UDP system messaging
// SSDP
#if LWIP_VERSION_MAJOR == 2
#define IP2STR(addr) (uint8_t)((uint32_t)addr & 0xFF), (uint8_t)(((uint32_t)addr >> 8) & 0xFF), (uint8_t)(((uint32_t)addr >> 16) & 0xFF), (uint8_t)(((uint32_t)addr >> 24) & 0xFF)
#endif
/*********************************************************************************************\
Syslog client
@@ -32,14 +36,49 @@ void syslog(const char *message)
}
/*********************************************************************************************\
Structs for UDP messaging
\*********************************************************************************************/
struct infoStruct
{
byte header = 255;
byte ID = 3;
byte sourcelUnit;
byte destUnit;
byte sourceTaskIndex;
byte destTaskIndex;
byte deviceNumber;
char taskName[26];
char ValueNames[VARS_PER_TASK][26];
};
struct dataStruct
{
byte header = 255;
byte ID = 5;
byte sourcelUnit;
byte destUnit;
byte sourceTaskIndex;
byte destTaskIndex;
float Values[VARS_PER_TASK];
};
//TODO: add sysinfoStruct
/*********************************************************************************************\
Check UDP messages (ESPEasy propiertary protocol)
\*********************************************************************************************/
boolean runningUPDCheck = false;
void checkUDP()
{
if (Settings.UDPPort == 0)
return;
if (runningUPDCheck)
return;
runningUPDCheck = true;
// UDP events
int packetSize = portUDP.parsePacket();
if (packetSize)
@@ -50,6 +89,7 @@ void checkUDP()
if (portUDP.remotePort() == 123)
{
// unexpected NTP reply, drop for now...
runningUPDCheck = false;
return;
}
char packetBuffer[128];
@@ -68,10 +108,22 @@ void checkUDP()
}
else
{
if (packetBuffer[1] > 1 && packetBuffer[1] < 6)
{
String log = (F("UDP : Sensor msg "));
for (byte x = 1; x < 6; x++)
{
log += " ";
log += (int)packetBuffer[x];
}
addLog(LOG_LEVEL_DEBUG_MORE, log);
}
// binary data!
switch (packetBuffer[1])
{
//TODO: use a nice struct for it
case 1: // sysinfo message
{
byte mac[6];
@@ -99,27 +151,155 @@ void checkUDP()
}
char macaddress[20];
sprintf_P(macaddress, PSTR("%02x:%02x:%02x:%02x:%02x:%02x"), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
char ipaddress[16];
sprintf_P(ipaddress, PSTR("%u.%u.%u.%u"), ip[0], ip[1], ip[2], ip[3]);
formatMAC(mac, macaddress);
char ipaddress[20];
formatIP(ip, ipaddress);
char log[80];
sprintf_P(log, PSTR("UDP : %s,%s,%u"), macaddress, ipaddress, unit);
addLog(LOG_LEVEL_DEBUG_MORE, log);
break;
}
case 2: // sensor info pull request
{
SendUDPTaskInfo(packetBuffer[2], packetBuffer[5], packetBuffer[4]);
break;
}
case 3: // sensor info
{
if (Settings.GlobalSync)
{
struct infoStruct infoReply;
memcpy((byte*)&infoReply, (byte*)&packetBuffer, sizeof(infoStruct));
// to prevent flash wear out (bugs in communication?) we can only write to an empty task
// so it will write only once and has to be cleared manually through webgui
if (Settings.TaskDeviceNumber[infoReply.destTaskIndex] == 0)
{
Settings.TaskDeviceNumber[infoReply.destTaskIndex] = infoReply.deviceNumber;
Settings.TaskDeviceDataFeed[infoReply.destTaskIndex] = 1; // remote feed
for (byte x=0; x < CONTROLLER_MAX; x++)
Settings.TaskDeviceSendData[x][infoReply.destTaskIndex] = false;
strcpy(ExtraTaskSettings.TaskDeviceName, infoReply.taskName);
for (byte x = 0; x < VARS_PER_TASK; x++)
strcpy( ExtraTaskSettings.TaskDeviceValueNames[x], infoReply.ValueNames[x]);
SaveTaskSettings(infoReply.destTaskIndex);
SaveSettings();
}
}
break;
}
case 4: // sensor data pull request
{
SendUDPTaskData(packetBuffer[2], packetBuffer[5], packetBuffer[4]);
break;
}
case 5: // sensor data
{
if (Settings.GlobalSync)
{
struct dataStruct dataReply;
memcpy((byte*)&dataReply, (byte*)&packetBuffer, sizeof(dataStruct));
// only if this task has a remote feed, update values
if (Settings.TaskDeviceDataFeed[dataReply.destTaskIndex] != 0)
{
for (byte x = 0; x < VARS_PER_TASK; x++)
{
UserVar[dataReply.destTaskIndex * VARS_PER_TASK + x] = dataReply.Values[x];
}
if (Settings.UseRules)
createRuleEvents(dataReply.destTaskIndex);
}
}
break;
}
default:
{
struct EventStruct TempEvent;
TempEvent.Data = (byte*)packetBuffer;
TempEvent.Par1 = remoteIP[3];
PluginCall(PLUGIN_UDP_IN, &TempEvent, dummyString);
CPluginCall(CPLUGIN_UDP_IN, &TempEvent);
break;
}
}
}
}
#if defined(ESP32) // testing
portUDP.flush();
#endif
runningUPDCheck = false;
}
/*********************************************************************************************\
Send task info using UDP message
\*********************************************************************************************/
void SendUDPTaskInfo(byte destUnit, byte sourceTaskIndex, byte destTaskIndex)
{
if (!WiFiConnected(100)) {
return;
}
struct infoStruct infoReply;
infoReply.sourcelUnit = Settings.Unit;
infoReply.sourceTaskIndex = sourceTaskIndex;
infoReply.destTaskIndex = destTaskIndex;
LoadTaskSettings(infoReply.sourceTaskIndex);
infoReply.deviceNumber = Settings.TaskDeviceNumber[infoReply.sourceTaskIndex];
strcpy(infoReply.taskName, ExtraTaskSettings.TaskDeviceName);
for (byte x = 0; x < VARS_PER_TASK; x++)
strcpy(infoReply.ValueNames[x], ExtraTaskSettings.TaskDeviceValueNames[x]);
byte firstUnit = 1;
byte lastUnit = UNIT_MAX - 1;
if (destUnit != 0)
{
firstUnit = destUnit;
lastUnit = destUnit;
}
for (byte x = firstUnit; x <= lastUnit; x++)
{
infoReply.destUnit = x;
sendUDP(x, (byte*)&infoReply, sizeof(infoStruct));
delay(10);
}
delay(50);
}
/*********************************************************************************************\
Send task data using UDP message
\*********************************************************************************************/
void SendUDPTaskData(byte destUnit, byte sourceTaskIndex, byte destTaskIndex)
{
if (!WiFiConnected(100)) {
return;
}
struct dataStruct dataReply;
dataReply.sourcelUnit = Settings.Unit;
dataReply.sourceTaskIndex = sourceTaskIndex;
dataReply.destTaskIndex = destTaskIndex;
for (byte x = 0; x < VARS_PER_TASK; x++)
dataReply.Values[x] = UserVar[dataReply.sourceTaskIndex * VARS_PER_TASK + x];
byte firstUnit = 1;
byte lastUnit = UNIT_MAX - 1;
if (destUnit != 0)
{
firstUnit = destUnit;
lastUnit = destUnit;
}
for (byte x = firstUnit; x <= lastUnit; x++)
{
dataReply.destUnit = x;
sendUDP(x, (byte*) &dataReply, sizeof(dataStruct));
delay(10);
}
delay(50);
}
@@ -253,7 +433,7 @@ void sendSysInfoUDP(byte repeats)
}
}
#if defined(ESP8266)
/********************************************************************************************\
Respond to HTTP XML requests for SSDP information
\*********************************************************************************************/
@@ -262,10 +442,8 @@ void SSDP_schema(WiFiClient &client) {
return;
}
IPAddress ip = WiFi.localIP();
char str[20];
sprintf_P(str, PSTR("%u.%u.%u.%u"), ip[0], ip[1], ip[2], ip[3]);
uint32_t chipId = ESP.getChipId();
const IPAddress ip = WiFi.localIP();
const uint32_t chipId = ESP.getChipId();
char uuid[64];
sprintf_P(uuid, PSTR("38323636-4558-4dda-9188-cda0e6%02x%02x%02x"),
(uint16_t) ((chipId >> 16) & 0xff),
@@ -285,7 +463,7 @@ void SSDP_schema(WiFiClient &client) {
"<minor>0</minor>"
"</specVersion>"
"<URLBase>http://");
ssdp_schema += str;
ssdp_schema += formatIP(ip);
ssdp_schema += F(":80/</URLBase>"
"<device>"
"<deviceType>urn:schemas-upnp-org:device:BinaryLight:1</deviceType>"
@@ -573,6 +751,7 @@ void SSDP_update() {
_server->flush();
}
}
#endif
// Check WiFi connection. Maximum timeout 500 msec.
bool WiFiConnected(uint32_t timeout_ms) {
@@ -582,11 +761,6 @@ bool WiFiConnected(uint32_t timeout_ms) {
yield(); // Allow at least once time for backgroundtasks
min_delay = 10;
}
if (!wifiConnected) {
// Apparently something needs network, perform check to see if it is ready now.
if (tryConnectWiFi())
checkWifiJustConnected();
}
while (WiFi.status() != WL_CONNECTED) {
if (timeOutReached(timer)) {
return false;
@@ -600,7 +774,12 @@ bool hostReachable(const IPAddress& ip) {
// Only do 1 ping at a time to return early
byte retry = 3;
while (retry > 0) {
#if defined(ESP8266)
if (Ping.ping(ip, 1)) return true;
#endif
#if defined(ESP32)
if (ping_start(ip, 4, 0, 0, 5)) return true;
#endif
delay(50);
--retry;
}
@@ -619,3 +798,4 @@ bool hostReachable(const String& hostname) {
addLog(LOG_LEVEL_ERROR, log);
return false;
}
-2
View File
@@ -288,8 +288,6 @@ void parseSystemVariables(String& s, boolean useURLencode)
if (s.indexOf(F("%sys")) != -1) {
SMART_REPL(F("%sysload%"), String(100 - (100 * loopCounterLast / loopCounterMax)))
SMART_REPL(F("%systm_hm%"), getTimeString(':', false))
SMART_REPL(F("%systm_hm_am%"), getTimeString_ampm(':', false))
SMART_REPL(F("%systime%"), getTimeString(':'))
SMART_REPL(F("%systime_am%"), getTimeString_ampm(':'))
repl(F("%sysname%"), Settings.Name, s, useURLencode);
+11 -21
View File
@@ -390,40 +390,30 @@ String getDateString()
// returns the current Time separated by the given delimiter
// time format example with ':' delimiter: 23:59:59 (HH:MM:SS)
String getTimeString(const timeStruct& ts, char delimiter, bool am_pm, bool show_seconds)
String getTimeString(const timeStruct& ts, char delimiter, bool am_pm)
{
char TimeString[20]; //19 digits plus the null char
if (am_pm) {
uint8_t hour(ts.Hour % 12);
if (hour == 0) { hour = 12; }
const char a_or_p = ts.Hour < 12 ? 'A' : 'P';
if (show_seconds) {
sprintf_P(TimeString, PSTR("%d%c%02d%c%02d %cM"),
hour, delimiter, ts.Minute, delimiter, ts.Second, a_or_p);
} else {
sprintf_P(TimeString, PSTR("%d%c%02d %cM"),
hour, delimiter, ts.Minute, a_or_p);
}
sprintf_P(TimeString, PSTR("%02d%c%02d%c%02d%cm"),
hour, delimiter, ts.Minute, delimiter, ts.Second,
ts.Hour < 12 ? 'a' : 'p');
} else {
if (show_seconds) {
sprintf_P(TimeString, PSTR("%02d%c%02d%c%02d"),
ts.Hour, delimiter, ts.Minute, delimiter, ts.Second);
} else {
sprintf_P(TimeString, PSTR("%d%c%02d"),
ts.Hour, delimiter, ts.Minute);
}
sprintf_P(TimeString, PSTR("%02d%c%02d%c%02d"),
ts.Hour, delimiter, ts.Minute, delimiter, ts.Second);
}
return TimeString;
}
String getTimeString(char delimiter, bool show_seconds /*=true*/)
String getTimeString(char delimiter)
{
return getTimeString(tm, delimiter, false, show_seconds);
return getTimeString(tm, delimiter, false);
}
String getTimeString_ampm(char delimiter, bool show_seconds /*=true*/)
String getTimeString_ampm(char delimiter)
{
return getTimeString(tm, delimiter, true, show_seconds);
return getTimeString(tm, delimiter, true);
}
// returns the current Time without delimiter
@@ -446,7 +436,7 @@ String getDateTimeString(const timeStruct& ts, char dateDelimiter, char timeDeli
String ret = getDateString(ts, dateDelimiter);
if (dateTimeDelimiter != '\0')
ret += dateTimeDelimiter;
ret += getTimeString(ts, timeDelimiter, am_pm, true);
ret += getTimeString(ts, timeDelimiter, am_pm);
return ret;
}
+282 -128
View File
@@ -76,15 +76,6 @@ public:
}
void startStream() {
startStream(false);
}
void startJsonStream() {
startStream(true);
}
private:
void startStream(bool json) {
maxCoreUsage = maxServerUsage = 0;
initialRam = ESP.getFreeHeap();
beforeTXRam = initialRam;
@@ -93,10 +84,12 @@ private:
if (beforeTXRam < 3000) {
lowMemorySkip = true;
WebServer.send(200, "text/plain", "Low memory. Cannot display webpage :-(");
tcpCleanup();
#if defined(ESP8266)
tcpCleanup();
#endif
return;
} else
sendHeaderBlocking(json);
sendHeaderBlocking();
}
void trackTotalMem() {
@@ -105,8 +98,6 @@ private:
maxServerUsage = initialRam - beforeTXRam;
}
public:
void trackCoreMem() {
duringTXRam = ESP.getFreeHeap();
if ((initialRam - duringTXRam) > maxCoreUsage)
@@ -167,14 +158,14 @@ void sendContentBlocking(String& data) {
data = "";
}
void sendHeaderBlocking(bool json) {
void sendHeaderBlocking() {
checkRAM(F("sendHeaderBlocking"));
#if defined(ESP8266) && defined(ARDUINO_ESP8266_RELEASE_2_3_0)
WebServer.setContentLength(CONTENT_LENGTH_UNKNOWN);
WebServer.sendHeader(F("Content-Type"), json ? F("application/json") : F("text/html"), true);
WebServer.sendHeader(F("Accept-Ranges"), F("none"));
WebServer.sendHeader(F("Cache-Control"), F("no-cache"));
WebServer.sendHeader(F("Transfer-Encoding"), F("chunked"));
WebServer.sendHeader("Content-Type", "text/html", true);
WebServer.sendHeader("Accept-Ranges", "none");
WebServer.sendHeader("Cache-Control", "no-cache");
WebServer.sendHeader("Transfer-Encoding", "chunked");
WebServer.send(200);
#else
unsigned int timeout = 0;
@@ -183,8 +174,8 @@ void sendHeaderBlocking(bool json) {
if (freeBeforeSend < 4000) timeout = 1000;
const uint32_t beginWait = millis();
WebServer.setContentLength(CONTENT_LENGTH_UNKNOWN);
WebServer.sendHeader(F("Content-Type"), json ? F("application/json") : F("text/html"), true);
WebServer.sendHeader(F("Cache-Control"), F("no-cache"));
WebServer.sendHeader("Content-Type", "text/html", true);
WebServer.sendHeader("Cache-Control", "no-cache");
WebServer.send(200);
// dont wait on 2.3.0. Memory returns just too slow.
while ((ESP.getFreeHeap() < freeBeforeSend) &&
@@ -284,13 +275,96 @@ void sendHeadandTail(const String& tmplName, boolean Tail = false) {
}
}
boolean ipLessEqual(const IPAddress& ip, const IPAddress& high)
{
for (byte i = 0; i < 4; ++i) {
if (ip[i] > high[i]) return false;
}
return true;
}
boolean ipInRange(const IPAddress& ip, const IPAddress& low, const IPAddress& high)
{
return (ipLessEqual(low, ip) && ipLessEqual(ip, high));
}
String describeAllowedIPrange() {
String reply;
switch (SecuritySettings.IPblockLevel) {
case ALL_ALLOWED:
reply += F("All Allowed");
break;
default:
{
IPAddress low, high;
getIPallowedRange(low, high);
reply += formatIP(low);
reply += F(" - ");
reply += formatIP(high);
}
}
return reply;
}
bool getIPallowedRange(IPAddress& low, IPAddress& high)
{
switch (SecuritySettings.IPblockLevel) {
case LOCAL_SUBNET_ALLOWED:
return getSubnetRange(low, high);
case ONLY_IP_RANGE_ALLOWED:
low = SecuritySettings.AllowedIPrangeLow;
high = SecuritySettings.AllowedIPrangeHigh;
break;
default:
low = IPAddress(0,0,0,0);
high = IPAddress(255,255,255,255);
return false;
}
return true;
}
boolean clientIPallowed()
{
// TD-er Must implement "safe time after boot"
IPAddress low, high;
if (!getIPallowedRange(low, high))
{
// No subnet range determined, cannot filter on IP
return true;
}
WiFiClient client(WebServer.client());
if (ipInRange(client.remoteIP(), low, high))
return true;
String response = F("IP blocked: ");
response += formatIP(client.remoteIP());
WebServer.send(403, "text/html", response);
response += F(" Allowed: ");
response += formatIP(low);
response += F(" - ");
response += formatIP(high);
addLog(LOG_LEVEL_ERROR, response);
return false;
}
void clearAccessBlock()
{
SecuritySettings.IPblockLevel = ALL_ALLOWED;
}
//********************************************************************************
// Web Interface init
//********************************************************************************
#include "core_version.h"
//#include "core_version.h"
#define HTML_SYMBOL_WARNING "&#9888;"
#define TASKS_PER_PAGE 12
#if defined(ESP8266)
#define TASKS_PER_PAGE 12
#endif
#if defined(ESP32)
#define TASKS_PER_PAGE 32
#endif
static const char pgDefaultCSS[] PROGMEM = {
//color scheme: #07D #D50 #DB0 #A0D
@@ -691,7 +765,7 @@ void addFooter(String& str)
// Web Interface root page
//********************************************************************************
void handle_root() {
Serial.println("handleroot");
checkRAM(F("handle_root"));
// if Wifi setup, launch setup wizard
if (wifiSetup)
{
@@ -881,7 +955,9 @@ void handle_root() {
//********************************************************************************
void handle_config() {
if (!isLoggedIn()) return;
checkRAM(F("handle_config"));
if (!isLoggedIn()) return;
navMenuIndex = 1;
TXBuffer.startStream();
sendHeadandTail(F("TmplStd"),_HEAD);
@@ -928,6 +1004,29 @@ void handle_config() {
//strncpy(SecuritySettings.WifiAPKey, apkey.c_str(), sizeof(SecuritySettings.WifiAPKey));
copyFormPassword(F("apkey"), SecuritySettings.WifiAPKey, sizeof(SecuritySettings.WifiAPKey));
// TD-er Read access control from form.
SecuritySettings.IPblockLevel = getFormItemInt(F("ipblocklevel"));
switch (SecuritySettings.IPblockLevel) {
case LOCAL_SUBNET_ALLOWED:
{
IPAddress low, high;
getSubnetRange(low, high);
for (byte i=0; i < 4; ++i) {
SecuritySettings.AllowedIPrangeLow[i] = low[i];
SecuritySettings.AllowedIPrangeHigh[i] = high[i];
}
break;
}
case ONLY_IP_RANGE_ALLOWED:
case ALL_ALLOWED:
// iprangelow.toCharArray(tmpString, 26);
str2ip(iprangelow, SecuritySettings.AllowedIPrangeLow);
// iprangehigh.toCharArray(tmpString, 26);
str2ip(iprangehigh, SecuritySettings.AllowedIPrangeHigh);
break;
}
Settings.Delay = sensordelay.toInt();
Settings.deepSleep = deepsleep.toInt();
Settings.deepSleepOnFail = (deepsleeponfail == "on");
@@ -958,6 +1057,22 @@ void handle_config() {
addFormSeparator(TXBuffer.buf );
addFormPasswordBox( TXBuffer.buf, F("WPA AP Mode Key"), F("apkey"), SecuritySettings.WifiAPKey, 63);
// TD-er add IP access box F("ipblocklevel")
addFormSubHeader( TXBuffer.buf, F("Client IP filtering"));
{
IPAddress low, high;
getIPallowedRange(low, high);
byte iplow[4];
byte iphigh[4];
for (byte i = 0; i < 4; ++i) {
iplow[i] = low[i];
iphigh[i] = high[i];
}
addFormIPaccessControlSelect( TXBuffer.buf, F("Client IP block level"), F("ipblocklevel"), SecuritySettings.IPblockLevel);
addFormIPBox( TXBuffer.buf, F("Access IP lower range"), F("iprangelow"), iplow);
addFormIPBox( TXBuffer.buf, F("Access IP upper range"), F("iprangehigh"), iphigh);
}
addFormSubHeader( TXBuffer.buf, F("IP Settings"));
addFormIPBox(TXBuffer.buf, F("ESP IP"), F("espip"), Settings.IP);
@@ -994,6 +1109,7 @@ void handle_config() {
// Web Interface controller page
//********************************************************************************
void handle_controllers() {
checkRAM(F("handle_controllers"));
if (!isLoggedIn()) return;
navMenuIndex = 2;
TXBuffer.startStream();
@@ -1065,7 +1181,11 @@ void handle_controllers() {
ControllerSettings.UseDNS = usedns.toInt();
if (ControllerSettings.UseDNS)
{
ControllerSettings.setHostname(controllerhostname);
strncpy(ControllerSettings.HostName, controllerhostname.c_str(), sizeof(ControllerSettings.HostName));
IPAddress IP;
WiFi.hostByName(ControllerSettings.HostName, IP);
for (byte x = 0; x < 4; x++)
ControllerSettings.IP[x] = IP[x];
}
//no protocol selected
else
@@ -1080,7 +1200,6 @@ void handle_controllers() {
copyFormPassword(F("controllerpassword"), SecuritySettings.ControllerPassword[controllerindex], sizeof(SecuritySettings.ControllerPassword[0]));
strncpy(ControllerSettings.Subscribe, controllersubscribe.c_str(), sizeof(ControllerSettings.Subscribe));
strncpy(ControllerSettings.Publish, controllerpublish.c_str(), sizeof(ControllerSettings.Publish));
CPlugin_ptr[ProtocolIndex](CPLUGIN_INIT, &TempEvent, dummyString);
}
}
addHtmlError( TXBuffer.buf, SaveControllerSettings(controllerindex, (byte*)&ControllerSettings, sizeof(ControllerSettings)));
@@ -1159,60 +1278,56 @@ void handle_controllers() {
options[0] = F("Use IP address");
options[1] = F("Use Hostname");
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[controllerindex]);
if (!Protocol[ProtocolIndex].Custom){
addFormSelector(TXBuffer.buf, F("Locate Controller"), F("usedns"), 2, options, NULL, NULL, choice, true);
if (ControllerSettings.UseDNS)
{
addFormTextBox(TXBuffer.buf, F("Controller Hostname"), F("controllerhostname"), ControllerSettings.HostName, sizeof(ControllerSettings.HostName)-1);
}
else
{
addFormIPBox(TXBuffer.buf, F("Controller IP"), F("controllerip"), ControllerSettings.IP);
}
addFormNumericBox(TXBuffer.buf, F("Controller Port"), F("controllerport"), ControllerSettings.Port, 1, 65535);
if (Protocol[ProtocolIndex].usesAccount)
{
String protoDisplayName;
if (!getControllerProtocolDisplayName(ProtocolIndex, CONTROLLER_USER, protoDisplayName)) {
protoDisplayName = F("Controller User");
}
addFormTextBox(TXBuffer.buf, protoDisplayName, F("controlleruser"), SecuritySettings.ControllerUser[controllerindex], sizeof(SecuritySettings.ControllerUser[0])-1);
}
if (Protocol[ProtocolIndex].usesPassword)
{
String protoDisplayName;
if (getControllerProtocolDisplayName(ProtocolIndex, CONTROLLER_PASS, protoDisplayName)) {
// It is not a regular password, thus use normal text field.
addFormTextBox(TXBuffer.buf, protoDisplayName, F("controllerpassword"), SecuritySettings.ControllerPassword[controllerindex], sizeof(SecuritySettings.ControllerPassword[0])-1);
} else {
addFormPasswordBox(TXBuffer.buf, F("Controller Password"), F("controllerpassword"), SecuritySettings.ControllerPassword[controllerindex], sizeof(SecuritySettings.ControllerPassword[0])-1);
}
}
if (Protocol[ProtocolIndex].usesTemplate || Protocol[ProtocolIndex].usesMQTT)
{
String protoDisplayName;
if (!getControllerProtocolDisplayName(ProtocolIndex, CONTROLLER_SUBSCRIBE, protoDisplayName)) {
protoDisplayName = F("Controller Subscribe");
}
addFormTextBox(TXBuffer.buf, protoDisplayName, F("controllersubscribe"), ControllerSettings.Subscribe, sizeof(ControllerSettings.Subscribe)-1);
}
if (Protocol[ProtocolIndex].usesTemplate || Protocol[ProtocolIndex].usesMQTT)
{
String protoDisplayName;
if (!getControllerProtocolDisplayName(ProtocolIndex, CONTROLLER_PUBLISH, protoDisplayName)) {
protoDisplayName = F("Controller Publish");
}
addFormTextBox(TXBuffer.buf, protoDisplayName, F("controllerpublish"), ControllerSettings.Publish, sizeof(ControllerSettings.Publish)-1);
}
addFormSelector(TXBuffer.buf, F("Locate Controller"), F("usedns"), 2, options, NULL, NULL, choice, true);
if (ControllerSettings.UseDNS)
{
addFormTextBox(TXBuffer.buf, F("Controller Hostname"), F("controllerhostname"), ControllerSettings.HostName, sizeof(ControllerSettings.HostName)-1);
}
else
{
addFormIPBox(TXBuffer.buf, F("Controller IP"), F("controllerip"), ControllerSettings.IP);
}
addFormNumericBox(TXBuffer.buf, F("Controller Port"), F("controllerport"), ControllerSettings.Port, 1, 65535);
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[controllerindex]);
if (Protocol[ProtocolIndex].usesAccount)
{
String protoDisplayName;
if (!getControllerProtocolDisplayName(ProtocolIndex, CONTROLLER_USER, protoDisplayName)) {
protoDisplayName = F("Controller User");
}
addFormTextBox(TXBuffer.buf, protoDisplayName, F("controlleruser"), SecuritySettings.ControllerUser[controllerindex], sizeof(SecuritySettings.ControllerUser[0])-1);
}
if (Protocol[ProtocolIndex].usesPassword)
{
String protoDisplayName;
if (getControllerProtocolDisplayName(ProtocolIndex, CONTROLLER_PASS, protoDisplayName)) {
// It is not a regular password, thus use normal text field.
addFormTextBox(TXBuffer.buf, protoDisplayName, F("controllerpassword"), SecuritySettings.ControllerPassword[controllerindex], sizeof(SecuritySettings.ControllerPassword[0])-1);
} else {
addFormPasswordBox(TXBuffer.buf, F("Controller Password"), F("controllerpassword"), SecuritySettings.ControllerPassword[controllerindex], sizeof(SecuritySettings.ControllerPassword[0])-1);
}
}
if (Protocol[ProtocolIndex].usesTemplate || Protocol[ProtocolIndex].usesMQTT)
{
String protoDisplayName;
if (!getControllerProtocolDisplayName(ProtocolIndex, CONTROLLER_SUBSCRIBE, protoDisplayName)) {
protoDisplayName = F("Controller Subscribe");
}
addFormTextBox(TXBuffer.buf, protoDisplayName, F("controllersubscribe"), ControllerSettings.Subscribe, sizeof(ControllerSettings.Subscribe)-1);
}
if (Protocol[ProtocolIndex].usesTemplate || Protocol[ProtocolIndex].usesMQTT)
{
String protoDisplayName;
if (!getControllerProtocolDisplayName(ProtocolIndex, CONTROLLER_PUBLISH, protoDisplayName)) {
protoDisplayName = F("Controller Publish");
}
addFormTextBox(TXBuffer.buf, protoDisplayName, F("controllerpublish"), ControllerSettings.Publish, sizeof(ControllerSettings.Publish)-1);
}
addFormCheckBox(TXBuffer.buf, F("Enabled"), F("controllerenabled"), Settings.ControllerEnabled[controllerindex]);
@@ -1238,6 +1353,7 @@ void handle_controllers() {
// Web Interface notifcations page
//********************************************************************************
void handle_notifications() {
checkRAM(F("handle_notifications"));
if (!isLoggedIn()) return;
navMenuIndex = 6;
TXBuffer.startStream();
@@ -1455,6 +1571,7 @@ void handle_notifications() {
// Web Interface hardware page
//********************************************************************************
void handle_hardware() {
checkRAM(F("handle_hardware"));
if (!isLoggedIn()) return;
navMenuIndex = 3;
TXBuffer.startStream();
@@ -1568,6 +1685,7 @@ void addIPaccessControlSelect(String& str, String name, int choice)
//********************************************************************************
//19480 (11128)
void handle_devices() {
checkRAM(F("handle_devices"));
if (!isLoggedIn()) return;
navMenuIndex = 4;
TXBuffer.startStream();
@@ -1721,6 +1839,18 @@ void handle_devices() {
if (Device[DeviceIndex].InverseLogicOption)
Settings.TaskDevicePin1Inversed[taskIndex] = (WebServer.arg(F("TDPI")) == F("on"));
if (Settings.GlobalSync)
{
if (Device[DeviceIndex].GlobalSyncOption)
Settings.TaskDeviceGlobalSync[taskIndex] = (WebServer.arg(F("TDGS")) == F("on"));
// Send task info if set global
if (Settings.TaskDeviceGlobalSync[taskIndex])
{
SendUDPTaskInfo(0, taskIndex, taskIndex);
}
}
for (byte varNr = 0; varNr < Device[DeviceIndex].ValueCount; varNr++)
{
@@ -1748,18 +1878,6 @@ void handle_devices() {
//allow the plugin to save plugin-specific form settings.
PluginCall(PLUGIN_WEBFORM_SAVE, &TempEvent, dummyString);
// notify controllers: CPLUGIN_TASK_CHANGE_NOTIFICATION
for (byte x=0; x < CONTROLLER_MAX; x++)
{
TempEvent.ControllerIndex = x;
if (Settings.TaskDeviceSendData[TempEvent.ControllerIndex][TempEvent.TaskIndex] &&
Settings.ControllerEnabled[TempEvent.ControllerIndex] && Settings.Protocol[TempEvent.ControllerIndex])
{
TempEvent.ProtocolIndex = getProtocolIndex(Settings.Protocol[TempEvent.ControllerIndex]);
CPlugin_ptr[TempEvent.ProtocolIndex](CPLUGIN_TASK_CHANGE_NOTIFICATION, &TempEvent, dummyString);
}
}
}
addHtmlError( SaveTaskSettings(taskIndex));
@@ -1958,6 +2076,11 @@ void handle_devices() {
addFormCheckBox(TXBuffer.buf, F("Enabled"), F("TDE"), Settings.TaskDeviceEnabled[taskIndex]); //="taskdeviceenabled"
if (Settings.GlobalSync && Device[DeviceIndex].GlobalSyncOption && Settings.TaskDeviceDataFeed[taskIndex] == 0 && Settings.UDPPort != 0)
{
addFormCheckBox(TXBuffer.buf, F("Global Sync"), F("TDGS"), Settings.TaskDeviceGlobalSync[taskIndex]); //="taskdeviceglobalsync"
}
// section: Sensor / Actuator
if (!Device[DeviceIndex].Custom && Settings.TaskDeviceDataFeed[taskIndex] == 0 &&
((Device[DeviceIndex].Ports != 0) || (Device[DeviceIndex].PullUpOption) || (Device[DeviceIndex].InverseLogicOption) || (Device[DeviceIndex].Type >= DEVICE_TYPE_SINGLE && Device[DeviceIndex].Type <= DEVICE_TYPE_TRIPLE)) )
@@ -3009,6 +3132,7 @@ void handle_tools() {
// Web Interface pin state list
//********************************************************************************
void handle_pinstates() {
checkRAM(F("handle_pinstates"));
if (!isLoggedIn()) return;
navMenuIndex = 7;
TXBuffer.startStream();
@@ -3072,6 +3196,7 @@ void handle_pinstates() {
// Web Interface I2C scanner
//********************************************************************************
void handle_i2cscanner() {
checkRAM(F("handle_i2cscanner"));
if (!isLoggedIn()) return;
navMenuIndex = 7;
TXBuffer.startStream();
@@ -3214,6 +3339,7 @@ void handle_i2cscanner() {
// Web Interface Wifi scanner
//********************************************************************************
void handle_wifiscanner() {
checkRAM(F("handle_wifiscanner"));
if (!isLoggedIn()) return;
navMenuIndex = 7;
TXBuffer.startStream();
@@ -3251,6 +3377,8 @@ void handle_wifiscanner() {
// Web Interface login page
//********************************************************************************
void handle_login() {
checkRAM(F("handle_login"));
if (!clientIPallowed()) return;
TXBuffer.startStream();
sendHeadandTail(F("TmplStd"),_HEAD);
@@ -3300,8 +3428,11 @@ void handle_login() {
// Web Interface control page (no password!)
//********************************************************************************
void handle_control() {
checkRAM(F("handle_control"));
if (!clientIPallowed()) return;
//TXBuffer.startStream(true); // true= json
// sendHeadandTail(F("TmplStd"),_HEAD);
// sendHeadandTail(F("TmplStd"),_HEAD);
String webrequest = WebServer.arg(F("cmd"));
// in case of event, store to buffer and return...
@@ -3320,18 +3451,18 @@ void handle_control() {
printToWeb = true;
printWebString = "";
if (printToWebJSON)
TXBuffer.startJsonStream();
else
TXBuffer.startStream();
if (PluginCall(PLUGIN_WRITE, &TempEvent, webrequest));
else if (remoteConfig(&TempEvent, webrequest));
else
TXBuffer += F("Unknown or restricted command!");
TXBuffer += printWebString;
TXBuffer.endStream();
TXBuffer += printWebString;
if (printToWebJSON)
WebServer.send(200, "application/json");
else
WebServer.send(200, "text/html");
printWebString = "";
printToWeb = false;
@@ -3345,7 +3476,8 @@ void handle_control() {
void handle_json()
{
String tasknr = WebServer.arg("tasknr");
String reply;
String reply = "";
if (tasknr.length() == 0)
{
reply += F("{\"System\":{\n");
@@ -3357,34 +3489,10 @@ void handle_json()
reply += F(",\n");
reply += to_json_object_value(F("Unit"), String(Settings.Unit));
reply += F(",\n");
reply += to_json_object_value(F("Name"), String(Settings.Name));
reply += F(",\n");
reply += to_json_object_value(F("Uptime"), String(wdcounter / 2));
reply += F(",\n");
reply += to_json_object_value(F("Free RAM"), String(ESP.getFreeHeap()));
reply += F("\n},\n");
reply += F("\"WiFi\":{\n");
reply += to_json_object_value(F("Hostname"), WiFi.hostname());
reply += F(",\n");
reply += to_json_object_value(F("IP"), WiFi.localIP().toString());
reply += F(",\n");
reply += to_json_object_value(F("Subnet Mask"), WiFi.subnetMask().toString());
reply += F(",\n");
reply += to_json_object_value(F("Gateway IP"), WiFi.gatewayIP().toString());
reply += F(",\n");
reply += to_json_object_value(F("MAC address"), WiFi.macAddress());
reply += F(",\n");
reply += to_json_object_value(F("DNS 1"), WiFi.dnsIP(0).toString());
reply += F(",\n");
reply += to_json_object_value(F("DNS 2"), WiFi.dnsIP(1).toString());
reply += F(",\n");
reply += to_json_object_value(F("SSID"), WiFi.SSID());
reply += F(",\n");
reply += to_json_object_value(F("BSSID"), WiFi.BSSIDstr());
reply += F(",\n");
reply += to_json_object_value(F("RSSI"), String(WiFi.RSSI()));
reply += F("\n},\n");
}
byte taskNr = tasknr.toInt();
@@ -3444,6 +3552,7 @@ void handle_json()
// Web Interface config page
//********************************************************************************
void handle_advanced() {
checkRAM(F("handle_advanced"));
if (!isLoggedIn()) return;
navMenuIndex = 7;
TXBuffer.startStream();
@@ -3477,9 +3586,12 @@ void handle_advanced() {
String usessdp = WebServer.arg(F("usessdp"));
String edit = WebServer.arg(F("edit"));
String wireclockstretchlimit = WebServer.arg(F("wireclockstretchlimit"));
String globalsync = WebServer.arg(F("globalsync"));
String userules = WebServer.arg(F("userules"));
String cft = WebServer.arg(F("cft"));
String MQTTRetainFlag = WebServer.arg(F("mqttretainflag"));
String ArduinoOTAEnable = WebServer.arg(F("arduinootaenable"));
if (edit.length() != 0)
@@ -3508,8 +3620,10 @@ void handle_advanced() {
Settings.UseSSDP = (usessdp == "on");
Settings.WireClockStretchLimit = wireclockstretchlimit.toInt();
Settings.UseRules = (userules == "on");
Settings.GlobalSync = (globalsync == "on");
Settings.ConnectionFailuresThreshold = cft.toInt();
Settings.MQTTRetainFlag = (MQTTRetainFlag == "on");
Settings.ArduinoOTAEnable = (ArduinoOTAEnable == "on");
addHtmlError( TXBuffer.buf, SaveSettings());
if (Settings.UseNTP)
@@ -3562,8 +3676,9 @@ void handle_advanced() {
addFormNumericBox(TXBuffer.buf, F("Baud Rate"), F("baudrate"), Settings.BaudRate, 0, 1000000);
addFormSubHeader(TXBuffer.buf, F("Inter-ESPEasy Network"));
addFormSubHeader(TXBuffer.buf, F("Inter-ESPEasy Network (experimental)"));
addFormCheckBox( TXBuffer.buf, F("Global Sync"), F("globalsync"), Settings.GlobalSync);
addFormNumericBox(TXBuffer.buf, F("UDP port"), F("udpport"), Settings.UDPPort, 0, 65535);
@@ -3581,6 +3696,8 @@ void handle_advanced() {
addFormNumericBox(TXBuffer.buf, F("I2C ClockStretchLimit"), F("wireclockstretchlimit"), Settings.WireClockStretchLimit); //TODO define limits
addFormCheckBox(TXBuffer.buf, F("Enable Arduino OTA"), F("arduinootaenable"), Settings.ArduinoOTAEnable);
addFormSeparator (TXBuffer.buf);
TXBuffer += F("<TR><TD><TD>");
@@ -3641,6 +3758,7 @@ void addLogLevelSelect(String& str, String name, int choice)
//********************************************************************************
boolean isLoggedIn()
{
if (!clientIPallowed()) return false;
if (SecuritySettings.Password[0] == 0)
WebLoggedIn = true;
@@ -3662,6 +3780,7 @@ boolean isLoggedIn()
//********************************************************************************
void handle_download()
{
checkRAM(F("handle_download"));
if (!isLoggedIn()) return;
navMenuIndex = 7;
// TXBuffer.startStream();
@@ -3712,6 +3831,7 @@ void handle_upload() {
// Web Interface upload page
//********************************************************************************
void handle_upload_post() {
checkRAM(F("handle_upload_post"));
if (!isLoggedIn()) return;
navMenuIndex = 7;
@@ -3746,6 +3866,7 @@ void handle_upload_post() {
//********************************************************************************
fs::File uploadFile;
void handleFileUpload() {
checkRAM(F("handleFileUpload"));
if (!isLoggedIn()) return;
static boolean valid = false;
@@ -3824,6 +3945,7 @@ void handleFileUpload() {
// Web Interface server web file from SPIFFS
//********************************************************************************
bool loadFromFS(boolean spiffs, String path) {
checkRAM(F("loadFromFS"));
if (!isLoggedIn()) return false;
statusLED(true);
@@ -3885,6 +4007,8 @@ bool loadFromFS(boolean spiffs, String path) {
// Web Interface custom page handler
//********************************************************************************
boolean handle_custom(String path) {
checkRAM(F("handle_custom"));
if (!clientIPallowed()) return false;
path = path.substring(1);
String reply = "";
@@ -4020,6 +4144,8 @@ boolean handle_custom(String path) {
// Web Interface file list
//********************************************************************************
void handle_filelist() {
checkRAM(F("handle_filelist"));
if (!clientIPallowed()) return;
navMenuIndex = 7;
TXBuffer.startStream();
sendHeadandTail(F("TmplStd"));
@@ -4112,6 +4238,8 @@ void handle_filelist() {
//********************************************************************************
#ifdef FEATURE_SD
void handle_SDfilelist() {
checkRAM(F("handle_SDfilelist"));
if (!clientIPallowed()) return;
navMenuIndex = 7;
TXBuffer.startStream();
sendHeadandTail(F("TmplStd"));
@@ -4256,6 +4384,7 @@ void handle_SDfilelist() {
// Web Interface handle other requests
//********************************************************************************
void handleNotFound() {
checkRAM(F("handleNotFound"));
if (wifiSetup)
{
@@ -4284,6 +4413,7 @@ void handleNotFound() {
// Web Interface Setup Wizard
//********************************************************************************
void handle_setup() {
checkRAM(F("handle_setup"));
// Do not check client IP range allowed.
TXBuffer.startStream();
sendHeadandTail(F("TmplAP"));
@@ -4417,6 +4547,7 @@ void handle_setup() {
// Web Interface rules page
//********************************************************************************
void handle_rules() {
checkRAM(F("handle_rules"));
if (!isLoggedIn()) return;
navMenuIndex = 5;
TXBuffer.startStream();
@@ -4500,7 +4631,6 @@ void handle_rules() {
TXBuffer += F("<TR><TD>Edit: ");
addSelector(TXBuffer.buf, F("set"), RULESETS_MAX, options, optionValues, NULL, choice, true);
addButton(TXBuffer.buf, fileName, F("Download to file"));
addHelpButton(TXBuffer.buf, F("Tutorial_Rules"));
// load form data from flash
@@ -4548,6 +4678,7 @@ void handle_rules() {
// Web Interface sysinfo page
//********************************************************************************
void handle_sysinfo() {
checkRAM(F("handle_sysinfo"));
if (!isLoggedIn()) return;
TXBuffer.startStream();
sendHeadandTail(F("TmplStd"));
@@ -4654,14 +4785,20 @@ void handle_sysinfo() {
{
TXBuffer += F("<TR><TD>Client IP<TD>");
WiFiClient client(WebServer.client());
WiFiClient client(WebServer.client());
TXBuffer += formatIP(client.remoteIP());
}
TXBuffer += F("<TR><TD>Allowed IP Range<TD>");
TXBuffer += describeAllowedIPrange();
TXBuffer += F("<TR><TD>Serial Port available:<TD>");
TXBuffer += String(SerialAvailableForWrite());
TXBuffer += F(" (");
TXBuffer += Serial.availableForWrite();
#if defined(ESP8266)
TXBuffer += Serial.availableForWrite();
#endif
TXBuffer += F(" , ");
TXBuffer += Serial.available();
TXBuffer += F(")");
@@ -4709,14 +4846,30 @@ void handle_sysinfo() {
TXBuffer += F(" [Development]");
#endif
TXBuffer += F("<TR><TD>Build Md5<TD>");
for (byte i = 0; i<16; i++) TXBuffer += String(CRCValues.compileTimeMD5[i],HEX);
TXBuffer += F("<TR><TD>Md5 check<TD>");
if (! CRCValues.checkPassed())
TXBuffer +="<font color = 'red'>fail !</font>";
else TXBuffer +="passed.";
TXBuffer += F("<TR><TD>Build time<TD>");
TXBuffer += String(CRCValues.compileDate);
TXBuffer += " ";
TXBuffer += String(CRCValues.compileTime);
TXBuffer += F("<TR><TD>Binary filename<TD>");
TXBuffer += String(CRCValues.binaryFilename);
TXBuffer += F("<TR><TD colspan=2><H3>ESP board</H3></TD></TR>");
TXBuffer += F("<TR><TD>ESP Chip ID<TD>");
#if defined(ESP8266)
TXBuffer += ESP.getChipId();
TXBuffer += F(" (0x");
String espChipId(ESP.getChipId(), HEX);
espChipId.toUpperCase();
String espChipId(ESP.getChipId(), HEX);
espChipId.toUpperCase();
TXBuffer += espChipId;
TXBuffer += F(")");
@@ -4945,5 +5098,6 @@ static const char favicon_8b_ico[] PROGMEM = {
unsigned int favicon_8b_ico_len = 1150;
void handle_favicon() {
checkRAM(F("handle_favicon"));
WebServer.send_P(200, PSTR("image/x-icon"), favicon_8b_ico, favicon_8b_ico_len);
}
+162 -290
View File
@@ -4,7 +4,7 @@
String WifiGetAPssid()
{
String ssid(Settings.Name);
ssid+=F("-");
ssid+=F("_");
ssid+=Settings.Unit;
return (ssid);
}
@@ -27,10 +27,7 @@ void WifiAPconfig()
{
// create and store unique AP SSID/PW to prevent ESP from starting AP mode with default SSID and No password!
// setup ssid for AP Mode when needed
String softAPSSID=WifiGetAPssid();
String pwd = SecuritySettings.WifiAPKey;
WiFi.softAP(softAPSSID.c_str(),pwd.c_str());
WiFi.softAP(WifiGetAPssid().c_str(), SecuritySettings.WifiAPKey);
// We start in STA mode
WifiAPMode(false);
@@ -47,7 +44,12 @@ void WifiAPconfig()
bool WifiIsAP()
{
byte wifimode = wifi_get_opmode();
#if defined(ESP8266)
byte wifimode = wifi_get_opmode();
#endif
#if defined(ESP32)
byte wifimode = WiFi.getMode();
#endif
return(wifimode == 2 || wifimode == 3); //apmode is enabled
}
@@ -77,307 +79,158 @@ void WifiAPMode(boolean state)
}
//********************************************************************************
// Set Wifi config
//********************************************************************************
bool prepareWiFi() {
String log = "";
char hostname[40];
strncpy(hostname, WifiGetHostname().c_str(), sizeof(hostname));
wifi_station_set_hostname(hostname);
//use static ip?
if (Settings.IP[0] != 0 && Settings.IP[0] != 255)
{
char str[20];
sprintf_P(str, PSTR("%u.%u.%u.%u"), Settings.IP[0], Settings.IP[1], Settings.IP[2], Settings.IP[3]);
log = F("IP : Static IP :");
log += str;
addLog(LOG_LEVEL_INFO, log);
IPAddress ip = Settings.IP;
IPAddress gw = Settings.Gateway;
IPAddress subnet = Settings.Subnet;
IPAddress dns = Settings.DNS;
WiFi.config(ip, gw, subnet, dns);
}
return selectValidWiFiSettings();
}
//********************************************************************************
// Configure network and connect to Wifi SSID and SSID2
//********************************************************************************
boolean WifiConnect(byte connectAttempts)
{
if (prepareWiFi()) {
//try to connect to one of the access points
bool connected = WifiConnectAndWait(connectAttempts);
if (!connected) {
if (selectNextWiFiSettings()) {
connected = WifiConnectAndWait(connectAttempts);
}
}
if (connected) {
return(true);
}
String log = "";
char hostname[40];
strncpy(hostname, WifiGetHostname().c_str(), sizeof(hostname));
#if defined(ESP8266)
wifi_station_set_hostname(hostname);
#endif
#if defined(ESP32)
WiFi.setHostname(hostname);
#endif
//use static ip?
if (Settings.IP[0] != 0 && Settings.IP[0] != 255)
{
const IPAddress ip = Settings.IP;
log = F("IP : Static IP :");
log += ip;
addLog(LOG_LEVEL_INFO, log);
const IPAddress gw = Settings.Gateway;
const IPAddress subnet = Settings.Subnet;
const IPAddress dns = Settings.DNS;
WiFi.config(ip, gw, subnet, dns);
}
//try to connect to one of the access points
if (WifiConnectSSID(SecuritySettings.WifiSSID, SecuritySettings.WifiKey, connectAttempts) ||
WifiConnectSSID(SecuritySettings.WifiSSID2, SecuritySettings.WifiKey2, connectAttempts))
{
// fix octet?
if (Settings.IP_Octet != 0 && Settings.IP_Octet != 255)
{
IPAddress ip = WiFi.localIP();
IPAddress gw = WiFi.gatewayIP();
IPAddress subnet = WiFi.subnetMask();
ip[3] = Settings.IP_Octet;
log = F("IP : Fixed IP octet:");
log += ip;
addLog(LOG_LEVEL_INFO, log);
WiFi.config(ip, gw, subnet);
}
#ifdef FEATURE_MDNS
String log = F("WIFI : ");
if (MDNS.begin(WifiGetHostname().c_str(), WiFi.localIP())) {
log += F("mDNS started, with name: ");
log += WifiGetHostname();
log += F(".local");
}
else{
log += F("mDNS failed");
}
addLog(LOG_LEVEL_INFO, log);
#endif
if (Settings.UseRules)
{
String event = F("WiFi#Connected");
rulesProcessing(event);
}
return(true);
}
addLog(LOG_LEVEL_ERROR, F("WIFI : Could not connect to AP!"));
//everything failed, activate AP mode (will deactivate automatically after a while if its connected again)
WifiAPMode(true);
return(false);
}
//********************************************************************************
// Start connect to WiFi and check later to see if connected.
//********************************************************************************
void WiFiConnectRelaxed() {
wifiConnected = false;
wifi_connect_attempt = 0;
if (prepareWiFi()) {
tryConnectWiFi();
return;
}
addLog(LOG_LEVEL_ERROR, F("WIFI : Could not connect to AP, no valid WiFi settings!"));
//everything failed, activate AP mode (will deactivate automatically after a while if its connected again)
WifiAPMode(true);
}
//********************************************************************************
// Manage WiFi credentials
//********************************************************************************
const char* getLastWiFiSettingsSSID() {
return lastWiFiSettings == 0 ? SecuritySettings.WifiSSID : SecuritySettings.WifiSSID2;
}
const char* getLastWiFiSettingsPassphrase() {
return lastWiFiSettings == 0 ? SecuritySettings.WifiKey : SecuritySettings.WifiKey2;
}
bool anyValidWifiSettings() {
if (wifiSettingsValid(SecuritySettings.WifiSSID, SecuritySettings.WifiKey))
return true;
if (wifiSettingsValid(SecuritySettings.WifiSSID2, SecuritySettings.WifiKey2))
return true;
addLog(LOG_LEVEL_ERROR, F("WIFI : No valid WiFi settings!"));
return false;
}
bool selectNextWiFiSettings() {
uint8_t tmp = lastWiFiSettings;
lastWiFiSettings = (lastWiFiSettings + 1) % 2;
if (!wifiSettingsValid(getLastWiFiSettingsSSID(), getLastWiFiSettingsPassphrase())) {
// other settings are not correct, switch back.
lastWiFiSettings = tmp;
return false; // Nothing changed.
}
return true;
}
bool selectValidWiFiSettings() {
if (wifiSettingsValid(getLastWiFiSettingsSSID(), getLastWiFiSettingsPassphrase()))
return true;
return selectNextWiFiSettings();
}
bool wifiSettingsValid(const char* ssid, const char* pass) {
if (ssid[0] == 0 || (strcasecmp(ssid, "ssid") == 0)) {
return false;
}
if (pass[0] == 0) return false;
if (strlen(ssid) > 32) return false;
if (strlen(pass) > 64) return false;
return true;
}
bool wifiConnectTimeoutReached() {
if (wifi_connect_attempt == 0) return true;
if (wifiSetupConnect) {
// Initial setup of WiFi, may take much longer since accesspoint is still active.
return timeOutReached(wifi_connect_timer + 20000);
}
// wait until it connects + add some device specific random offset to prevent
// all nodes overloading the accesspoint when turning on at the same time.
const unsigned int randomOffset_in_sec = wifi_connect_attempt == 1 ? 0 : 1000 * ((ESP.getChipId() & 0xF));
return timeOutReached(wifi_connect_timer + DEFAULT_WIFI_CONNECTION_TIMEOUT + randomOffset_in_sec);
}
//********************************************************************************
// Simply start the WiFi connection sequence
//********************************************************************************
bool tryConnectWiFi() {
if (wifiSetup && !wifiSetupConnect)
return false;
if (WiFi.status() == WL_CONNECTED)
return(true); //already connected, need to disconnect first
if (!wifiConnectTimeoutReached())
return true; // timeout not reached yet, thus no need to retry again.
if (!anyValidWifiSettings())
return false;
if (wifi_connect_attempt != 0 && ((wifi_connect_attempt % 3) == 0)) {
// Change to other wifi settings.
if (selectNextWiFiSettings())
WiFi.disconnect();
}
if (wifi_connect_attempt > 6) {
//everything failed, activate AP mode (will deactivate automatically after a while if its connected again)
WifiAPMode(true);
}
String ssid;
ssid.reserve(32);
String passphrase;
passphrase.reserve(64);
ssid = getLastWiFiSettingsSSID();
passphrase = getLastWiFiSettingsPassphrase();
String log = F("WIFI : Connecting ");
log += ssid;
log += F(" attempt #");
log += wifi_connect_attempt;
addLog(LOG_LEVEL_INFO, log);
wifi_connect_timer = millis();
switch (wifi_connect_attempt) {
case 0:
if (lastBSSID[0] == 0)
WiFi.begin(ssid.c_str(), passphrase.c_str());
else
WiFi.begin(ssid.c_str(), passphrase.c_str(), 0, &lastBSSID[0]);
break;
default:
WiFi.begin(ssid.c_str(), passphrase.c_str());
}
++wifi_connect_attempt;
switch (WiFi.status()) {
case WL_NO_SSID_AVAIL: {
log = F("WIFI : No SSID found matching: ");
log += ssid;
addLog(LOG_LEVEL_INFO, log);
return false;
}
case WL_CONNECT_FAILED: {
log = F("WIFI : Connection failed to: ");
log += ssid;
addLog(LOG_LEVEL_INFO, log);
return false;
}
case WL_CONNECTED:
checkWifiJustConnected();
break;
default:
break;
}
return true; // Sent
}
//********************************************************************************
// Connect to Wifi specific SSID
//********************************************************************************
boolean WifiConnectAndWait(byte connectAttempts)
boolean WifiConnectSSID(char WifiSSID[], char WifiKey[], byte connectAttempts)
{
String log;
wifiConnected = false;
wifi_connect_attempt = 0;
for (byte tryConnect = 0; tryConnect < connectAttempts; tryConnect++)
//already connected, need to disconnect first
if (WiFi.status() == WL_CONNECTED)
return(true);
//no ssid specified
if ((WifiSSID[0] == 0) || (strcasecmp(WifiSSID, "ssid") == 0))
return(false);
for (byte tryConnect = 1; tryConnect <= connectAttempts; tryConnect++)
{
if (tryConnectWiFi()) {
do {
if (checkWifiJustConnected())
return true;
delay(50);
} while (!wifiConnectTimeoutReached());
}
// log = F("WIFI : Disconnecting!");
// addLog(LOG_LEVEL_INFO, log);
#if defined(ESP8266)
ETS_UART_INTR_DISABLE();
wifi_station_disconnect();
ETS_UART_INTR_ENABLE();
#endif
for (byte x = 0; x < 20; x++)
log = F("WIFI : Connecting ");
log += WifiSSID;
log += F(" attempt #");
log += tryConnect;
addLog(LOG_LEVEL_INFO, log);
if (tryConnect == 1)
WiFi.begin(WifiSSID, WifiKey);
else
WiFi.begin();
//wait until it connects
for (byte x = 0; x < 200; x++)
{
if (!WiFiConnected(50))
{
statusLED(false);
// No delay needed, since the WiFi check has a delay
}
else
break;
}
if (WiFi.status() == WL_CONNECTED)
{
if (Settings.UseNTP) {
initTime();
}
log = F("WIFI : Connected! IP: ");
log += formatIP(WiFi.localIP());
log += F(" (");
log += WifiGetHostname();
log += F(")");
addLog(LOG_LEVEL_INFO, log);
statusLED(true);
delay(50);
return(true);
}
else
{
// log = F("WIFI : Disconnecting!");
// addLog(LOG_LEVEL_INFO, log);
#if defined(ESP8266)
ETS_UART_INTR_DISABLE();
wifi_station_disconnect();
ETS_UART_INTR_ENABLE();
#endif
for (byte x = 0; x < 20; x++)
{
statusLED(true);
delay(50);
}
}
}
return false;
}
bool checkWifiJustConnected() {
if (wifiConnected) return true;
delay(1);
if (WiFi.status() != WL_CONNECTED) {
statusLED(false);
return false;
}
wifiConnected = true;
String log = F("WIFI : WiFi connect attempt took: ");
log += timePassedSince(wifi_connect_timer);
log += F(" ms");
addLog(LOG_LEVEL_INFO, log);
// fix octet?
if (Settings.IP_Octet != 0 && Settings.IP_Octet != 255)
{
IPAddress ip = WiFi.localIP();
IPAddress gw = WiFi.gatewayIP();
IPAddress subnet = WiFi.subnetMask();
ip[3] = Settings.IP_Octet;
log = F("IP : Fixed IP octet:");
log += ip;
addLog(LOG_LEVEL_INFO, log);
WiFi.config(ip, gw, subnet);
}
#ifdef FEATURE_MDNS
String log = F("WIFI : ");
if (MDNS.begin(WifiGetHostname().c_str(), WiFi.localIP())) {
log += F("mDNS started, with name: ");
log += WifiGetHostname();
log += F(".local");
}
else{
log += F("mDNS failed");
}
addLog(LOG_LEVEL_INFO, log);
#endif
// First try to get the time, since that may be used in logs
if (Settings.UseNTP) {
initTime();
}
uint8_t* curBSSID = WiFi.BSSID();
bool changed = false;
for (byte i=0; i < 6; ++i) {
if (lastBSSID[i] != *(curBSSID + i)) {
changed = true;
lastBSSID[i] = *(curBSSID + i);
}
}
if (Settings.UseRules)
{
if (changed) {
String event = F("WiFi#ChangedAccesspoint");
rulesProcessing(event);
}
String event = F("WiFi#Connected");
rulesProcessing(event);
}
log = F("WIFI : Connected! IP: ");
log += formatIP(WiFi.localIP());
log += F(" (");
log += WifiGetHostname();
log += F(") AP: ");
log += WiFi.SSID();
log += F(" AP BSSID: ");
log += WiFi.BSSIDstr();
addLog(LOG_LEVEL_INFO, log);
statusLED(true);
return true;
}
//********************************************************************************
// Disconnect from Wifi AP
@@ -385,7 +238,6 @@ bool checkWifiJustConnected() {
void WifiDisconnect()
{
WiFi.disconnect();
wifiConnected = false;
}
@@ -427,20 +279,18 @@ void WifiScan()
//********************************************************************************
void WifiCheck()
{
if(wifiSetup)
return;
if (WiFi.status() != WL_CONNECTED)
{
NC_Count++;
//give it time to automaticly reconnect
//give it time to automatically reconnect
if (NC_Count > 2)
{
if (wifiConnected) {
wifi_connect_attempt = 0;
wifiConnected = false;
WiFiConnectRelaxed();
}
WifiConnect(2);
C_Count=0;
NC_Count = 0;
}
@@ -455,8 +305,30 @@ void WifiCheck()
WifiAPMode(false);
}
}
if (!wifiConnected) {
if (tryConnectWiFi())
checkWifiJustConnected();
}
//********************************************************************************
// Return subnet range of WiFi.
//********************************************************************************
bool getSubnetRange(IPAddress& low, IPAddress& high)
{
if (WifiIsAP()) {
// WiFi is active as accesspoint, do not check.
return false;
}
if (WiFi.status() != WL_CONNECTED) {
return false;
}
const IPAddress ip = WiFi.localIP();
const IPAddress subnet = WiFi.subnetMask();
low = ip;
high = ip;
// Compute subnet range.
for (byte i=0; i < 4; ++i) {
if (subnet[i] != 255) {
low[i] = low[i] & subnet[i];
high[i] = high[i] | ~subnet[i];
}
}
return true;
}
+1
View File
@@ -6,6 +6,7 @@
#define CPLUGIN_ID_001 1
#define CPLUGIN_NAME_001 "Domoticz HTTP"
boolean CPlugin_001(byte function, struct EventStruct *event, String& string)
{
boolean success = false;
+1 -1
View File
@@ -110,7 +110,7 @@ boolean CPlugin_004(byte function, struct EventStruct *event, String& string)
addLog(LOG_LEVEL_DEBUG_MORE, log);
if (line.substring(0, 15) == F("HTTP/1.1 200 OK"))
{
strcpy_P(log, PSTR("HTTP : Succes!"));
strcpy_P(log, PSTR("HTTP : Success!"));
addLog(LOG_LEVEL_DEBUG, log);
success = true;
}
+1
View File
@@ -108,6 +108,7 @@ boolean CPlugin_005(byte function, struct EventStruct *event, String& string)
value = (unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16);
else
value = formatUserVar(event, x);
MQTTpublish(event->ControllerIndex, tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);
String log = F("MQTT : ");
log += tmppubname;
+1 -1
View File
@@ -105,7 +105,7 @@ boolean CPlugin_007(byte function, struct EventStruct *event, String& string)
addLog(LOG_LEVEL_DEBUG_MORE, log);
if (line.substring(0, 15) == F("HTTP/1.1 200 OK"))
{
strcpy_P(log, PSTR("HTTP : Succes!"));
strcpy_P(log, PSTR("HTTP : Success!"));
addLog(LOG_LEVEL_DEBUG, log);
success = true;
}
+2 -2
View File
@@ -21,7 +21,7 @@ boolean CPlugin_008(byte function, struct EventStruct *event, String& string)
Protocol[protocolCount].usesAccount = true;
Protocol[protocolCount].usesPassword = true;
Protocol[protocolCount].defaultPort = 80;
Protocol[protocolCount].usesID = false;
Protocol[protocolCount].usesID = true;
break;
}
@@ -135,7 +135,7 @@ boolean HTTPSend(struct EventStruct *event, byte varIndex, float value, unsigned
addLog(LOG_LEVEL_DEBUG_MORE, line);
if (line.startsWith(F("HTTP/1.1 200 OK")))
{
// strcpy_P(log, PSTR("HTTP : Succes!"));
// strcpy_P(log, PSTR("HTTP : Success!"));
// addLog(LOG_LEVEL_DEBUG, log);
addLog(LOG_LEVEL_DEBUG, F("HTTP : Success!"));
// success = true;
+1 -1
View File
@@ -20,7 +20,7 @@
- moved on/off translation for SENSOR_TYPE_SWITCH/DIMMER to FHEM module
- v1.03
- changed http request from GET to POST (RFC conform)
- removed obsolet http get url code
- removed obsolete http get url code
- v1.04
- added build options and node_type_id to JSON/device
/******************************************************************************/
+1 -1
View File
@@ -89,7 +89,7 @@ void C010_Send(struct EventStruct *event, byte varIndex, float value, unsigned l
if (WiFi.status() == WL_CONNECTED) {
ControllerSettings.beginPacket(portUDP);
portUDP.write(msg.c_str());
portUDP.write((uint8_t*)msg.c_str(),msg.length());
portUDP.endPacket();
}
-265
View File
@@ -1,265 +0,0 @@
//#######################################################################################################
//########################### Controller Plugin 013: ESPEasy P2P network ################################
//#######################################################################################################
#define CPLUGIN_013
#define CPLUGIN_ID_013 13
#define CPLUGIN_NAME_013 "ESPEasy P2P Networking"
WiFiUDP C013_portUDP;
struct infoStruct
{
byte header = 255;
byte ID = 3;
byte sourcelUnit;
byte destUnit;
byte sourceTaskIndex;
byte destTaskIndex;
byte deviceNumber;
char taskName[26];
char ValueNames[VARS_PER_TASK][26];
};
struct dataStruct
{
byte header = 255;
byte ID = 5;
byte sourcelUnit;
byte destUnit;
byte sourceTaskIndex;
byte destTaskIndex;
float Values[VARS_PER_TASK];
};
boolean CPlugin_013(byte function, struct EventStruct *event, String& string)
{
boolean success = false;
switch (function)
{
case CPLUGIN_PROTOCOL_ADD:
{
Protocol[++protocolCount].Number = CPLUGIN_ID_013;
Protocol[protocolCount].usesMQTT = false;
Protocol[protocolCount].usesTemplate = false;
Protocol[protocolCount].usesAccount = false;
Protocol[protocolCount].usesPassword = false;
Protocol[protocolCount].defaultPort = 65501;
Protocol[protocolCount].usesID = false;
Protocol[protocolCount].Custom = true;
break;
}
case CPLUGIN_GET_DEVICENAME:
{
string = F(CPLUGIN_NAME_013);
break;
}
case CPLUGIN_PROTOCOL_TEMPLATE:
{
event->String1 = "";
event->String2 = "";
break;
}
case CPLUGIN_INIT:
{
//C013_portUDP.begin(Settings.UDPPort);
break;
}
case CPLUGIN_TASK_CHANGE_NOTIFICATION:
{
C013_SendUDPTaskInfo(0, event->TaskIndex, event->TaskIndex);
break;
}
case CPLUGIN_PROTOCOL_SEND:
{
C013_Send(event, 0, UserVar[event->BaseVarIndex], 0);
break;
}
case CPLUGIN_UDP_IN:
{
C013_Receive(event);
break;
}
}
return success;
}
//********************************************************************************
// Generic UDP message
//********************************************************************************
void C013_Send(struct EventStruct *event, byte varIndex, float value, unsigned long longValue)
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
statusLED(true);
C013_SendUDPTaskData(0, event->TaskIndex, event->TaskIndex);
}
void C013_SendUDPTaskInfo(byte destUnit, byte sourceTaskIndex, byte destTaskIndex)
{
if (!WiFiConnected(100)) {
return;
}
struct infoStruct infoReply;
infoReply.sourcelUnit = Settings.Unit;
infoReply.sourceTaskIndex = sourceTaskIndex;
infoReply.destTaskIndex = destTaskIndex;
LoadTaskSettings(infoReply.sourceTaskIndex);
infoReply.deviceNumber = Settings.TaskDeviceNumber[infoReply.sourceTaskIndex];
strcpy(infoReply.taskName, ExtraTaskSettings.TaskDeviceName);
for (byte x = 0; x < VARS_PER_TASK; x++)
strcpy(infoReply.ValueNames[x], ExtraTaskSettings.TaskDeviceValueNames[x]);
byte firstUnit = 1;
byte lastUnit = UNIT_MAX - 1;
if (destUnit != 0)
{
firstUnit = destUnit;
lastUnit = destUnit;
}
for (byte x = firstUnit; x <= lastUnit; x++)
{
if (x != Settings.Unit){
infoReply.destUnit = x;
C013_sendUDP(x, (byte*)&infoReply, sizeof(infoStruct));
delay(10);
}
}
delay(50);
}
void C013_SendUDPTaskData(byte destUnit, byte sourceTaskIndex, byte destTaskIndex)
{
if (!WiFiConnected(100)) {
return;
}
struct dataStruct dataReply;
dataReply.sourcelUnit = Settings.Unit;
dataReply.sourceTaskIndex = sourceTaskIndex;
dataReply.destTaskIndex = destTaskIndex;
for (byte x = 0; x < VARS_PER_TASK; x++)
dataReply.Values[x] = UserVar[dataReply.sourceTaskIndex * VARS_PER_TASK + x];
byte firstUnit = 1;
byte lastUnit = UNIT_MAX - 1;
if (destUnit != 0)
{
firstUnit = destUnit;
lastUnit = destUnit;
}
for (byte x = firstUnit; x <= lastUnit; x++)
{
if (x != Settings.Unit){
dataReply.destUnit = x;
C013_sendUDP(x, (byte*) &dataReply, sizeof(dataStruct));
delay(10);
}
}
delay(50);
}
/*********************************************************************************************\
Send UDP message (unit 255=broadcast)
\*********************************************************************************************/
void C013_sendUDP(byte unit, byte* data, byte size)
{
if (!WiFiConnected(100)) {
return;
}
if (unit != 255)
if (Nodes[unit].ip[0] == 0)
return;
String log = "C013 : Send UDP message to ";
log += unit;
addLog(LOG_LEVEL_DEBUG_MORE, log);
statusLED(true);
IPAddress remoteNodeIP;
if (unit == 255)
remoteNodeIP = {255, 255, 255, 255};
else
remoteNodeIP = Nodes[unit].ip;
C013_portUDP.beginPacket(remoteNodeIP, Settings.UDPPort);
C013_portUDP.write(data, size);
C013_portUDP.endPacket();
}
void C013_Receive(struct EventStruct *event) {
if (event->Data[1] > 1 && event->Data[1] < 6)
{
String log = (F("C013 : msg "));
for (byte x = 1; x < 6; x++)
{
log += " ";
log += (int)event->Data[x];
}
addLog(LOG_LEVEL_DEBUG_MORE, log);
}
switch (event->Data[1]) {
case 2: // sensor info pull request
{
//SendUDPTaskInfo(packetBuffer[2], packetBuffer[5], packetBuffer[4]);
break;
}
case 3: // sensor info
{
struct infoStruct infoReply;
memcpy((byte*)&infoReply, (byte*)event->Data, sizeof(infoStruct));
// to prevent flash wear out (bugs in communication?) we can only write to an empty task
// so it will write only once and has to be cleared manually through webgui
if (Settings.TaskDeviceNumber[infoReply.destTaskIndex] == 0)
{
Settings.TaskDeviceNumber[infoReply.destTaskIndex] = infoReply.deviceNumber;
Settings.TaskDeviceDataFeed[infoReply.destTaskIndex] = 1; // remote feed
for (byte x = 0; x < CONTROLLER_MAX; x++)
Settings.TaskDeviceSendData[x][infoReply.destTaskIndex] = false;
strcpy(ExtraTaskSettings.TaskDeviceName, infoReply.taskName);
for (byte x = 0; x < VARS_PER_TASK; x++)
strcpy( ExtraTaskSettings.TaskDeviceValueNames[x], infoReply.ValueNames[x]);
SaveTaskSettings(infoReply.destTaskIndex);
SaveSettings();
}
break;
}
case 4: // sensor data pull request
{
//SendUDPTaskData(packetBuffer[2], packetBuffer[5], packetBuffer[4]);
break;
}
case 5: // sensor data
{
struct dataStruct dataReply;
memcpy((byte*)&dataReply, (byte*)event->Data, sizeof(dataStruct));
// only if this task has a remote feed, update values
if (Settings.TaskDeviceDataFeed[dataReply.destTaskIndex] != 0)
{
for (byte x = 0; x < VARS_PER_TASK; x++)
{
UserVar[dataReply.destTaskIndex * VARS_PER_TASK + x] = dataReply.Values[x];
}
if (Settings.UseRules)
createRuleEvents(dataReply.destTaskIndex);
}
break;
}
}
}
+1 -1
View File
@@ -45,7 +45,7 @@ boolean NPlugin_002(byte function, struct EventStruct *event, String& string)
{
NotificationSettingsStruct NotificationSettings;
LoadNotificationSettings(event->NotificationIndex, (byte*)&NotificationSettings, sizeof(NotificationSettings));
//this reserves IRAM and uninitalized RAM
//this reserves IRAM and uninitialized RAM
tone(NotificationSettings.Pin1, 500, 500);
success = true;
}
+122 -23
View File
@@ -6,9 +6,11 @@
#define PLUGIN_ID_001 1
#define PLUGIN_NAME_001 "Switch input - Switch"
#define PLUGIN_VALUENAME1_001 "Switch"
Servo servo1;
Servo servo2;
#if defined(ESP8266)
Servo servo1;
Servo servo2;
#endif
#define GPIO_MAX 17
// Make sure the initial default is a switch (value 0)
#define PLUGIN_001_TYPE_SWITCH 0
#define PLUGIN_001_TYPE_DIMMER 3 // Due to some changes in previous versions, do not use 2.
@@ -25,6 +27,8 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
boolean success = false;
static boolean switchstate[TASKS_MAX];
static boolean outputstate[TASKS_MAX];
static int8_t PinMonitor[GPIO_MAX];
static int8_t PinMonitorState[GPIO_MAX];
switch (function)
{
@@ -106,6 +110,11 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
case PLUGIN_INIT:
{
for (byte x=0; x < GPIO_MAX; x++){
PinMonitor[x] = 0;
PinMonitorState[x] = 0;
}
if (Settings.TaskDevicePin1PullUp[event->TaskIndex])
pinMode(Settings.TaskDevicePin1[event->TaskIndex], INPUT_PULLUP);
else
@@ -126,6 +135,38 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
break;
}
case PLUGIN_REQUEST:
{
String device = parseString(string, 1);
String command = parseString(string, 2);
String strPar1 = parseString(string, 3);
int par1 = strPar1.toInt();
if (device == F("gpio") && command == F("pinstate"))
{
string = digitalRead(par1);
success = true;
}
break;
}
case PLUGIN_UNCONDITIONAL_POLL:
{
// port monitoring, on request by rule command
for (byte x=0; x < GPIO_MAX; x++)
if (PinMonitor[x] != 0){
byte state = digitalRead(x);
if (PinMonitorState[x] != state){
String eventString = F("GPIO#");
eventString += x;
eventString += F("=");
eventString += state;
rulesProcessing(eventString);
PinMonitorState[x] = state;
}
}
break;
}
case PLUGIN_TEN_PER_SECOND:
{
const boolean state = Plugin_001_read_switch_state(event);
@@ -197,11 +238,16 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
if (command == F("gpio"))
{
success = true;
if (event->Par1 >= 0 && event->Par1 <= 16)
if (event->Par1 >= 0 && event->Par1 <= PIN_D_MAX)
{
pinMode(event->Par1, OUTPUT);
digitalWrite(event->Par1, event->Par2);
setPinState(PLUGIN_ID_001, event->Par1, PIN_MODE_OUTPUT, event->Par2);
if (event->Par2 == 2) {
pinMode(event->Par1, INPUT);
setPinState(PLUGIN_ID_001, event->Par1, PIN_MODE_INPUT, 0);
} else {
pinMode(event->Par1, OUTPUT);
digitalWrite(event->Par1, event->Par2);
setPinState(PLUGIN_ID_001, event->Par1, PIN_MODE_OUTPUT, event->Par2);
}
log = String(F("SW : GPIO ")) + String(event->Par1) + String(F(" Set to ")) + String(event->Par2);
addLog(LOG_LEVEL_INFO, log);
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_001, event->Par1, log, 0));
@@ -211,10 +257,11 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
if (command == F("pwm"))
{
success = true;
if (event->Par1 >= 0 && event->Par1 <= 16)
if (event->Par1 >= 0 && event->Par1 <= PIN_D_MAX)
{
pinMode(event->Par1, OUTPUT);
#if defined(ESP8266)
pinMode(event->Par1, OUTPUT);
#endif
if(event->Par3 != 0)
{
byte prev_mode;
@@ -231,12 +278,22 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
curr_value += step_value;
int16_t new_value;
new_value = (uint16_t)(curr_value >> 12);
analogWrite(event->Par1, new_value);
#if defined(ESP8266)
analogWrite(event->Par1, new_value);
#endif
#if defined(ESP32)
analogWriteESP32(event->Par1, new_value);
#endif
delay(1);
}
}
analogWrite(event->Par1, event->Par2);
#if defined(ESP8266)
analogWrite(event->Par1, event->Par2);
#endif
#if defined(ESP32)
analogWriteESP32(event->Par1, event->Par2);
#endif
setPinState(PLUGIN_ID_001, event->Par1, PIN_MODE_PWM, event->Par2);
log = String(F("SW : GPIO ")) + String(event->Par1) + String(F(" Set PWM to ")) + String(event->Par2);
addLog(LOG_LEVEL_INFO, log);
@@ -247,7 +304,7 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
if (command == F("pulse"))
{
success = true;
if (event->Par1 >= 0 && event->Par1 <= 16)
if (event->Par1 >= 0 && event->Par1 <= PIN_D_MAX)
{
pinMode(event->Par1, OUTPUT);
digitalWrite(event->Par1, event->Par2);
@@ -264,7 +321,7 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
{
boolean time_in_msec = command == F("longpulse_ms");
success = true;
if (event->Par1 >= 0 && event->Par1 <= 16)
if (event->Par1 >= 0 && event->Par1 <= PIN_D_MAX)
{
pinMode(event->Par1, OUTPUT);
digitalWrite(event->Par1, event->Par2);
@@ -287,12 +344,16 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
case 1:
//IRAM: doing servo stuff uses 740 bytes IRAM. (doesnt matter how many instances)
servo1.attach(event->Par2);
servo1.write(event->Par3);
#if defined(ESP8266)
servo1.attach(event->Par2);
servo1.write(event->Par3);
#endif
break;
case 2:
servo2.attach(event->Par2);
servo2.write(event->Par3);
#if defined(ESP8266)
servo2.attach(event->Par2);
servo2.write(event->Par3);
#endif
break;
}
setPinState(PLUGIN_ID_001, event->Par2, PIN_MODE_SERVO, event->Par3);
@@ -310,6 +371,15 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
}
}
if (command == F("monitor"))
{
if (parseString(string, 2) == F("gpio"))
{
PinMonitor[event->Par2] = 1;
success = true;
}
}
if (command == F("inputswitchstate"))
{
success = true;
@@ -317,6 +387,7 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
outputstate[event->Par1] = event->Par2;
}
// FIXME: Absolutely no error checking in play_rtttl, until then keep it only in testing
#ifdef PLUGIN_BUILD_TESTING
//play a tune via a RTTTL string, look at https://www.letscontrolit.com/forum/viewtopic.php?f=4&t=343&hilit=speaker&start=10 for more info.
if (command == F("rtttl"))
@@ -325,10 +396,11 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
if (event->Par1 >= 0 && event->Par1 <= 16)
{
pinMode(event->Par1, OUTPUT);
char sng[1024] ="";
string.replace("-","#");
string.toCharArray(sng, 1024);
play_rtttl(event->Par1, sng);
// char sng[1024] ="";
String tmpString=string;
tmpString.replace("-","#");
// tmpString.toCharArray(sng, 1024);
play_rtttl(event->Par1, tmpString.c_str());
setPinState(PLUGIN_ID_001, event->Par1, PIN_MODE_OUTPUT, event->Par2);
log = String(F("SW : ")) + string;
addLog(LOG_LEVEL_INFO, log);
@@ -340,7 +412,7 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
if (command == F("tone"))
{
success = true;
if (event->Par1 >= 0 && event->Par1 <= 16)
if (event->Par1 >= 0 && event->Par1 <= PIN_D_MAX)
{
pinMode(event->Par1, OUTPUT);
tone(event->Par1, event->Par2, event->Par3);
@@ -365,6 +437,33 @@ boolean Plugin_001(byte function, struct EventStruct *event, String& string)
return success;
}
#if defined(ESP32)
void analogWriteESP32(int pin, int value)
{
// find existing channel if this pin has been used before
int8_t ledChannel = -1;
for(byte x = 0; x < 16; x++)
if (ledChannelPin[x] == pin)
ledChannel = x;
if(ledChannel == -1) // no channel set for this pin
{
for(byte x = 0; x < 16; x++) // find free channel
if (ledChannelPin[x] == -1)
{
int freq = 5000;
ledChannelPin[x] = pin; // store pin nr
ledcSetup(x, freq, 10); // setup channel
ledcAttachPin(pin, x); // attach to this pin
ledChannel = x;
break;
}
}
ledcWrite(ledChannel, value);
}
#endif
// TD-er: Needed to fix a mistake in earlier fixes.
byte P001_getSwitchType(struct EventStruct *event) {
byte choice = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
+17 -2
View File
@@ -47,6 +47,11 @@ boolean Plugin_002(byte function, struct EventStruct *event, String& string)
case PLUGIN_WEBFORM_LOAD:
{
#if defined(ESP32)
string += F("<TR><TD>Analog Pin:<TD>");
addPinSelect(false, string, "taskdevicepin1", Settings.TaskDevicePin1[event->TaskIndex]);
#endif
addFormCheckBox(string, F("Oversampling"), F("plugin_002_oversampling"), Settings.TaskDevicePluginConfig[event->TaskIndex][0]);
addFormSubHeader(string, F("Two Point Calibration"));
@@ -85,7 +90,12 @@ boolean Plugin_002(byte function, struct EventStruct *event, String& string)
{
if (Settings.TaskDevicePluginConfig[event->TaskIndex][0]) //Oversampling?
{
Plugin_002_OversamplingValue += analogRead(A0);
#if defined(ESP8266)
Plugin_002_OversamplingValue += analogRead(A0);
#endif
#if defined(ESP32)
Plugin_002_OversamplingValue += analogRead(Settings.TaskDevicePin1[event->TaskIndex]);
#endif
Plugin_002_OversamplingCount ++;
}
success = true;
@@ -106,7 +116,12 @@ boolean Plugin_002(byte function, struct EventStruct *event, String& string)
}
else
{
int16_t value = analogRead(A0);
#if defined(ESP8266)
int16_t value = analogRead(A0);
#endif
#if defined(ESP32)
int16_t value = analogRead(Settings.TaskDevicePin1[event->TaskIndex]);
#endif
UserVar[event->BaseVarIndex] = (float)value;
log += value;
+151 -109
View File
@@ -2,12 +2,19 @@
// #################################### Plugin 004: TempSensor Dallas DS18B20 ###########################
// #######################################################################################################
// Maxim Integrated (ex Dallas) DS18B20 datasheet : https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf
#if defined(ESP32)
#define ESP32noInterrupts() {portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;portENTER_CRITICAL(&mux)
#define ESP32interrupts() portEXIT_CRITICAL(&mux);}
#endif
#define PLUGIN_004
#define PLUGIN_ID_004 4
#define PLUGIN_NAME_004 "Environment - DS18b20"
#define PLUGIN_VALUENAME1_004 "Temperature"
uint8_t Plugin_004_DallasPin;
int8_t Plugin_004_DallasPin;
boolean Plugin_004(byte function, struct EventStruct * event, String& string)
{
@@ -47,47 +54,46 @@ boolean Plugin_004(byte function, struct EventStruct * event, String& string)
{
uint8_t savedAddress[8];
byte resolutionChoice = 0;
// Scan the onewire bus and fill dropdown list with devicecount on this GPIO.
Plugin_004_DallasPin = Settings.TaskDevicePin1[event->TaskIndex];
// get currently saved address
for (byte i = 0; i < 8; i++) {
savedAddress[i] = ExtraTaskSettings.TaskDevicePluginConfigLong[i];
if (Plugin_004_DallasPin != -1){
// get currently saved address
for (byte i = 0; i < 8; i++)
savedAddress[i] = ExtraTaskSettings.TaskDevicePluginConfigLong[i];
// find all suitable devices
addRowLabel(string, F("Device Address"));
addSelector_Head(string, F("plugin_004_dev"), false);
addSelector_Item(string, "", -1, false, false, F(""));
uint8_t tmpAddress[8];
byte count = 0;
Plugin_004_DS_reset();
Plugin_004_DS_reset_search();
while (Plugin_004_DS_search(tmpAddress))
{
String option = "";
for (byte j = 0; j < 8; j++)
{
option += String(tmpAddress[j], HEX);
if (j < 7) option += F("-");
}
bool selected = (memcmp(tmpAddress, savedAddress, 8) == 0) ? true : false;
addSelector_Item(string, option, count, selected, false, F(""));
count ++;
}
addSelector_Foot(string);
// Device Resolution select
if (ExtraTaskSettings.TaskDevicePluginConfigLong[0] != 0)
resolutionChoice = Plugin_004_DS_getResolution(savedAddress);
else
resolutionChoice = 9;
String resultsOptions[4] = { "9", "10", "11", "12" };
int resultsOptionValues[4] = { 9, 10, 11, 12 };
addFormSelector(string, F("Device Resolution"), F("plugin_004_res"), 4, resultsOptions, resultsOptionValues, resolutionChoice);
string += F(" Bit");
}
// find all suitable devices
addRowLabel(string, F("Device Address"));
addSelector_Head(string, F("plugin_004_dev"), false);
addSelector_Item(string, "", -1, false, false, F(""));
uint8_t tmpAddress[8];
byte count = 0;
Plugin_004_DS_reset();
Plugin_004_DS_reset_search();
while (Plugin_004_DS_search(tmpAddress))
{
String option = "";
for (byte j = 0; j < 8; j++)
{
option += String(tmpAddress[j], HEX);
if (j < 7) option += F("-");
}
bool selected = (memcmp(tmpAddress, savedAddress, 8) == 0) ? true : false;
addSelector_Item(string, option, count, selected, false, F(""));
count ++;
}
addSelector_Foot(string);
// Device Resolution select
if (ExtraTaskSettings.TaskDevicePluginConfigLong[0] != 0)
resolutionChoice = Plugin_004_DS_getResolution(savedAddress);
else
resolutionChoice = 9;
String resultsOptions[4] = { "9", "10", "11", "12" };
int resultsOptionValues[4] = { 9, 10, 11, 12 };
addFormSelector(string, F("Device Resolution"), F("plugin_004_res"), 4, resultsOptions, resultsOptionValues, resolutionChoice);
string += F(" Bit");
success = true;
break;
}
@@ -99,12 +105,14 @@ 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 =
Plugin_004_DS_scan(getFormItemInt(F("plugin_004_dev")), addr);
for (byte x = 0; x < 8; x++)
ExtraTaskSettings.TaskDevicePluginConfigLong[x] = addr[x];
Plugin_004_DS_setResolution(addr, getFormItemInt(F("plugin_004_res")));
if (Plugin_004_DallasPin != -1){
Plugin_004_DS_scan(getFormItemInt(F("plugin_004_dev")), addr);
for (byte x = 0; x < 8; x++)
ExtraTaskSettings.TaskDevicePluginConfigLong[x] = addr[x];
Plugin_004_DS_setResolution(addr, getFormItemInt(F("plugin_004_res")));
Plugin_004_DS_startConvertion(addr);
}
success = true;
break;
}
@@ -115,7 +123,19 @@ 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];
if (Plugin_004_DallasPin != -1){
uint8_t addr[8];
Plugin_004_get_addr(addr, event->TaskIndex);
Plugin_004_DS_startConvertion(addr);
delay(800); //give it time to do intial conversion
}
success = true;
break;
@@ -125,14 +145,12 @@ boolean Plugin_004(byte function, struct EventStruct * event, String& string)
{
if (ExtraTaskSettings.TaskDevicePluginConfigLong[0] != 0){
uint8_t addr[8];
// Load ROM address from tasksettings
LoadTaskSettings(event->TaskIndex);
for (byte x = 0; x < 8; x++)
addr[x] = ExtraTaskSettings.TaskDevicePluginConfigLong[x];
Plugin_004_get_addr(addr, event->TaskIndex);
Plugin_004_DallasPin = Settings.TaskDevicePin1[event->TaskIndex];
float value = 0;
String log = F("DS : Temperature: ");
if (Plugin_004_DS_readTemp(addr, &value))
{
UserVar[event->BaseVarIndex] = value;
@@ -144,6 +162,7 @@ boolean Plugin_004(byte function, struct EventStruct * event, String& string)
UserVar[event->BaseVarIndex] = NAN;
log += F("Error!");
}
Plugin_004_DS_startConvertion(addr);
log += (" (");
for (byte x = 0; x < 8; x++)
@@ -162,28 +181,53 @@ boolean Plugin_004(byte function, struct EventStruct * event, String& string)
return success;
}
void Plugin_004_get_addr(uint8_t addr[], byte TaskIndex)
{
// Load ROM address from tasksettings
LoadTaskSettings(TaskIndex);
for (byte x = 0; x < 8; x++)
addr[x] = ExtraTaskSettings.TaskDevicePluginConfigLong[x];
}
/*********************************************************************************************\
Dallas Scan bus
\*********************************************************************************************/
byte Plugin_004_DS_scan(byte getDeviceROM, uint8_t* ROM)
{
byte tmpaddr[8];
byte devCount = 0;
Plugin_004_DS_reset();
byte tmpaddr[8];
byte devCount = 0;
Plugin_004_DS_reset();
Plugin_004_DS_reset_search();
while (Plugin_004_DS_search(tmpaddr))
{
if (getDeviceROM == devCount)
for (byte i = 0; i < 8; i++)
ROM[i] = tmpaddr[i];
devCount++;
}
return devCount;
Plugin_004_DS_reset_search();
while (Plugin_004_DS_search(tmpaddr))
{
if (getDeviceROM == devCount)
for (byte i = 0; i < 8; i++)
ROM[i] = tmpaddr[i];
devCount++;
}
return devCount;
}
/*********************************************************************************************\
* Dallas Read temperature
* Dallas Start Temperature Conversion, expected duration:
* 9 bits resolution -> 93.75 ms
* 10 bits resolution -> 187.5 ms
* 11 bits resolution -> 375 ms
* 12 bits resolution -> 750 ms
\*********************************************************************************************/
void Plugin_004_DS_startConvertion(uint8_t ROM[8])
{
Plugin_004_DS_reset();
Plugin_004_DS_write(0x55); // Choose ROM
for (byte i = 0; i < 8; i++)
Plugin_004_DS_write(ROM[i]);
Plugin_004_DS_write(0x44); // Take temperature mesurement
}
/*********************************************************************************************\
* Dallas Read temperature from scratchpad
\*********************************************************************************************/
boolean Plugin_004_DS_readTemp(uint8_t ROM[8], float * value)
{
@@ -194,20 +238,13 @@ boolean Plugin_004_DS_readTemp(uint8_t ROM[8], float * value)
Plugin_004_DS_write(0x55); // Choose ROM
for (byte i = 0; i < 8; i++)
Plugin_004_DS_write(ROM[i]);
Plugin_004_DS_write(0x44);
delay(800);
Plugin_004_DS_reset();
Plugin_004_DS_write(0x55); // Choose ROM
for (byte i = 0; i < 8; i++)
Plugin_004_DS_write(ROM[i]);
Plugin_004_DS_write(0xBE); // Read scratchpad
for (byte i = 0; i < 9; i++) // copy 8 bytes
for (byte i = 0; i < 9; i++) // read 9 bytes
ScratchPad[i] = Plugin_004_DS_read();
if (Plugin_004_DS_crc8(ScratchPad, 8) != ScratchPad[8])
if (!Plugin_004_DS_crc8(ScratchPad))
{
*value = 0;
return false;
@@ -222,15 +259,11 @@ boolean Plugin_004_DS_readTemp(uint8_t ROM[8], float * value)
{
DSTemp = (ScratchPad[1] << 11) | ScratchPad[0] << 3;
DSTemp = ((DSTemp & 0xfff0) << 3) - 16 +
(
((ScratchPad[7] - ScratchPad[6]) << 7) /
ScratchPad[7]
);
(((ScratchPad[7] - ScratchPad[6]) << 7) / ScratchPad[7]);
*value = float(DSTemp) * 0.0078125;
}
return true;
} // Plugin_004_DS_readTemp
}
/*********************************************************************************************\
* Dallas Get Resolution
@@ -245,19 +278,15 @@ int Plugin_004_DS_getResolution(uint8_t ROM[8])
Plugin_004_DS_reset();
Plugin_004_DS_write(0x55); // Choose ROM
for (byte i = 0; i < 8; i++)
{
Plugin_004_DS_write(ROM[i]);
}
Plugin_004_DS_write(0xBE); // Read scratchpad
for (byte i = 0; i < 9; i++) // copy 8 bytes
for (byte i = 0; i < 9; i++) // read 9 bytes
ScratchPad[i] = Plugin_004_DS_read();
if (Plugin_004_DS_crc8(ScratchPad, 8) != ScratchPad[8])
{
if (!Plugin_004_DS_crc8(ScratchPad))
return 0;
}
else
{
switch (ScratchPad[4])
@@ -272,6 +301,7 @@ int Plugin_004_DS_getResolution(uint8_t ROM[8])
return 10;
case 0x1F: // 9 bit
default:
return 9;
}
}
@@ -291,44 +321,38 @@ boolean Plugin_004_DS_setResolution(uint8_t ROM[8], byte res)
Plugin_004_DS_reset();
Plugin_004_DS_write(0x55); // Choose ROM
for (byte i = 0; i < 8; i++)
{
Plugin_004_DS_write(ROM[i]);
}
Plugin_004_DS_write(0xBE); // Read scratchpad
for (byte i = 0; i < 9; i++) // copy 8 bytes
for (byte i = 0; i < 9; i++) // read 9 bytes
ScratchPad[i] = Plugin_004_DS_read();
if (Plugin_004_DS_crc8(ScratchPad, 8) != ScratchPad[8])
{
return 0;
}
if (!Plugin_004_DS_crc8(ScratchPad))
return false;
else
{
switch (res)
{
case 12:
ScratchPad[4] = 0x7F; // 12 bit
ScratchPad[4] = 0x7F; // 12 bits
break;
case 11:
ScratchPad[4] = 0x5F; // 11 bit
ScratchPad[4] = 0x5F; // 11 bits
break;
case 10:
ScratchPad[4] = 0x3F; // 10 bit
ScratchPad[4] = 0x3F; // 10 bits
break;
case 9:
default:
ScratchPad[4] = 0x1F; // 9 bit
ScratchPad[4] = 0x1F; // 9 bits
break;
}
Plugin_004_DS_reset();
Plugin_004_DS_write(0x55); // Choose ROM
for (byte i = 0; i < 8; i++)
{
Plugin_004_DS_write(ROM[i]);
}
Plugin_004_DS_write(0x4E); // Write to EEPROM
Plugin_004_DS_write(ScratchPad[2]); // high alarm temp
@@ -337,9 +361,7 @@ boolean Plugin_004_DS_setResolution(uint8_t ROM[8], byte res)
Plugin_004_DS_write(0x55); // Choose ROM
for (byte i = 0; i < 8; i++)
{
Plugin_004_DS_write(ROM[i]);
}
// save the newly written values to eeprom
Plugin_004_DS_write(0x48);
@@ -357,7 +379,9 @@ uint8_t Plugin_004_DS_reset()
{
uint8_t r;
uint8_t retries = 125;
// noInterrupts();
#if defined(ESP32)
ESP32noInterrupts();
#endif
pinMode(Plugin_004_DallasPin, INPUT);
do // wait until the wire is high... just in case
{
@@ -373,7 +397,9 @@ uint8_t Plugin_004_DS_reset()
delayMicroseconds(40);
r = !digitalRead(Plugin_004_DallasPin);
delayMicroseconds(420);
// interrupts();
#if defined(ESP32)
ESP32interrupts();
#endif
return r;
}
@@ -555,14 +581,18 @@ uint8_t Plugin_004_DS_read_bit(void)
{
uint8_t r;
// noInterrupts();
#if defined(ESP32)
ESP32noInterrupts();
#endif
pinMode(Plugin_004_DallasPin, OUTPUT);
digitalWrite(Plugin_004_DallasPin, LOW);
delayMicroseconds(3);
pinMode(Plugin_004_DallasPin, INPUT); // let pin float, pull up will raise
delayMicroseconds(10);
r = digitalRead(Plugin_004_DallasPin);
// interrupts();
#if defined(ESP32)
ESP32interrupts();
#endif
delayMicroseconds(53);
return r;
}
@@ -574,33 +604,45 @@ void Plugin_004_DS_write_bit(uint8_t v)
{
if (v & 1)
{
// noInterrupts();
#if defined(ESP32)
ESP32noInterrupts();
#endif
digitalWrite(Plugin_004_DallasPin, LOW);
pinMode(Plugin_004_DallasPin, OUTPUT);
delayMicroseconds(10);
digitalWrite(Plugin_004_DallasPin, HIGH);
// interrupts();
#if defined(ESP32)
ESP32interrupts();
#endif
delayMicroseconds(55);
}
else
{
// noInterrupts();
#if defined(ESP32)
ESP32noInterrupts();
#endif
digitalWrite(Plugin_004_DallasPin, LOW);
pinMode(Plugin_004_DallasPin, OUTPUT);
delayMicroseconds(65);
digitalWrite(Plugin_004_DallasPin, HIGH);
// interrupts();
#if defined(ESP32)
ESP32interrupts();
#endif
delayMicroseconds(5);
}
}
uint8_t Plugin_004_DS_crc8(uint8_t * addr, uint8_t len)
/*********************************************************************************************\
* Dallas Calculate CRC8 and compare it of addr[0-7] and compares it to addr[8]
\*********************************************************************************************/
boolean Plugin_004_DS_crc8(uint8_t * addr)
{
uint8_t crc = 0;
uint8_t crc = 0;
uint8_t len = 8;
while (len--)
{
uint8_t inbyte = *addr++;
uint8_t inbyte = *addr++; // from 0 to 7
for (uint8_t i = 8; i; i--)
{
uint8_t mix = (crc ^ inbyte) & 0x01;
@@ -609,5 +651,5 @@ uint8_t Plugin_004_DS_crc8(uint8_t * addr, uint8_t len)
inbyte >>= 1;
}
}
return crc;
return crc == *addr; // addr 8
}
+1 -1
View File
@@ -70,7 +70,7 @@ boolean Plugin_010(byte function, struct EventStruct *event, String& string)
optionValuesMode[1] = RESOLUTION_NORMAL;
optionValuesMode[2] = RESOLUTION_HIGH;
optionValuesMode[3] = RESOLUTION_AUTO_HIGH;
addFormSelector(string, F("Measurment mode"), F("plugin_010_mode"), 4, optionsMode, optionValuesMode, choiceMode);
addFormSelector(string, F("Measurement mode"), F("plugin_010_mode"), 4, optionsMode, optionValuesMode, choiceMode);
addFormCheckBox(string, F("Send sensor to sleep"), F("plugin_010_sleep"), Settings.TaskDevicePluginConfig[event->TaskIndex][2]);
+17 -16
View File
@@ -226,22 +226,7 @@ boolean Plugin_012(byte function, struct EventStruct *event, String& string)
if (argIndex)
tmpString = tmpString.substring(0, argIndex);
if (lcd && tmpString.equalsIgnoreCase(F("LCDCMD")))
{
success = true;
argIndex = string.lastIndexOf(',');
tmpString = string.substring(argIndex + 1);
if (tmpString.equalsIgnoreCase(F("Off"))){
lcd->noBacklight();
}
else if (tmpString.equalsIgnoreCase(F("On"))){
lcd->backlight();
}
else if (tmpString.equalsIgnoreCase(F("Clear"))){
lcd->clear();
}
}
else if (lcd && tmpString.equalsIgnoreCase(F("LCD")))
if (lcd && tmpString.equalsIgnoreCase(F("LCD")))
{
success = true;
argIndex = string.lastIndexOf(',');
@@ -296,6 +281,22 @@ boolean Plugin_012(byte function, struct EventStruct *event, String& string)
}
}
if (lcd && tmpString.equalsIgnoreCase(F("LCDCMD")))
{
success = true;
argIndex = string.lastIndexOf(',');
tmpString = string.substring(argIndex + 1);
if (tmpString.equalsIgnoreCase(F("Off"))){
lcd->noBacklight();
}
else if (tmpString.equalsIgnoreCase(F("On"))){
lcd->backlight();
}
else if (tmpString.equalsIgnoreCase(F("Clear"))){
lcd->clear();
}
}
break;
}
+34 -21
View File
@@ -112,9 +112,17 @@ boolean Plugin_019(byte function, struct EventStruct *event, String& string)
if (command == F("pcfgpio"))
{
success = true;
Plugin_019_Write(event->Par1, event->Par2);
setPinState(PLUGIN_ID_019, event->Par1, PIN_MODE_OUTPUT, event->Par2);
log = String(F("PCF : GPIO ")) + String(event->Par1) + String(F(" Set to ")) + String(event->Par2);
if (event->Par2 == 2) { //INPUT
// PCF8574 specific: only can read 0/low state, so we must send 1
setPinState(PLUGIN_ID_019, event->Par1, PIN_MODE_INPUT, 1);
Plugin_019_Write(event->Par1,1);
log = String(F("PCF : GPIO ")) + String(event->Par1) + String(F(" Set to 1"));
}
else { // OUTPUT
setPinState(PLUGIN_ID_019, event->Par1, PIN_MODE_OUTPUT, event->Par2);
Plugin_019_Write(event->Par1, event->Par2);
log = String(F("PCF : GPIO ")) + String(event->Par1) + String(F(" Set to ")) + String(event->Par2);
}
addLog(LOG_LEVEL_INFO, log);
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_019, event->Par1, log, 0));
}
@@ -200,28 +208,33 @@ int Plugin_019_Read(byte Par1)
//********************************************************************************
boolean Plugin_019_Write(byte Par1, byte Par2)
{
boolean success = false;
byte portvalue = 0;
byte unit = (Par1 - 1) / 8;
byte port = Par1 - (unit * 8);
uint8_t address = 0x20 + unit;
if (unit > 7) address += 0x10;
// get the current pin status
Wire.requestFrom(address, (uint8_t)0x1);
if (Wire.available())
{
portvalue = Wire.read();
if (Par2 == 1)
portvalue |= (1 << (port - 1));
else
portvalue &= ~(1 << (port - 1));
// write back new data
Wire.beginTransmission(address);
Wire.write(portvalue);
Wire.endTransmission();
success = true;
//generate bitmask
int i = 0;
byte portmask = 0;
byte mode = 0;
uint16_t value = 0;
unit *= 8; // calculate first pin
unit += 1;
for(i =0;i<8;i++){
mode =0;
if(!getPinState(PLUGIN_ID_019, unit, &mode, &value) || mode == PIN_MODE_INPUT || (mode == PIN_MODE_OUTPUT && value == 1))
portmask |= (1 << i);
unit++;
}
return(success);
if (Par2 == 1)
portmask |= (1 << (port - 1));
else
portmask &= ~(1 << (port - 1));
Wire.beginTransmission(address);
Wire.write(portmask);
Wire.endTransmission();
return true;
}
+12 -2
View File
@@ -96,12 +96,22 @@ boolean Plugin_020(byte function, struct EventStruct *event, String& string)
LoadTaskSettings(event->TaskIndex);
if ((ExtraTaskSettings.TaskDevicePluginConfigLong[0] != 0) && (ExtraTaskSettings.TaskDevicePluginConfigLong[1] != 0))
{
byte serialconfig = 0x10;
#if defined(ESP8266)
byte serialconfig = 0x10;
#endif
#if defined(ESP32)
uint32_t serialconfig = 0x8000010;
#endif
serialconfig += ExtraTaskSettings.TaskDevicePluginConfigLong[3];
serialconfig += (ExtraTaskSettings.TaskDevicePluginConfigLong[2] - 5) << 2;
if (ExtraTaskSettings.TaskDevicePluginConfigLong[4] == 2)
serialconfig += 0x20;
Serial.begin(ExtraTaskSettings.TaskDevicePluginConfigLong[1], (SerialConfig)serialconfig);
#if defined(ESP8266)
Serial.begin(ExtraTaskSettings.TaskDevicePluginConfigLong[1], (SerialConfig)serialconfig);
#endif
#if defined(ESP32)
Serial.begin(ExtraTaskSettings.TaskDevicePluginConfigLong[1], serialconfig);
#endif
ser2netServer = new WiFiServer(ExtraTaskSettings.TaskDevicePluginConfigLong[0]);
ser2netServer->begin();
+37 -2
View File
@@ -8,7 +8,7 @@
#define PLUGIN_VALUENAME1_022 "PWM"
#define PLUGIN_022_PCA9685_MODE1 0x00 // location for Mode1 register address
#define PCA9685_MODE2 0x01 // location for Mode2 reigster address
#define PCA9685_MODE2 0x01 // location for Mode2 register address
#define PCA9685_LED0 0x06 // location for start of LED0 registers
#define PCA9685_ADDRESS 0x40 // I2C address
@@ -63,6 +63,16 @@ boolean Plugin_022(byte function, struct EventStruct *event, String& string)
addLog(LOG_LEVEL_INFO, log);
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_022, event->Par1, log, 0));
}
if (command == F("pcafrq"))
{
if (!Plugin_022_init) Plugin_022_initialize();
success = true;
Plugin_022_Frequency(event->Par1);
setPinState(PLUGIN_ID_022, 99, PIN_MODE_UNDEFINED, event->Par1);
log = String(F("PCA : FREQ ")) + String(event->Par1);
addLog(LOG_LEVEL_INFO, log);
SendStatus(event->Source, getPinStateJSON(SEARCH_PIN_STATE, PLUGIN_ID_022, 99, log, 0));
}
if (command == F("status"))
{
@@ -90,6 +100,15 @@ void Plugin_022_writeRegister(int regAddress, byte data) {
Wire.endTransmission();
}
uint8_t Plugin_022_readRegister(int regAddress) {
uint8_t res = 0;
Wire.requestFrom(PCA9685_ADDRESS,1,1);
while (Wire.available()) {
res = Wire.read();
}
return res;
}
//********************************************************************************
// PCA9685 write
@@ -107,10 +126,26 @@ void Plugin_022_Write(byte Par1, int Par2)
Wire.write(highByte(LED_OFF));
Wire.endTransmission();
}
void Plugin_022_Frequency(uint16_t freq)
{
Plugin_022_writeRegister(PLUGIN_022_PCA9685_MODE1, (byte)0x0);
freq *= 0.9;
// prescale = 25000000 / 4096;
uint16_t prescale = 6103;
prescale /= freq;
prescale -= 1;
uint8_t oldmode = Plugin_022_readRegister(0);
uint8_t newmode = (oldmode&0x7f) | 0x10;
Plugin_022_writeRegister(PLUGIN_022_PCA9685_MODE1, (byte)newmode);
Plugin_022_writeRegister(0xfe, (byte)prescale); //prescale register
Plugin_022_writeRegister(PLUGIN_022_PCA9685_MODE1, (byte)oldmode);
delayMicroseconds(5000);
Plugin_022_writeRegister(PLUGIN_022_PCA9685_MODE1, (byte)oldmode | 0xa1);
}
void Plugin_022_initialize()
{
// default mode is open drain ouput, drive leds connected to VCC
// default mode is open drain output, drive leds connected to VCC
Plugin_022_writeRegister(PLUGIN_022_PCA9685_MODE1, (byte)0x01); // reset the device
delay(1);
Plugin_022_writeRegister(PLUGIN_022_PCA9685_MODE1, (byte)B10100000); // set up for auto increment
+279 -132
View File
@@ -15,11 +15,19 @@
byte Plugin_023_OLED_address = 0x3c;
byte Plugin_023_OLED_type = 0;
byte Plugin_023_OLED_font_width = 0;
enum
{
OLED_64x48 = 0x01,
OLED_rotated = 0x02
OLED_rotated = 0x02,
OLED_128x32 = 0x04
};
enum
{
Size_normal = 0x01,
Size_optimized = 0x02
};
boolean Plugin_023(byte function, struct EventStruct *event, String& string)
@@ -70,9 +78,14 @@ boolean Plugin_023(byte function, struct EventStruct *event, String& string)
addFormSelector(string, F("Rotation"), F("plugin_023_rotate"), 2, options2, optionValues2, choice2);
byte choice3 = Settings.TaskDevicePluginConfig[event->TaskIndex][3];
String options3[2] = { F("128x64"), F("64x48") };
int optionValues3[2] = { 1, 2 };
addFormSelector(string, F("Display Size"), F("plugin_023_size"), 2, options3, optionValues3, choice3);
String options3[3] = { F("128x64"), F("128x32"), F("64x48") };
int optionValues3[3] = { 1, 3, 2 };
addFormSelector(string, F("Display Size"), F("plugin_023_size"), 3, options3, optionValues3, choice3);
byte choice4 = Settings.TaskDevicePluginConfig[event->TaskIndex][4];
String options4[2] = { F("Normal"), F("Optimized") };
int optionValues4[2] = { 1, 2 };
addFormSelector(string, F("Font Width"), F("plugin_023_font_width"), 2, options4, optionValues4, choice4);
char deviceTemplate[8][64];
LoadCustomTaskSettings(event->TaskIndex, (byte*)&deviceTemplate, sizeof(deviceTemplate));
@@ -95,6 +108,7 @@ boolean Plugin_023(byte function, struct EventStruct *event, String& string)
Settings.TaskDevicePluginConfig[event->TaskIndex][1] = getFormItemInt(F("plugin_023_rotate"));
Settings.TaskDevicePluginConfig[event->TaskIndex][2] = getFormItemInt(F("plugin_23_timer"));
Settings.TaskDevicePluginConfig[event->TaskIndex][3] = getFormItemInt(F("plugin_023_size"));
Settings.TaskDevicePluginConfig[event->TaskIndex][4] = getFormItemInt(F("plugin_023_font_width"));
char deviceTemplate[8][64];
for (byte varNr = 0; varNr < 8; varNr++)
@@ -115,6 +129,16 @@ boolean Plugin_023(byte function, struct EventStruct *event, String& string)
{
Plugin_023_OLED_type = 0;
Plugin_023_OLED_address = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
if (Settings.TaskDevicePluginConfig[event->TaskIndex][3] == 3)
{
Plugin_023_OLED_type = OLED_128x32;
}
if (Settings.TaskDevicePluginConfig[event->TaskIndex][4] == 2)
{
Plugin_023_OLED_font_width = Size_optimized;
}
Plugin_023_StartUp_OLED();
Plugin_023_clear_display();
if (Settings.TaskDevicePluginConfig[event->TaskIndex][1] == 2)
@@ -184,6 +208,14 @@ boolean Plugin_023(byte function, struct EventStruct *event, String& string)
int argIndex = tmpString.indexOf(',');
if (argIndex)
tmpString = tmpString.substring(0, argIndex);
if (tmpString.equalsIgnoreCase(F("OLED")))
{
success = true;
argIndex = string.lastIndexOf(',');
tmpString = string.substring(argIndex + 1);
String newString = P023_parseTemplate(tmpString, 16);
Plugin_023_sendStrXY(newString.c_str(), event->Par1 - 1, event->Par2 - 1);
}
if (tmpString.equalsIgnoreCase(F("OLEDCMD")))
{
success = true;
@@ -196,20 +228,112 @@ boolean Plugin_023(byte function, struct EventStruct *event, String& string)
else if (tmpString.equalsIgnoreCase(F("Clear")))
Plugin_023_clear_display();
}
else if (tmpString.equalsIgnoreCase(F("OLED")))
{
success = true;
argIndex = string.lastIndexOf(',');
tmpString = string.substring(argIndex + 1);
String newString = P023_parseTemplate(tmpString, 16);
Plugin_023_sendStrXY(newString.c_str(), event->Par1 - 1, event->Par2 - 1);
}
break;
}
}
return success;
}
const char Plugin_023_myFont_Size[] PROGMEM = {
0x05, // SPACE
0x05, // !
0x07, // "
0x08, // #
0x08, // $
0x08, // %
0x08, // &
0x06, // '
0x06, // (
0x06, // )
0x08, // *
0x08, // +
0x05, // ,
0x08, // -
0x05, // .
0x08, // /
0x08, // 0
0x07, // 1
0x08, // 2
0x08, // 3
0x08, // 4
0x08, // 5
0x08, // 6
0x08, // 7
0x08, // 8
0x08, // 9
0x06, // :
0x06, // ;
0x07, // <
0x08, // =
0x07, // >
0x08, // ?
0x08, // @
0x08, // A
0x08, // B
0x08, // C
0x08, // D
0x08, // E
0x08, // F
0x08, // G
0x08, // H
0x06, // I
0x08, // J
0x08, // K
0x08, // L
0x08, // M
0x08, // N
0x08, // O
0x08, // P
0x08, // Q
0x08, // R
0x08, // S
0x08, // T
0x08, // U
0x08, // V
0x08, // W
0x08, // X
0x08, // Y
0x08, // Z
0x06, // [
0x08, // BACKSLASH
0x06, // ]
0x08, // ^
0x08, // _
0x06, // `
0x08, // a
0x08, // b
0x07, // c
0x08, // d
0x08, // e
0x07, // f
0x08, // g
0x08, // h
0x05, // i
0x06, // j
0x07, // k
0x06, // l
0x08, // m
0x07, // n
0x07, // o
0x07, // p
0x07, // q
0x07, // r
0x07, // s
0x06, // t
0x07, // u
0x08, // v
0x08, // w
0x08, // x
0x07, // y
0x08, // z
0x06, // {
0x05, // |
0x06, // }
0x08, // ~
0x08 // DEL
};
// Perform some specific changes for OLED display
String P023_parseTemplate(String &tmpString, byte lineSize) {
String result = parseTemplate(tmpString, lineSize);
@@ -222,102 +346,102 @@ String P023_parseTemplate(String &tmpString, byte lineSize) {
const char Plugin_023_myFont[][8] PROGMEM = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x5F, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00},
{0x00, 0x14, 0x7F, 0x14, 0x7F, 0x14, 0x00, 0x00},
{0x00, 0x24, 0x2A, 0x7F, 0x2A, 0x12, 0x00, 0x00},
{0x00, 0x23, 0x13, 0x08, 0x64, 0x62, 0x00, 0x00},
{0x00, 0x36, 0x49, 0x55, 0x22, 0x50, 0x00, 0x00},
{0x00, 0x00, 0x05, 0x03, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x1C, 0x22, 0x41, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x41, 0x22, 0x1C, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x08, 0x2A, 0x1C, 0x2A, 0x08, 0x00, 0x00},
{0x00, 0x08, 0x08, 0x3E, 0x08, 0x08, 0x00, 0x00},
{0x00, 0xA0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00},
{0x00, 0x60, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x20, 0x10, 0x08, 0x04, 0x02, 0x00, 0x00},
{0x00, 0x3E, 0x51, 0x49, 0x45, 0x3E, 0x00, 0x00},
{0x00, 0x00, 0x42, 0x7F, 0x40, 0x00, 0x00, 0x00},
{0x00, 0x62, 0x51, 0x49, 0x49, 0x46, 0x00, 0x00},
{0x00, 0x22, 0x41, 0x49, 0x49, 0x36, 0x00, 0x00},
{0x00, 0x18, 0x14, 0x12, 0x7F, 0x10, 0x00, 0x00},
{0x00, 0x27, 0x45, 0x45, 0x45, 0x39, 0x00, 0x00},
{0x00, 0x3C, 0x4A, 0x49, 0x49, 0x30, 0x00, 0x00},
{0x00, 0x01, 0x71, 0x09, 0x05, 0x03, 0x00, 0x00},
{0x00, 0x36, 0x49, 0x49, 0x49, 0x36, 0x00, 0x00},
{0x00, 0x06, 0x49, 0x49, 0x29, 0x1E, 0x00, 0x00},
{0x00, 0x00, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0xAC, 0x6C, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x08, 0x14, 0x22, 0x41, 0x00, 0x00, 0x00},
{0x00, 0x14, 0x14, 0x14, 0x14, 0x14, 0x00, 0x00},
{0x00, 0x41, 0x22, 0x14, 0x08, 0x00, 0x00, 0x00},
{0x00, 0x02, 0x01, 0x51, 0x09, 0x06, 0x00, 0x00},
{0x00, 0x32, 0x49, 0x79, 0x41, 0x3E, 0x00, 0x00},
{0x00, 0x7E, 0x09, 0x09, 0x09, 0x7E, 0x00, 0x00},
{0x00, 0x7F, 0x49, 0x49, 0x49, 0x36, 0x00, 0x00},
{0x00, 0x3E, 0x41, 0x41, 0x41, 0x22, 0x00, 0x00},
{0x00, 0x7F, 0x41, 0x41, 0x22, 0x1C, 0x00, 0x00},
{0x00, 0x7F, 0x49, 0x49, 0x49, 0x41, 0x00, 0x00},
{0x00, 0x7F, 0x09, 0x09, 0x09, 0x01, 0x00, 0x00},
{0x00, 0x3E, 0x41, 0x41, 0x51, 0x72, 0x00, 0x00},
{0x00, 0x7F, 0x08, 0x08, 0x08, 0x7F, 0x00, 0x00},
{0x00, 0x41, 0x7F, 0x41, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x20, 0x40, 0x41, 0x3F, 0x01, 0x00, 0x00},
{0x00, 0x7F, 0x08, 0x14, 0x22, 0x41, 0x00, 0x00},
{0x00, 0x7F, 0x40, 0x40, 0x40, 0x40, 0x00, 0x00},
{0x00, 0x7F, 0x02, 0x0C, 0x02, 0x7F, 0x00, 0x00},
{0x00, 0x7F, 0x04, 0x08, 0x10, 0x7F, 0x00, 0x00},
{0x00, 0x3E, 0x41, 0x41, 0x41, 0x3E, 0x00, 0x00},
{0x00, 0x7F, 0x09, 0x09, 0x09, 0x06, 0x00, 0x00},
{0x00, 0x3E, 0x41, 0x51, 0x21, 0x5E, 0x00, 0x00},
{0x00, 0x7F, 0x09, 0x19, 0x29, 0x46, 0x00, 0x00},
{0x00, 0x26, 0x49, 0x49, 0x49, 0x32, 0x00, 0x00},
{0x00, 0x01, 0x01, 0x7F, 0x01, 0x01, 0x00, 0x00},
{0x00, 0x3F, 0x40, 0x40, 0x40, 0x3F, 0x00, 0x00},
{0x00, 0x1F, 0x20, 0x40, 0x20, 0x1F, 0x00, 0x00},
{0x00, 0x3F, 0x40, 0x38, 0x40, 0x3F, 0x00, 0x00},
{0x00, 0x63, 0x14, 0x08, 0x14, 0x63, 0x00, 0x00},
{0x00, 0x03, 0x04, 0x78, 0x04, 0x03, 0x00, 0x00},
{0x00, 0x61, 0x51, 0x49, 0x45, 0x43, 0x00, 0x00},
{0x00, 0x7F, 0x41, 0x41, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x02, 0x04, 0x08, 0x10, 0x20, 0x00, 0x00},
{0x00, 0x41, 0x41, 0x7F, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x04, 0x02, 0x01, 0x02, 0x04, 0x00, 0x00},
{0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00},
{0x00, 0x01, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x20, 0x54, 0x54, 0x54, 0x78, 0x00, 0x00},
{0x00, 0x7F, 0x48, 0x44, 0x44, 0x38, 0x00, 0x00},
{0x00, 0x38, 0x44, 0x44, 0x28, 0x00, 0x00, 0x00},
{0x00, 0x38, 0x44, 0x44, 0x48, 0x7F, 0x00, 0x00},
{0x00, 0x38, 0x54, 0x54, 0x54, 0x18, 0x00, 0x00},
{0x00, 0x08, 0x7E, 0x09, 0x02, 0x00, 0x00, 0x00},
{0x00, 0x18, 0xA4, 0xA4, 0xA4, 0x7C, 0x00, 0x00},
{0x00, 0x7F, 0x08, 0x04, 0x04, 0x78, 0x00, 0x00},
{0x00, 0x00, 0x7D, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x80, 0x84, 0x7D, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x7F, 0x10, 0x28, 0x44, 0x00, 0x00, 0x00},
{0x00, 0x41, 0x7F, 0x40, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x7C, 0x04, 0x18, 0x04, 0x78, 0x00, 0x00},
{0x00, 0x7C, 0x08, 0x04, 0x7C, 0x00, 0x00, 0x00},
{0x00, 0x38, 0x44, 0x44, 0x38, 0x00, 0x00, 0x00},
{0x00, 0xFC, 0x24, 0x24, 0x18, 0x00, 0x00, 0x00},
{0x00, 0x18, 0x24, 0x24, 0xFC, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x7C, 0x08, 0x04, 0x00, 0x00, 0x00},
{0x00, 0x48, 0x54, 0x54, 0x24, 0x00, 0x00, 0x00},
{0x00, 0x04, 0x7F, 0x44, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x3C, 0x40, 0x40, 0x7C, 0x00, 0x00, 0x00},
{0x00, 0x1C, 0x20, 0x40, 0x20, 0x1C, 0x00, 0x00},
{0x00, 0x3C, 0x40, 0x30, 0x40, 0x3C, 0x00, 0x00},
{0x00, 0x44, 0x28, 0x10, 0x28, 0x44, 0x00, 0x00},
{0x00, 0x1C, 0xA0, 0xA0, 0x7C, 0x00, 0x00, 0x00},
{0x00, 0x44, 0x64, 0x54, 0x4C, 0x44, 0x00, 0x00},
{0x00, 0x08, 0x36, 0x41, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x41, 0x36, 0x08, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x02, 0x01, 0x01, 0x02, 0x01, 0x00, 0x00},
{0x00, 0x02, 0x05, 0x05, 0x02, 0x00, 0x00, 0x00}
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // SPACE
{0x00, 0x00, 0x5F, 0x00, 0x00, 0x00, 0x00, 0x00}, // !
{0x00, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00}, // "
{0x00, 0x14, 0x7F, 0x14, 0x7F, 0x14, 0x00, 0x00}, // #
{0x00, 0x24, 0x2A, 0x7F, 0x2A, 0x12, 0x00, 0x00}, // $
{0x00, 0x23, 0x13, 0x08, 0x64, 0x62, 0x00, 0x00}, // %
{0x00, 0x36, 0x49, 0x55, 0x22, 0x50, 0x00, 0x00}, // &
{0x00, 0x00, 0x05, 0x03, 0x00, 0x00, 0x00, 0x00}, // '
{0x00, 0x1C, 0x22, 0x41, 0x00, 0x00, 0x00, 0x00}, // (
{0x00, 0x41, 0x22, 0x1C, 0x00, 0x00, 0x00, 0x00}, // )
{0x00, 0x08, 0x2A, 0x1C, 0x2A, 0x08, 0x00, 0x00}, // *
{0x00, 0x08, 0x08, 0x3E, 0x08, 0x08, 0x00, 0x00}, // +
{0x00, 0xA0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00}, // ,
{0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00}, // -
{0x00, 0x60, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00}, // .
{0x00, 0x20, 0x10, 0x08, 0x04, 0x02, 0x00, 0x00}, // /
{0x00, 0x3E, 0x51, 0x49, 0x45, 0x3E, 0x00, 0x00}, // 0
{0x00, 0x00, 0x42, 0x7F, 0x40, 0x00, 0x00, 0x00}, // 1
{0x00, 0x62, 0x51, 0x49, 0x49, 0x46, 0x00, 0x00}, // 2
{0x00, 0x22, 0x41, 0x49, 0x49, 0x36, 0x00, 0x00}, // 3
{0x00, 0x18, 0x14, 0x12, 0x7F, 0x10, 0x00, 0x00}, // 4
{0x00, 0x27, 0x45, 0x45, 0x45, 0x39, 0x00, 0x00}, // 5
{0x00, 0x3C, 0x4A, 0x49, 0x49, 0x30, 0x00, 0x00}, // 6
{0x00, 0x01, 0x71, 0x09, 0x05, 0x03, 0x00, 0x00}, // 7
{0x00, 0x36, 0x49, 0x49, 0x49, 0x36, 0x00, 0x00}, // 8
{0x00, 0x06, 0x49, 0x49, 0x29, 0x1E, 0x00, 0x00}, // 9
{0x00, 0x00, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00}, // :
{0x00, 0x00, 0xAC, 0x6C, 0x00, 0x00, 0x00, 0x00}, // ;
{0x00, 0x08, 0x14, 0x22, 0x41, 0x00, 0x00, 0x00}, // <
{0x00, 0x14, 0x14, 0x14, 0x14, 0x14, 0x00, 0x00}, // =
{0x00, 0x41, 0x22, 0x14, 0x08, 0x00, 0x00, 0x00}, // >
{0x00, 0x02, 0x01, 0x51, 0x09, 0x06, 0x00, 0x00}, // ?
{0x00, 0x32, 0x49, 0x79, 0x41, 0x3E, 0x00, 0x00}, // @
{0x00, 0x7E, 0x09, 0x09, 0x09, 0x7E, 0x00, 0x00}, // A
{0x00, 0x7F, 0x49, 0x49, 0x49, 0x36, 0x00, 0x00}, // B
{0x00, 0x3E, 0x41, 0x41, 0x41, 0x22, 0x00, 0x00}, // C
{0x00, 0x7F, 0x41, 0x41, 0x22, 0x1C, 0x00, 0x00}, // D
{0x00, 0x7F, 0x49, 0x49, 0x49, 0x41, 0x00, 0x00}, // E
{0x00, 0x7F, 0x09, 0x09, 0x09, 0x01, 0x00, 0x00}, // F
{0x00, 0x3E, 0x41, 0x41, 0x51, 0x72, 0x00, 0x00}, // G
{0x00, 0x7F, 0x08, 0x08, 0x08, 0x7F, 0x00, 0x00}, // H
{0x00, 0x41, 0x7F, 0x41, 0x00, 0x00, 0x00, 0x00}, // I
{0x00, 0x20, 0x40, 0x41, 0x3F, 0x01, 0x00, 0x00}, // J
{0x00, 0x7F, 0x08, 0x14, 0x22, 0x41, 0x00, 0x00}, // K
{0x00, 0x7F, 0x40, 0x40, 0x40, 0x40, 0x00, 0x00}, // L
{0x00, 0x7F, 0x02, 0x0C, 0x02, 0x7F, 0x00, 0x00}, // M
{0x00, 0x7F, 0x04, 0x08, 0x10, 0x7F, 0x00, 0x00}, // N
{0x00, 0x3E, 0x41, 0x41, 0x41, 0x3E, 0x00, 0x00}, // O
{0x00, 0x7F, 0x09, 0x09, 0x09, 0x06, 0x00, 0x00}, // P
{0x00, 0x3E, 0x41, 0x51, 0x21, 0x5E, 0x00, 0x00}, // Q
{0x00, 0x7F, 0x09, 0x19, 0x29, 0x46, 0x00, 0x00}, // R
{0x00, 0x26, 0x49, 0x49, 0x49, 0x32, 0x00, 0x00}, // S
{0x00, 0x01, 0x01, 0x7F, 0x01, 0x01, 0x00, 0x00}, // T
{0x00, 0x3F, 0x40, 0x40, 0x40, 0x3F, 0x00, 0x00}, // U
{0x00, 0x1F, 0x20, 0x40, 0x20, 0x1F, 0x00, 0x00}, // V
{0x00, 0x3F, 0x40, 0x38, 0x40, 0x3F, 0x00, 0x00}, // W
{0x00, 0x63, 0x14, 0x08, 0x14, 0x63, 0x00, 0x00}, // X
{0x00, 0x03, 0x04, 0x78, 0x04, 0x03, 0x00, 0x00}, // Y
{0x00, 0x61, 0x51, 0x49, 0x45, 0x43, 0x00, 0x00}, // Z
{0x00, 0x7F, 0x41, 0x41, 0x00, 0x00, 0x00, 0x00}, // [
{0x00, 0x02, 0x04, 0x08, 0x10, 0x20, 0x00, 0x00}, // BACKSLASH
{0x00, 0x41, 0x41, 0x7F, 0x00, 0x00, 0x00, 0x00}, // ]
{0x00, 0x04, 0x02, 0x01, 0x02, 0x04, 0x00, 0x00}, // ^
{0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00}, // _
{0x00, 0x01, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00}, // `
{0x00, 0x20, 0x54, 0x54, 0x54, 0x78, 0x00, 0x00}, // a
{0x00, 0x7F, 0x48, 0x44, 0x44, 0x38, 0x00, 0x00}, // b
{0x00, 0x38, 0x44, 0x44, 0x28, 0x00, 0x00, 0x00}, // c
{0x00, 0x38, 0x44, 0x44, 0x48, 0x7F, 0x00, 0x00}, // d
{0x00, 0x38, 0x54, 0x54, 0x54, 0x18, 0x00, 0x00}, // e
{0x00, 0x08, 0x7E, 0x09, 0x02, 0x00, 0x00, 0x00}, // f
{0x00, 0x18, 0xA4, 0xA4, 0xA4, 0x7C, 0x00, 0x00}, // g
{0x00, 0x7F, 0x08, 0x04, 0x04, 0x78, 0x00, 0x00}, // h
{0x00, 0x00, 0x7D, 0x00, 0x00, 0x00, 0x00, 0x00}, // i
{0x00, 0x80, 0x84, 0x7D, 0x00, 0x00, 0x00, 0x00}, // j
{0x00, 0x7F, 0x10, 0x28, 0x44, 0x00, 0x00, 0x00}, // k
{0x00, 0x41, 0x7F, 0x40, 0x00, 0x00, 0x00, 0x00}, // l
{0x00, 0x7C, 0x04, 0x18, 0x04, 0x78, 0x00, 0x00}, // m
{0x00, 0x7C, 0x08, 0x04, 0x7C, 0x00, 0x00, 0x00}, // n
{0x00, 0x38, 0x44, 0x44, 0x38, 0x00, 0x00, 0x00}, // o
{0x00, 0xFC, 0x24, 0x24, 0x18, 0x00, 0x00, 0x00}, // p
{0x00, 0x18, 0x24, 0x24, 0xFC, 0x00, 0x00, 0x00}, // q
{0x00, 0x00, 0x7C, 0x08, 0x04, 0x00, 0x00, 0x00}, // r
{0x00, 0x48, 0x54, 0x54, 0x24, 0x00, 0x00, 0x00}, // s
{0x00, 0x04, 0x7F, 0x44, 0x00, 0x00, 0x00, 0x00}, // t
{0x00, 0x3C, 0x40, 0x40, 0x7C, 0x00, 0x00, 0x00}, // u
{0x00, 0x1C, 0x20, 0x40, 0x20, 0x1C, 0x00, 0x00}, // v
{0x00, 0x3C, 0x40, 0x30, 0x40, 0x3C, 0x00, 0x00}, // w
{0x00, 0x44, 0x28, 0x10, 0x28, 0x44, 0x00, 0x00}, // x
{0x00, 0x1C, 0xA0, 0xA0, 0x7C, 0x00, 0x00, 0x00}, // y
{0x00, 0x44, 0x64, 0x54, 0x4C, 0x44, 0x00, 0x00}, // z
{0x00, 0x08, 0x36, 0x41, 0x00, 0x00, 0x00, 0x00}, // {
{0x00, 0x00, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00}, // |
{0x00, 0x41, 0x36, 0x08, 0x00, 0x00, 0x00, 0x00}, // }
{0x00, 0x02, 0x01, 0x01, 0x02, 0x01, 0x00, 0x00}, // ~
{0x00, 0x02, 0x05, 0x05, 0x02, 0x00, 0x00, 0x00} // DEL
};
static void Plugin_023_reset_display(void)
@@ -444,9 +568,20 @@ static void Plugin_023_sendStrXY(const char *string, int X, int Y)
{
Plugin_023_setXY(X, Y);
unsigned char i = 0;
unsigned char font_width = 0;
while (*string)
{
for (i = 0; i < 8; i++)
switch (Plugin_023_OLED_font_width)
{
case Size_optimized:
font_width = pgm_read_byte(&(Plugin_023_myFont_Size[*string - 0x20]));
break;
default:
font_width = 8;
}
for (i = 0; i < font_width; i++)
{
Plugin_023_SendChar(pgm_read_byte(Plugin_023_myFont[*string - 0x20] + i));
}
@@ -457,35 +592,47 @@ static void Plugin_023_sendStrXY(const char *string, int X, int Y)
static void Plugin_023_init_OLED(void)
{
Plugin_023_sendcommand(0xae); //display off
Plugin_023_sendcommand(0xa6); //Set Normal Display (default)
Plugin_023_sendcommand(0xAE); //DISPLAYOFF
Plugin_023_sendcommand(0xD5); //SETDISPLAYCLOCKDIV
Plugin_023_sendcommand(0x80); // the suggested ratio 0x80
Plugin_023_sendcommand(0xA8); //SSD1306_SETMULTIPLEX
Plugin_023_sendcommand(0x3F);
Plugin_023_sendcommand(0xD3); //SETDISPLAYOFFSET
Plugin_023_sendcommand(0x0); //no offset
Plugin_023_sendcommand(0x40 | 0x0); //SETSTARTLINE
Plugin_023_sendcommand(0x8D); //CHARGEPUMP
unsigned char multiplex;
unsigned char compins;
switch (Plugin_023_OLED_type)
{
case OLED_128x32:
multiplex = 0x1F;
compins = 0x02;
break;
default:
multiplex = 0x3F;
compins = 0x12;
}
Plugin_023_sendcommand(0xAE); //display off
Plugin_023_sendcommand(0xD5); //SETDISPLAYCLOCKDIV
Plugin_023_sendcommand(0x80); // the suggested ratio 0x80
Plugin_023_sendcommand(0xA8); //SSD1306_SETMULTIPLEX
Plugin_023_sendcommand(multiplex); //0x1F if 128x32, 0x3F if others (e.g. 128x64)
Plugin_023_sendcommand(0xD3); //SETDISPLAYOFFSET
Plugin_023_sendcommand(0x00); //no offset
Plugin_023_sendcommand(0x40 | 0x0); //SETSTARTLINE
Plugin_023_sendcommand(0x8D); //CHARGEPUMP
Plugin_023_sendcommand(0x14);
Plugin_023_sendcommand(0x20); //MEMORYMODE
Plugin_023_sendcommand(0x00); //0x0 act like ks0108
Plugin_023_sendcommand(0xA0);
Plugin_023_sendcommand(0xC0);
Plugin_023_sendcommand(0xDA); //0xDA
Plugin_023_sendcommand(0x12); //COMSCANDEC
Plugin_023_sendcommand(0x81); //SETCONTRAS
Plugin_023_sendcommand(0x20); //MEMORYMODE
Plugin_023_sendcommand(0x00); //0x0 act like ks0108
Plugin_023_sendcommand(0xA0); //128x32 ???
Plugin_023_sendcommand(0xC0); //128x32 ???
Plugin_023_sendcommand(0xDA); //COMPINS
Plugin_023_sendcommand(compins); //0x02 if 128x32, 0x12 if others (e.g. 128x64)
Plugin_023_sendcommand(0x81); //SETCONTRAS
Plugin_023_sendcommand(0xCF);
Plugin_023_sendcommand(0xd9); //SETPRECHARGE
Plugin_023_sendcommand(0xD9); //SETPRECHARGE
Plugin_023_sendcommand(0xF1);
Plugin_023_sendcommand(0xDB); //SETVCOMDETECT
Plugin_023_sendcommand(0xDB); //SETVCOMDETECT
Plugin_023_sendcommand(0x40);
Plugin_023_sendcommand(0xA4); //DISPLAYALLON_RESUME
Plugin_023_sendcommand(0xA6); //NORMALDISPLAY
Plugin_023_sendcommand(0xA4); //DISPLAYALLON_RESUME
Plugin_023_sendcommand(0xA6); //NORMALDISPLAY
Plugin_023_clear_display();
Plugin_023_sendcommand(0x2e); // stop scroll
Plugin_023_sendcommand(0x2E); // stop scroll
Plugin_023_sendcommand(0x20); //Set Memory Addressing Mode
Plugin_023_sendcommand(0x00); //Set Memory Addressing Mode ab Horizontal addressing mode
}
+8 -2
View File
@@ -40,7 +40,7 @@ boolean Plugin_026(byte function, struct EventStruct *event, String& string)
case PLUGIN_WEBFORM_LOAD:
{
byte choice = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
String options[9];
String options[10];
options[0] = F("Uptime");
options[1] = F("Free RAM");
options[2] = F("Wifi RSSI");
@@ -50,7 +50,8 @@ boolean Plugin_026(byte function, struct EventStruct *event, String& string)
options[6] = F("IP 2.Octet");
options[7] = F("IP 3.Octet");
options[8] = F("IP 4.Octet");
addFormSelector(string, F("Indicator"), F("plugin_026"), 9, options, NULL, choice);
options[9] = F("Web activity");
addFormSelector(string, F("Indicator"), F("plugin_026"), 10, options, NULL, choice);
success = true;
break;
@@ -117,6 +118,11 @@ boolean Plugin_026(byte function, struct EventStruct *event, String& string)
value = WiFi.localIP()[3];
break;
}
case 9:
{
value = (millis()-lastWeb)/1000; // respond in seconds
break;
}
}
UserVar[event->BaseVarIndex] = value;
String log = F("SYS : ");
+341 -122
View File
@@ -2,54 +2,57 @@
//#################### Plugin 028 BME280 I2C Temp/Hum/Barometric Pressure Sensor #######################
//#######################################################################################################
//#include <math.h>
#define PLUGIN_028
#define PLUGIN_ID_028 28
#define PLUGIN_NAME_028 "Environment - BME280"
#define PLUGIN_NAME_028 "Environment - BMx280"
#define PLUGIN_VALUENAME1_028 "Temperature"
#define PLUGIN_VALUENAME2_028 "Humidity"
#define PLUGIN_VALUENAME3_028 "Pressure"
enum
{
BME280_REGISTER_DIG_T1 = 0x88,
BME280_REGISTER_DIG_T2 = 0x8A,
BME280_REGISTER_DIG_T3 = 0x8C,
#define PLUGIN_028_BME280_DEVICE "BME280"
#define PLUGIN_028_BMP280_DEVICE "BMP280"
BME280_REGISTER_DIG_P1 = 0x8E,
BME280_REGISTER_DIG_P2 = 0x90,
BME280_REGISTER_DIG_P3 = 0x92,
BME280_REGISTER_DIG_P4 = 0x94,
BME280_REGISTER_DIG_P5 = 0x96,
BME280_REGISTER_DIG_P6 = 0x98,
BME280_REGISTER_DIG_P7 = 0x9A,
BME280_REGISTER_DIG_P8 = 0x9C,
BME280_REGISTER_DIG_P9 = 0x9E,
// Minimal interval in msec.
#define BMx280_MEASUREMENT_INTERVAL_MSEC 50000
BME280_REGISTER_DIG_H1 = 0xA1,
BME280_REGISTER_DIG_H2 = 0xE1,
BME280_REGISTER_DIG_H3 = 0xE3,
BME280_REGISTER_DIG_H4 = 0xE4,
BME280_REGISTER_DIG_H5 = 0xE5,
BME280_REGISTER_DIG_H6 = 0xE7,
#define BMx280_REGISTER_DIG_T1 0x88
#define BMx280_REGISTER_DIG_T2 0x8A
#define BMx280_REGISTER_DIG_T3 0x8C
BME280_REGISTER_CHIPID = 0xD0,
BME280_REGISTER_VERSION = 0xD1,
BME280_REGISTER_SOFTRESET = 0xE0,
#define BMx280_REGISTER_DIG_P1 0x8E
#define BMx280_REGISTER_DIG_P2 0x90
#define BMx280_REGISTER_DIG_P3 0x92
#define BMx280_REGISTER_DIG_P4 0x94
#define BMx280_REGISTER_DIG_P5 0x96
#define BMx280_REGISTER_DIG_P6 0x98
#define BMx280_REGISTER_DIG_P7 0x9A
#define BMx280_REGISTER_DIG_P8 0x9C
#define BMx280_REGISTER_DIG_P9 0x9E
BME280_REGISTER_CAL26 = 0xE1, // R calibration stored in 0xE1-0xF0
#define BMx280_REGISTER_DIG_H1 0xA1
#define BMx280_REGISTER_DIG_H2 0xE1
#define BMx280_REGISTER_DIG_H3 0xE3
#define BMx280_REGISTER_DIG_H4 0xE4
#define BMx280_REGISTER_DIG_H5 0xE5
#define BMx280_REGISTER_DIG_H6 0xE7
BME280_REGISTER_CONTROLHUMID = 0xF2,
BME280_REGISTER_STATUS = 0xF3,
BME280_REGISTER_CONTROL = 0xF4,
BME280_REGISTER_CONFIG = 0xF5,
BME280_REGISTER_PRESSUREDATA = 0xF7,
BME280_REGISTER_TEMPDATA = 0xFA,
BME280_REGISTER_HUMIDDATA = 0xFD,
#define BMx280_REGISTER_CHIPID 0xD0
#define BMx280_REGISTER_VERSION 0xD1
#define BMx280_REGISTER_SOFTRESET 0xE0
BME280_CONTROL_SETTING = 0x25, // Oversampling: 1x P, 1x T, forced
BME280_CONTROL_SETTING_HUMIDITY = 0x01, // Oversampling: 1x H
BME280_CONFIG_SETTING = 0xA0, // Tstandby 1000ms, filter off, 3-wire SPI Disable
};
#define BMx280_REGISTER_CAL26 0xE1 // R calibration stored in 0xE1-0xF0
#define BMx280_REGISTER_CONTROLHUMID 0xF2
#define BMx280_REGISTER_STATUS 0xF3
#define BMx280_REGISTER_CONTROL 0xF4
#define BMx280_REGISTER_CONFIG 0xF5
#define BMx280_REGISTER_PRESSUREDATA 0xF7
#define BMx280_REGISTER_TEMPDATA 0xFA
#define BMx280_REGISTER_HUMIDDATA 0xFD
#define BME280_CONTROL_SETTING_HUMIDITY 0x02 // Oversampling: 2x H
typedef struct
{
@@ -76,14 +79,99 @@ typedef struct
} bme280_calib_data;
bme280_calib_data _bme280_calib[2];
boolean Plugin_028_init[2] = {false, false};
int Plugin_28_i2c_addresses[2] = { 0x76, 0x77 };
uint8_t _i2caddr;
int32_t _sensorID;
int32_t t_fine;
static float last_hum_val[2] = {0.0, 0.0};
static float last_press_val[2] = {0.0, 0.0};
static float last_temp_val[2] = {0.0, 0.0};
static float last_dew_temp_val[2] = {0.0, 0.0};
static unsigned long last_measurement[2] = {0, 0};
enum BMx_ChipId {
Unknown_DEVICE = 0,
BMP280_DEVICE_SAMPLE1 = 0x56,
BMP280_DEVICE_SAMPLE2 = 0x57,
BMP280_DEVICE = 0x58,
BME280_DEVICE = 0x60
};
BMx_ChipId _sensorID[2] = {Unknown_DEVICE, Unknown_DEVICE};
byte Plugin_028_get_config_settings() {
const uint8_t idx = Plugin_028_device_index(_i2caddr);
switch (_sensorID[idx]) {
case BMP280_DEVICE_SAMPLE1:
case BMP280_DEVICE_SAMPLE2:
case BMP280_DEVICE: return 0x28; // Tstandby 62.5ms, filter 4, 3-wire SPI Disable
case BME280_DEVICE: return 0x28; // Tstandby 62.5ms, filter 4, 3-wire SPI Disable
default: return 0;
}
}
byte Plugin_028_get_control_settings() {
const uint8_t idx = Plugin_028_device_index(_i2caddr);
switch (_sensorID[idx]) {
case BMP280_DEVICE_SAMPLE1:
case BMP280_DEVICE_SAMPLE2:
case BMP280_DEVICE: return 0x93; // Oversampling: 8x P, 8x T, normal mode
case BME280_DEVICE: return 0x93; // Oversampling: 8x P, 8x T, normal mode
default: return 0;
}
}
String Plugin_028_getFullDeviceName() {
const uint8_t idx = Plugin_028_device_index(_i2caddr);
String devicename = Plugin_028_getDeviceName();
if (_sensorID[idx] == BMP280_DEVICE_SAMPLE1 ||
_sensorID[idx] == BMP280_DEVICE_SAMPLE2)
{
devicename += F(" sample");
}
return devicename;
}
String Plugin_028_getDeviceName() {
const uint8_t idx = Plugin_028_device_index(_i2caddr);
switch (_sensorID[idx]) {
case BMP280_DEVICE_SAMPLE1:
case BMP280_DEVICE_SAMPLE2:
case BMP280_DEVICE: return PLUGIN_028_BMP280_DEVICE;
case BME280_DEVICE: return PLUGIN_028_BME280_DEVICE;
default: return F("Unknown");
}
}
boolean Plugin_028_hasHumidity() {
const uint8_t idx = Plugin_028_device_index(_i2caddr);
switch (_sensorID[idx]) {
case BMP280_DEVICE_SAMPLE1:
case BMP280_DEVICE_SAMPLE2:
case BMP280_DEVICE: return false;
case BME280_DEVICE: return true;
default: return false;
}
}
uint8_t Plugin_028_read8(byte reg, bool * is_ok = NULL); // Declaration
boolean Plugin_028_init[2] = {false, false};
uint8_t Plugin_028_i2c_addr(struct EventStruct *event) {
_i2caddr = (uint8_t)Settings.TaskDevicePluginConfig[event->TaskIndex][0];
if (_i2caddr != Plugin_28_i2c_addresses[0] && _i2caddr != Plugin_28_i2c_addresses[1]) {
// Set to default address
_i2caddr = Plugin_28_i2c_addresses[0];
}
return _i2caddr;
}
uint8_t Plugin_028_device_index(const uint8_t i2cAddress) {
return i2cAddress & 0x1; //Addresses are 0x76 and 0x77 so we may use it this way
}
boolean Plugin_028(byte function, struct EventStruct *event, String& string)
{
@@ -123,68 +211,80 @@ boolean Plugin_028(byte function, struct EventStruct *event, String& string)
case PLUGIN_WEBFORM_LOAD:
{
byte choice = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
/*
String options[2];
options[0] = F("0x76 - default settings (SDO Low)");
options[1] = F("0x77 - alternate settings (SDO HIGH)");
*/
int optionValues[2] = { 0x76, 0x77 };
addFormSelectorI2C(string, F("plugin_028_bme280_i2c"), 2, optionValues, choice);
const uint8_t i2cAddress = Plugin_028_i2c_addr(event);
addFormSelectorI2C(string, F("plugin_028_bme280_i2c"), 2, Plugin_28_i2c_addresses, i2cAddress);
const uint8_t idx = Plugin_028_device_index(i2cAddress);
if (_sensorID[idx] != Unknown_DEVICE) {
String detectedString = F("Detected: ");
detectedString += Plugin_028_getFullDeviceName();
addUnit(string, detectedString);
}
addFormNote(string, F("SDO Low=0x76, High=0x77"));
addFormNumericBox(string, F("Altitude"), F("plugin_028_bme280_elev"), Settings.TaskDevicePluginConfig[event->TaskIndex][1]);
addUnit(string, F("m"));
addFormNumericBox(string, F("Temperature offset"), F("plugin_028_bme280_tempoffset"), Settings.TaskDevicePluginConfig[event->TaskIndex][2]);
addUnit(string, F("x 0.1C"));
String offsetNote = F("Offset in units of 0.1 degree Celcius");
if (Plugin_028_hasHumidity()) {
offsetNote += F(" (also correct humidity)");
}
addFormNote(string, offsetNote);
success = true;
break;
}
case PLUGIN_WEBFORM_SAVE:
{
Settings.TaskDevicePluginConfig[event->TaskIndex][0] = getFormItemInt(F("plugin_028_bme280_i2c"));
const uint8_t i2cAddress = getFormItemInt(F("plugin_028_bme280_i2c"));
Plugin_028_check(i2cAddress); // Check id device is present
Settings.TaskDevicePluginConfig[event->TaskIndex][0] = i2cAddress;
Settings.TaskDevicePluginConfig[event->TaskIndex][1] = getFormItemInt(F("plugin_028_bme280_elev"));
Settings.TaskDevicePluginConfig[event->TaskIndex][2] = getFormItemInt(F("plugin_028_bme280_tempoffset"));
success = true;
break;
}
case PLUGIN_READ:
{
uint8_t idx = Settings.TaskDevicePluginConfig[event->TaskIndex][0] & 0x1; //Addresses are 0x76 and 0x77 so we may use it this way
Plugin_028_init[idx] &= Plugin_028_check(Settings.TaskDevicePluginConfig[event->TaskIndex][0]); // Check id device is present
Plugin_028_init[idx] &= (Plugin_028_read8(BME280_REGISTER_CONTROL) == BME280_CONTROL_SETTING); // Check if the coefficients are still valid
if (!Plugin_028_init[idx])
{
Plugin_028_init[idx] = Plugin_028_begin(Settings.TaskDevicePluginConfig[event->TaskIndex][0]);
delay(65); //May be needed here as well to fix first wrong measurement?
const uint8_t i2cAddress = Plugin_028_i2c_addr(event);
const uint8_t idx = Plugin_028_device_index(i2cAddress);
const float tempOffset = Settings.TaskDevicePluginConfig[event->TaskIndex][2] / 10.0;
if (!Plugin_028_update_measurements(i2cAddress, tempOffset)) {
success = false;
break;
}
if (Plugin_028_init[idx])
{
UserVar[event->BaseVarIndex] = Plugin_028_readTemperature(idx);
UserVar[event->BaseVarIndex + 1] = ((float)Plugin_028_readHumidity(idx));
int elev = Settings.TaskDevicePluginConfig[event->TaskIndex][1];
if (elev)
{
UserVar[event->BaseVarIndex + 2] = Plugin_028_pressureElevation((float)Plugin_028_readPressure(idx) / 100, elev);
} else {
UserVar[event->BaseVarIndex + 2] = ((float)Plugin_028_readPressure(idx)) / 100;
}
String log = F("BME : Address: 0x");
log += String(_i2caddr,HEX);
addLog(LOG_LEVEL_INFO, log);
log = F("BME : Temperature: ");
log += UserVar[event->BaseVarIndex];
addLog(LOG_LEVEL_INFO, log);
log = F("BME : Humidity: ");
UserVar[event->BaseVarIndex] = last_temp_val[idx];
UserVar[event->BaseVarIndex + 1] = last_hum_val[idx];
const int elev = Settings.TaskDevicePluginConfig[event->TaskIndex][1];
if (elev) {
UserVar[event->BaseVarIndex + 2] = Plugin_028_pressureElevation(last_press_val[idx], elev);
} else {
UserVar[event->BaseVarIndex + 2] = last_press_val[idx];
}
String log;
log.reserve(40); // Prevent re-allocation
log = Plugin_028_getDeviceName();
log += F(" : Address: 0x");
log += String(_i2caddr,HEX);
addLog(LOG_LEVEL_INFO, log);
log = Plugin_028_getDeviceName();
log += F(" : Temperature: ");
log += UserVar[event->BaseVarIndex];
addLog(LOG_LEVEL_INFO, log);
if (Plugin_028_hasHumidity()) {
log = Plugin_028_getDeviceName();
log += F(" : Humidity: ");
log += UserVar[event->BaseVarIndex + 1];
addLog(LOG_LEVEL_INFO, log);
log = F("BME : Barometric Pressure: ");
log += UserVar[event->BaseVarIndex + 2];
addLog(LOG_LEVEL_INFO, log);
success = true;
}
log = Plugin_028_getDeviceName();
log += F(" : Barometric Pressure: ");
log += UserVar[event->BaseVarIndex + 2];
addLog(LOG_LEVEL_INFO, log);
success = true;
break;
}
@@ -192,18 +292,125 @@ boolean Plugin_028(byte function, struct EventStruct *event, String& string)
return success;
}
// Only perform the measurements with big interval to prevent the sensor from warming up.
bool Plugin_028_update_measurements(uint8_t i2cAddress, float tempOffset) {
const uint8_t idx = Plugin_028_device_index(i2cAddress);
const unsigned long current_time = millis();
if ((last_measurement[idx] > BMx280_MEASUREMENT_INTERVAL_MSEC) &&
(current_time < (last_measurement[idx] + BMx280_MEASUREMENT_INTERVAL_MSEC)) &&
(current_time > last_measurement[idx])) {
// Timeout has not yet been reached.
return false;
}
Plugin_028_init[idx] &= Plugin_028_check(i2cAddress); // Check id device is present
if (!Plugin_028_init[idx]) {
Plugin_028_init[idx] = Plugin_028_begin(i2cAddress);
}
if (Plugin_028_init[idx]) {
last_measurement[idx] = current_time;
// Set the Sensor in sleep to be make sure that the following configs will be stored
Plugin_028_write8(BMx280_REGISTER_CONTROL, 0x00);
if (Plugin_028_hasHumidity()) {
Plugin_028_write8(BMx280_REGISTER_CONTROLHUMID, BME280_CONTROL_SETTING_HUMIDITY);
}
Plugin_028_write8(BMx280_REGISTER_CONFIG, Plugin_028_get_config_settings());
Plugin_028_write8(BMx280_REGISTER_CONTROL, Plugin_028_get_control_settings());
// Start measurement
delay(1000); // Wait one second to make sure the filtered values stabilize.
last_temp_val[idx] = Plugin_028_readTemperature(i2cAddress);
last_press_val[idx] = ((float)Plugin_028_readPressure(i2cAddress)) / 100;
last_hum_val[idx] = ((float)Plugin_028_readHumidity(i2cAddress));
// Set to sleep mode again to prevent the sensor from heating up.
Plugin_028_write8(BMx280_REGISTER_CONTROL, 0x00);
String log;
log.reserve(120); // Prevent re-allocation
log = Plugin_028_getDeviceName();
log += F(":");
boolean logAdded = false;
if (Plugin_028_hasHumidity()) {
// Apply half of the temp offset, to correct the dew point offset.
// The sensor is warmer than the surrounding air, which has effect on the perceived humidity.
last_dew_temp_val[idx] = compute_dew_point_temp(last_temp_val[idx] + (tempOffset / 2.0), last_hum_val[idx]);
} else {
// No humidity measurement, thus set dew point equal to air temperature.
last_dew_temp_val[idx] = last_temp_val[idx];
}
if (tempOffset > 0.1 || tempOffset < -0.1) {
// There is some offset to apply.
log += F(" Apply temp offset ");
log += tempOffset;
log += F("C");
if (Plugin_028_hasHumidity()) {
log += F(" humidity ");
log += last_hum_val[idx];
last_hum_val[idx] = compute_humidity_from_dewpoint(last_temp_val[idx] + tempOffset, last_dew_temp_val[idx]);
log += F("% => ");
log += last_hum_val[idx];
log += F("%");
}
log += F(" temperature ");
log += last_temp_val[idx];
last_temp_val[idx] = last_temp_val[idx] + tempOffset;
log += F("C => ");
log += last_temp_val[idx];
log += F("C");
logAdded = true;
}
if (Plugin_028_hasHumidity()) {
log += F(" dew point ");
log += last_dew_temp_val[idx];
log += F("C");
logAdded = true;
}
if (logAdded)
addLog(LOG_LEVEL_INFO, log);
return true;
}
return false;
}
//**************************************************************************/
// Check BME280 presence
//**************************************************************************/
bool Plugin_028_check(uint8_t a) {
_i2caddr = a?a:0x76;
const uint8_t idx = Plugin_028_device_index(_i2caddr);
bool wire_status = false;
if (Plugin_028_read8(BME280_REGISTER_CHIPID, &wire_status) != 0x60) {
return false;
} else {
return wire_status;
const uint8_t chip_id = Plugin_028_read8(BMx280_REGISTER_CHIPID, &wire_status);
switch (chip_id) {
case BMP280_DEVICE_SAMPLE1:
case BMP280_DEVICE_SAMPLE2:
case BMP280_DEVICE:
case BME280_DEVICE: {
if (wire_status) {
// Store detected chip ID when chip found.
if (_sensorID[idx] != chip_id) {
_sensorID[idx] = static_cast<BMx_ChipId>(chip_id);
String log = F("BMx280 : Detected ");
log += Plugin_028_getFullDeviceName();
addLog(LOG_LEVEL_INFO, log);
}
} else {
_sensorID[idx] = Unknown_DEVICE;
}
break;
}
default:
_sensorID[idx] = Unknown_DEVICE;
break;
}
if (_sensorID[idx] == Unknown_DEVICE) {
String log = F("BMx280 : Unable to detect chip ID");
addLog(LOG_LEVEL_INFO, log);
return false;
}
return wire_status;
}
//**************************************************************************/
@@ -212,16 +419,11 @@ bool Plugin_028_check(uint8_t a) {
bool Plugin_028_begin(uint8_t a) {
if (! Plugin_028_check(a))
return false;
Plugin_028_readCoefficients(_i2caddr & 0x01);
// Set the Sensor in sleep to be make sure that the following configs will be stored
Plugin_028_write8(BME280_REGISTER_CONTROL, 0x00);
Plugin_028_write8(BME280_REGISTER_CONFIG, BME280_CONFIG_SETTING);
Plugin_028_write8(BME280_REGISTER_CONTROLHUMID, BME280_CONTROL_SETTING_HUMIDITY);
Plugin_028_write8(BME280_REGISTER_CONTROL, BME280_CONTROL_SETTING);
// Perform soft reset
Plugin_028_write8(BMx280_REGISTER_SOFTRESET, 0xB6);
delay(2); // Startup time is 2 ms (datasheet)
Plugin_028_readCoefficients(a);
delay(65); //May be needed here as well to fix first wrong measurement?
return true;
}
@@ -314,45 +516,48 @@ int16_t Plugin_028_readS16_LE(byte reg)
//**************************************************************************/
// Reads the factory-set coefficients
//**************************************************************************/
void Plugin_028_readCoefficients(uint8_t idx)
void Plugin_028_readCoefficients(uint8_t i2cAddress)
{
_bme280_calib[idx].dig_T1 = Plugin_028_read16_LE(BME280_REGISTER_DIG_T1);
_bme280_calib[idx].dig_T2 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_T2);
_bme280_calib[idx].dig_T3 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_T3);
const uint8_t idx = Plugin_028_device_index(i2cAddress);
_bme280_calib[idx].dig_P1 = Plugin_028_read16_LE(BME280_REGISTER_DIG_P1);
_bme280_calib[idx].dig_P2 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_P2);
_bme280_calib[idx].dig_P3 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_P3);
_bme280_calib[idx].dig_P4 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_P4);
_bme280_calib[idx].dig_P5 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_P5);
_bme280_calib[idx].dig_P6 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_P6);
_bme280_calib[idx].dig_P7 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_P7);
_bme280_calib[idx].dig_P8 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_P8);
_bme280_calib[idx].dig_P9 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_P9);
_bme280_calib[idx].dig_T1 = Plugin_028_read16_LE(BMx280_REGISTER_DIG_T1);
_bme280_calib[idx].dig_T2 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_T2);
_bme280_calib[idx].dig_T3 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_T3);
_bme280_calib[idx].dig_H1 = Plugin_028_read8(BME280_REGISTER_DIG_H1);
_bme280_calib[idx].dig_H2 = Plugin_028_readS16_LE(BME280_REGISTER_DIG_H2);
_bme280_calib[idx].dig_H3 = Plugin_028_read8(BME280_REGISTER_DIG_H3);
_bme280_calib[idx].dig_H4 = (Plugin_028_read8(BME280_REGISTER_DIG_H4) << 4) | (Plugin_028_read8(BME280_REGISTER_DIG_H4 + 1) & 0xF);
_bme280_calib[idx].dig_H5 = (Plugin_028_read8(BME280_REGISTER_DIG_H5 + 1) << 4) | (Plugin_028_read8(BME280_REGISTER_DIG_H5) >> 4);
_bme280_calib[idx].dig_H6 = (int8_t)Plugin_028_read8(BME280_REGISTER_DIG_H6);
_bme280_calib[idx].dig_P1 = Plugin_028_read16_LE(BMx280_REGISTER_DIG_P1);
_bme280_calib[idx].dig_P2 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_P2);
_bme280_calib[idx].dig_P3 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_P3);
_bme280_calib[idx].dig_P4 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_P4);
_bme280_calib[idx].dig_P5 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_P5);
_bme280_calib[idx].dig_P6 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_P6);
_bme280_calib[idx].dig_P7 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_P7);
_bme280_calib[idx].dig_P8 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_P8);
_bme280_calib[idx].dig_P9 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_P9);
if (Plugin_028_hasHumidity()) {
_bme280_calib[idx].dig_H1 = Plugin_028_read8(BMx280_REGISTER_DIG_H1);
_bme280_calib[idx].dig_H2 = Plugin_028_readS16_LE(BMx280_REGISTER_DIG_H2);
_bme280_calib[idx].dig_H3 = Plugin_028_read8(BMx280_REGISTER_DIG_H3);
_bme280_calib[idx].dig_H4 = (Plugin_028_read8(BMx280_REGISTER_DIG_H4) << 4) | (Plugin_028_read8(BMx280_REGISTER_DIG_H4 + 1) & 0xF);
_bme280_calib[idx].dig_H5 = (Plugin_028_read8(BMx280_REGISTER_DIG_H5 + 1) << 4) | (Plugin_028_read8(BMx280_REGISTER_DIG_H5) >> 4);
_bme280_calib[idx].dig_H6 = (int8_t)Plugin_028_read8(BMx280_REGISTER_DIG_H6);
}
}
//**************************************************************************/
// Read temperature
//**************************************************************************/
float Plugin_028_readTemperature(uint8_t idx)
float Plugin_028_readTemperature(uint8_t i2cAddress)
{
const uint8_t idx = Plugin_028_device_index(i2cAddress);
int32_t var1, var2;
// set to forced mode, i.e. "take next measurement"
Plugin_028_write8(BME280_REGISTER_CONTROL, BME280_CONTROL_SETTING);
// wait until measurement has been completed, otherwise we would read
// the values from the last measurement
while (Plugin_028_read8(BME280_REGISTER_STATUS) & 0x08)
while (Plugin_028_read8(BMx280_REGISTER_STATUS) & 0x08)
delay(1);
int32_t adc_T = Plugin_028_read24(BME280_REGISTER_TEMPDATA);
int32_t adc_T = Plugin_028_read24(BMx280_REGISTER_TEMPDATA);
adc_T >>= 4;
var1 = ((((adc_T >> 3) - ((int32_t)_bme280_calib[idx].dig_T1 << 1))) *
@@ -371,10 +576,12 @@ float Plugin_028_readTemperature(uint8_t idx)
//**************************************************************************/
// Read pressure
//**************************************************************************/
float Plugin_028_readPressure(uint8_t idx) {
float Plugin_028_readPressure(uint8_t i2cAddress)
{
const uint8_t idx = Plugin_028_device_index(i2cAddress);
int64_t var1, var2, p;
int32_t adc_P = Plugin_028_read24(BME280_REGISTER_PRESSUREDATA);
int32_t adc_P = Plugin_028_read24(BMx280_REGISTER_PRESSUREDATA);
adc_P >>= 4;
var1 = ((int64_t)t_fine) - 128000;
@@ -400,9 +607,21 @@ float Plugin_028_readPressure(uint8_t idx) {
//**************************************************************************/
// Read humidity
//**************************************************************************/
float Plugin_028_readHumidity(uint8_t idx) {
int32_t adc_H = Plugin_028_read16(BME280_REGISTER_HUMIDDATA);
float Plugin_028_readHumidity(uint8_t i2cAddress)
{
if (!Plugin_028_hasHumidity()) {
// 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.
const uint8_t idx = Plugin_028_device_index(i2cAddress);
unsigned long difTime = millis() - last_measurement[idx];
if (difTime < 1587) {
delay(1587 - difTime);
}
int32_t adc_H = Plugin_028_read16(BMx280_REGISTER_HUMIDDATA);
int32_t v_x1_u32r;
@@ -438,7 +657,7 @@ float Plugin_028_readAltitude(float seaLevel)
// at high altitude. See this thread for more information:
// http://forums.adafruit.com/viewtopic.php?f=22&t=58064
float atmospheric = Plugin_028_readPressure(_i2caddr & 0x01) / 100.0F;
float atmospheric = Plugin_028_readPressure(_i2caddr) / 100.0F;
return 44330.0 * (1.0 - pow(atmospheric / seaLevel, 0.1903));
}
+17 -11
View File
@@ -137,14 +137,14 @@ boolean Plugin_035(byte function, struct EventStruct *event, String& string)
for (uint t = 0; t < c0; t++)
printWebString += F("0");
}
//So, as we recieve a "1", and processed the counted 0s
//So, as we receive a "1", and processed the counted 0s
//sending them as a ms timing into the buffer, we clear
//the 0s counter
c0 = 0;
} else {
//So, bit is 0
//On first call, ignore 0s (supress left-most 0s)
//On first call, ignore 0s (suppress left-most 0s)
if (c0+c1 != 0) {
//add 1 to counter c0
c0++;
@@ -154,11 +154,11 @@ boolean Plugin_035(byte function, struct EventStruct *event, String& string)
//add the total ms into the buffer (number of 1s
//multiplied by defined pulse length ms)
buf[idx++] = c1 * IrPLen;
//print the number of 1s just for debuging/info purpouses
//print the number of 1s just for debugging/info purposes
for (uint t = 0; t < c1; t++)
printWebString += F("1");
}
//So, as we recieve a "0", and processed the counted 1s
//So, as we receive a "0", and processed the counted 1s
//sending them as a ms timing into the buffer, we clear
//the 1s counter
c1 = 0;
@@ -195,17 +195,23 @@ boolean Plugin_035(byte function, struct EventStruct *event, String& string)
//sprintf_P(log, PSTR("IR Params2: RAW Code:%s"), IrRaw.c_str());
//addLog(LOG_LEVEL_INFO, log);
} else {
unsigned int IrRepeat=0;
unsigned long IrSecondCode=0UL;
if (GetArgv(command, TmpStr1, 2)) IrType = TmpStr1;
if (GetArgv(command, TmpStr1, 3)) IrCode = strtoul(TmpStr1, NULL, 16); //(long) TmpStr1
if (GetArgv(command, TmpStr1, 4)) IrBits = str2int(TmpStr1);
if (GetArgv(command, TmpStr1, 5)) IrRepeat = str2int(TmpStr1);
if (GetArgv(command, TmpStr1, 6)) IrSecondCode = strtoul(TmpStr1, NULL, 16);
if (IrType.equalsIgnoreCase(F("NEC"))) Plugin_035_irSender->sendNEC(IrCode, IrBits);
if (IrType.equalsIgnoreCase(F("JVC"))) Plugin_035_irSender->sendJVC(IrCode, IrBits, 2);
if (IrType.equalsIgnoreCase(F("RC5"))) Plugin_035_irSender->sendRC5(IrCode, IrBits);
if (IrType.equalsIgnoreCase(F("RC6"))) Plugin_035_irSender->sendRC6(IrCode, IrBits);
if (IrType.equalsIgnoreCase(F("SAMSUNG"))) Plugin_035_irSender->sendSAMSUNG(IrCode, IrBits);
if (IrType.equalsIgnoreCase(F("SONY"))) Plugin_035_irSender->sendSony(IrCode, IrBits);
if (IrType.equalsIgnoreCase(F("PANASONIC"))) Plugin_035_irSender->sendPanasonic(IrBits, IrCode);
if (IrType.equalsIgnoreCase("NEC")) Plugin_035_irSender->sendNEC(IrCode, IrBits);
if (IrType.equalsIgnoreCase("JVC")) Plugin_035_irSender->sendJVC(IrCode, IrBits, 2);
if (IrType.equalsIgnoreCase("RC5")) Plugin_035_irSender->sendRC5(IrCode, IrBits);
if (IrType.equalsIgnoreCase("RC6")) Plugin_035_irSender->sendRC6(IrCode, IrBits);
if (IrType.equalsIgnoreCase("SAMSUNG")) Plugin_035_irSender->sendSAMSUNG(IrCode, IrBits);
if (IrType.equalsIgnoreCase("SONY")) Plugin_035_irSender->sendSony(IrCode, IrBits);
if (IrType.equalsIgnoreCase("PANASONIC")) Plugin_035_irSender->sendPanasonic(IrBits, IrCode);
if (IrType.equalsIgnoreCase("PIONEER")) Plugin_035_irSender->sendPioneer(IrCode, IrBits, IrRepeat, IrSecondCode);
}
addLog(LOG_LEVEL_INFO, F("IRTX :IR Code Sent"));
+21 -3
View File
@@ -15,6 +15,11 @@
// If you use 'NeoPixelAll' this will off all LED (like NeoPixelAll,0,0,0)
// (3): Set color LED between <start led nr> and <stop led nr> to specified color (eg. NeoPixelLine,1,6,255,255,255)
//RGBW note:
// for RGBW strips append the additional <brightness> to the commands
// eg: NeoPixel,<led nr>,<red 0-255>,<green 0-255>,<blue 0-255>,<brightness 0-255>
// The NeoPixelLine command does not work for RGBW, cause espeasy currently only allows max. 5 parameters
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel *Plugin_038_pixels;
@@ -55,8 +60,13 @@ boolean Plugin_038(byte function, struct EventStruct *event, String& string)
case PLUGIN_WEBFORM_LOAD:
{
const String options[] = { F("GRB"), F("GRBW") };
int indices[] = { 1, 2 };
addFormNumericBox(string, F("Led Count"), F("plugin_038_leds"), Settings.TaskDevicePluginConfig[event->TaskIndex][0],1,999);
addFormPinSelect(string, F("GPIO"), F("taskdevicepin1"), Settings.TaskDevicePin1[event->TaskIndex]);
addFormSelector(string, F("Strip Type"), F("plugin_038_strip"), 2, options, indices, Settings.TaskDevicePluginConfig[event->TaskIndex][1] );
success = true;
break;
}
@@ -65,6 +75,7 @@ boolean Plugin_038(byte function, struct EventStruct *event, String& string)
{
Settings.TaskDevicePluginConfig[event->TaskIndex][0] = getFormItemInt(F("plugin_038_leds"));
MaxPixels = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
Settings.TaskDevicePluginConfig[event->TaskIndex][1] = getFormItemInt(F("plugin_038_strip"));
success = true;
break;
}
@@ -73,7 +84,14 @@ boolean Plugin_038(byte function, struct EventStruct *event, String& string)
{
if (!Plugin_038_pixels)
{
Plugin_038_pixels = new Adafruit_NeoPixel(Settings.TaskDevicePluginConfig[event->TaskIndex][0], Settings.TaskDevicePin1[event->TaskIndex], NEO_GRB + NEO_KHZ800);
byte striptype = Settings.TaskDevicePluginConfig[event->TaskIndex][1];
if (striptype == 1)
Plugin_038_pixels = new Adafruit_NeoPixel(Settings.TaskDevicePluginConfig[event->TaskIndex][0], Settings.TaskDevicePin1[event->TaskIndex], NEO_GRB + NEO_KHZ800);
else if (striptype == 2)
Plugin_038_pixels = new Adafruit_NeoPixel(Settings.TaskDevicePluginConfig[event->TaskIndex][0], Settings.TaskDevicePin1[event->TaskIndex], NEO_GRBW + NEO_KHZ800);
else
Plugin_038_pixels = new Adafruit_NeoPixel(Settings.TaskDevicePluginConfig[event->TaskIndex][0], Settings.TaskDevicePin1[event->TaskIndex], NEO_GRB + NEO_KHZ800);
Plugin_038_pixels->begin(); // This initializes the NeoPixel library.
}
MaxPixels = Settings.TaskDevicePluginConfig[event->TaskIndex][0];
@@ -98,7 +116,7 @@ boolean Plugin_038(byte function, struct EventStruct *event, String& string)
// string.toCharArray(Line, 80);
// int Par4 = 0;
// if (GetArgv(Line, TmpStr1, 5)) Par4 = str2int(TmpStr1);
Plugin_038_pixels->setPixelColor(event->Par1 - 1, Plugin_038_pixels->Color(event->Par2, event->Par3, event->Par4));
Plugin_038_pixels->setPixelColor(event->Par1 - 1, Plugin_038_pixels->Color(event->Par2, event->Par3, event->Par4, event->Par5));
Plugin_038_pixels->show(); // This sends the updated pixel color to the hardware.
success = true;
}
@@ -111,7 +129,7 @@ boolean Plugin_038(byte function, struct EventStruct *event, String& string)
// string.toCharArray(Line, 80);
for (int i = 0; i < MaxPixels; i++)
{
Plugin_038_pixels->setPixelColor(i, Plugin_038_pixels->Color(event->Par1, event->Par2, event->Par3));
Plugin_038_pixels->setPixelColor(i, Plugin_038_pixels->Color(event->Par1, event->Par2, event->Par3, event->Par4));
}
Plugin_038_pixels->show();
success = true;
+40 -13
View File
@@ -9,15 +9,15 @@
// MAX6675 or MAX31855 in order to read the values. Take a look at ebay to find such boards :-)
// You can only use ESP8266 boards which expose the SPI Interface. This Plugin uses only the Hardware
// SPI Interface - no software SPI at the moment.
// But neverless you need at least 3 Pins to use SPI. So using an very simple ESP-01 is no option - Sorry.
// The Wiring ist straight forward ...
// But nevertheless you need at least 3 Pins to use SPI. So using an very simple ESP-01 is no option - Sorry.
// The Wiring is straight forward ...
//
// If you like to send suggestions feel free to send me an email : dominik@logview.info
// Have fun ... Dominik
// Wiring
// https://de.wikipedia.org/wiki/Serial_Peripheral_Interface
// You need an ESP8266 device with accessable SPI Pins. These are:
// You need an ESP8266 device with accessible SPI Pins. These are:
// Name Description GPIO NodeMCU Notes
// MOSI Master Output GPIO13 D7 Not used (No Data sending to MAX)
// MISO Master Input GPIO12 D6 Hardware SPI
@@ -42,6 +42,7 @@
uint8_t Plugin_039_SPI_CS_Pin = 15; // D8
bool Plugin_039_SensorAttached = true;
uint32_t Plugin_039_Sensor_fault = 0;
double Plugin_039_Celsius = 0.0;
boolean Plugin_039(byte function, struct EventStruct *event, String& string)
@@ -231,9 +232,28 @@ double readMax31855()
log += String(rawvalue);
addLog(LOG_LEVEL_DEBUG, log);
if (Plugin_039_Sensor_fault != (rawvalue & 0x7)) {
// Fault code changed, log them
Plugin_039_Sensor_fault = (rawvalue & 0x7);
log = F("P039 : MAX31855");
if (Plugin_039_Sensor_fault == 0) {
log += F("Fault resolved");
} else {
log += F("Fault code:");
if (rawvalue & 0x01) {
log += F(" Open (no connection)");
}
if (rawvalue & 0x02) {
log += F(" Short-circuit to GND");
}
if (rawvalue & 0x04) {
log += F(" Short-circuit to Vcc");
}
}
addLog(LOG_LEVEL_DEBUG, log);
}
// D16 - This bit reads at 1 when any of the SCV, SCG, or OC faults are active. Default value is 0.
Plugin_039_SensorAttached = !(rawvalue & 0x00010000);
if (Plugin_039_SensorAttached)
{
// Data is D[31:18]
@@ -246,19 +266,26 @@ double readMax31855()
// -0.25 1111 1111 1111 11
// -1.00 1111 1111 1111 00
// -250.00 1111 0000 0110 00
if (rawvalue & 0x2000) // Bit 31=1 -> neg Values
{
// Negate all Bits
rawvalue = ~rawvalue;
// Add 1 and make negative
rawvalue = (rawvalue + 1) * -1;
}
// We're left with (32 - 18 =) 14 bits
int temperature = Plugin_039_convert_two_complement(rawvalue, 14);
// Calculate Celsius
return rawvalue * 0.25;
return temperature * 0.25;
}
else
{
// Fault state, thus output no value.
return NAN;
}
}
int Plugin_039_convert_two_complement(uint32_t value, int nr_bits) {
const bool negative = (value & (1 << (nr_bits - 1))) != 0;
int nativeInt;
if (negative) {
// Add zeroes to the left to create the proper negative native-sized integer.
nativeInt = value | ~((1 << nr_bits) - 1);
} else {
nativeInt = value;
}
return nativeInt;
}
+4 -4
View File
@@ -11,7 +11,7 @@
// * Extract jscolor.min.js
// * Now open the Web UI of your ESPEasy with this URL:
// http://<IP-ESPEasy>/upload
// * Select Browse ... and choose the extracted jscolor.min.js File (ensure the ...min... verion !!)
// * Select Browse ... and choose the extracted jscolor.min.js File (ensure the ...min... version !!)
// * Press Upload und you are done.
// Add the Adafruit Neopixel Library to your library path. You will find it here:
@@ -21,14 +21,14 @@
// NOTES
// Please keep in mind that you can add tasks which produce a very large delay while reading the sensor.
// For example the DS18B20 is very slow in reading the values. This can slow down the simulation and you
// will notice that the candle did not run smooth. So keep an eye on your tasks and donßt add to much other tasks.
// will notice that the candle did not run smooth. So keep an eye on your tasks and don't add to much other tasks.
// HARDWARE
// The Wifi Candle uses 20 WS2812 RGB pixels. They are all connected in one row.
// I build a wooden wick with 5 pixels on each side. (A picture is here : http://www.esp8266.nu/forum/viewtopic.php?f=2&t=2147)
// The pixels are connected to 5V and the data pin I use is GPIO13 (but you can choose another one).
// Please ensure that you use a strong power supply because the pixels consume a lot of power when they
// shine in white with high brigthness!
// shine in white with high brightness!
// I also placed a 100µF capacitor at the end of the WS2812 chain on +5/GND just to ensure a good power stability.
// btw ... My Testboard was a NodeMCU V3.
@@ -80,7 +80,7 @@ byte Candle_bright = 128;
SimType Candle_type = TypeSimpleCandle;
ColorType Candle_color = ColorDefault;
// gloable Variables
// global variables
unsigned long Candle_Update = 0;
word Candle_Temp[4] = { 0, 0, 0 }; // Temp variables
int Candle_Temp4 = 0;
+34 -10
View File
@@ -108,12 +108,23 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
LoadTaskSettings(event->TaskIndex);
if ((ExtraTaskSettings.TaskDevicePluginConfigLong[0] != 0) && (ExtraTaskSettings.TaskDevicePluginConfigLong[1] != 0))
{
byte serialconfig = 0x10;
#if defined(ESP8266)
byte serialconfig = 0x10;
#endif
#if defined(ESP32)
uint32_t serialconfig = 0x8000010;
#endif
serialconfig += ExtraTaskSettings.TaskDevicePluginConfigLong[3];
serialconfig += (ExtraTaskSettings.TaskDevicePluginConfigLong[2] - 5) << 2;
if (ExtraTaskSettings.TaskDevicePluginConfigLong[4] == 2)
serialconfig += 0x20;
Serial.begin(ExtraTaskSettings.TaskDevicePluginConfigLong[1], (SerialConfig)serialconfig);
#if defined(ESP8266)
Serial.begin(ExtraTaskSettings.TaskDevicePluginConfigLong[1], (SerialConfig)serialconfig);
#endif
#if defined(ESP32)
Serial.begin(ExtraTaskSettings.TaskDevicePluginConfigLong[1], serialconfig);
#endif
if (P1GatewayServer) P1GatewayServer->close();
P1GatewayServer = new WiFiServer(ExtraTaskSettings.TaskDevicePluginConfigLong[0]);
P1GatewayServer->begin();
@@ -138,7 +149,7 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
addLog(LOG_LEVEL_DEBUG, F("P1 : DSMR version 4 meter, CRC on"));
CRCcheck = true;
} else {
addLog(LOG_LEVEL_DEBUG, F("P1 : DSMR version 4 meter, CRC on"));
addLog(LOG_LEVEL_DEBUG, F("P1 : DSMR version 4 meter, CRC off"));
CRCcheck = false;
}
@@ -148,6 +159,17 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
break;
}
case PLUGIN_EXIT:
{
if (P1GatewayServer) {
P1GatewayServer->close();
//FIXME: shouldnt P1P1GatewayServer be deleted?
P1GatewayServer = NULL;
}
success = true;
break;
}
case PLUGIN_TEN_PER_SECOND:
{
if (Plugin_044_init)
@@ -223,8 +245,8 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
break;
case WAITING:
if (ch == '/') {
Plugin_044_serial_buf[bytes_read] = ch;
bytes_read++;
Plugin_044_serial_buf[0] = ch;
bytes_read=1;
state = READING;
} // else ignore data
break;
@@ -239,6 +261,10 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
if (validP1char(ch)) {
Plugin_044_serial_buf[bytes_read] = ch;
bytes_read++;
} else if (ch=='/') {
addLog(LOG_LEVEL_DEBUG, F("P1 : Error: Start detected, discarded input."));
Plugin_044_serial_buf[0] = ch;
bytes_read = 1;
} else { // input is non-ascii
addLog(LOG_LEVEL_DEBUG, F("P1 : Error: DATA corrupt, discarded input."));
Serial.flush();
@@ -248,13 +274,12 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
break;
case CHECKSUM:
checkI ++;
if (checkI == 5) {
if (checkI == 4) {
checkI = 0;
state = DONE;
} else {
Plugin_044_serial_buf[bytes_read] = ch;
bytes_read++;
}
Plugin_044_serial_buf[bytes_read] = ch;
bytes_read++;
break;
case DONE:
// Plugin_044_serial_buf[bytes_read]= '\n';
@@ -278,7 +303,6 @@ boolean Plugin_044(byte function, struct EventStruct *event, String& string)
if (state == DONE) {
if (checkDatagram(bytes_read)) {
bytes_read++;
Plugin_044_serial_buf[bytes_read] = '\r';
bytes_read++;
Plugin_044_serial_buf[bytes_read] = '\n';
+7 -7
View File
@@ -17,23 +17,23 @@
// included in all copies or substantial portions of the Software.
// This plugin enables the use of a MPU6050 sensor as e.g. used in the breakoutboard GY-521.
// This plugin enables the use of a MPU6050 sensor as e.g. used in the breakout-board GY-521.
// Using the webform you can set thresholds for the x-y-z axis and timeout values. If the thresholds are
// exceeded the sensor is on, if the thresholds are not met during the timeout period the sensor is off.
// Using this plugin you can get a notification from your home automationsystem when the monitored machine or
// device is no longer vibrating and thus this can be used as a signaling device for the end of a (dish)washer
// Using this plugin you can get a notification from your home automation system when the monitored machine or
// device is no longer vibrating and thus this can be used as a signalling device for the end of a (dish)washer
// or dryer cycle.
// You can also use the plugin to read raw sensorvalues. You can use more then one instance of the plugin and
// You can also use the plugin to read raw sensor values. You can use more then one instance of the plugin and
// you can set multiple movement alarms by giving each instance other threshold values if needed.
// Best practise: Create three custom sensors in your homecontroller (like domoticz) and let it plot the x, y and
// z range. Plot the sensorvalues while you use the washingmachine and/or dryer. Also keep monitoring when they
// Best practise: Create three custom sensors in your home controller (like domoticz) and let it plot the x, y and
// z range. Plot the sensor values while you use the washing machine and/or dryer. Also keep monitoring when they
// are not in use so you can determine the needed thresholds. When you have these you can select the movement
// detection function to setup the plugin for further use.
// The plugin can simultanious be used with two MPU6050 devices by adding multiple instances.
// The plugin can be used simultaneously with two MPU6050 devices by adding multiple instances.
// Originally released in the PlayGround as Plugin 118.
// Plugin var usage:
+34 -34
View File
@@ -5,26 +5,26 @@
// Purpose: Sniff the data received by the Ventus W266 display unit and send it to Domoticz
// Status : "Initial release"
// This plugin can be used on a esp8266 connected to the recievermodule inside a Ventus W266 or
// Renkforce W205GU display unit. The plugin then reads the data send from the remote sensorunit and
// This plugin can be used on a esp8266 connected to the receiver module inside a Ventus W266 or
// Renkforce W205GU display unit. The plugin then reads the data send from the remote sensor unit and
// can send the data to Domoticz or an other controller. The plugin does not read the data of the
// sensors in the display unit such as indoor temperature and airpressure.
// sensors in the display unit such as indoor temperature and air pressure.
// The displaynit has a RFM31 reciever but the pinout of this receiver is identical to the pinout
// of a RFM01 reciever. We need to connect 4 wires to read the SPI exchange between the host and the
// reciever. Because we need to read both MOSI and MISO signals the hardware SPI is unusable and we
// use bitbanging to achive the same result.
// The display unit has a RFM31 receiver but the pinout of this receiver is identical to the pinout
// of a RFM01 receiver. We need to connect 4 wires to read the SPI exchange between the host and the
// receiver. Because we need to read both MOSI and MISO signals the hardware SPI is unusable and we
// use bit-banging to achieve the same result.
// Connect pins 5-8 from the "RFM31BJ-S1" to the pins you defined in de webgui.
// Connect pins 5-8 from the "RFM31BJ-S1" to the pins you defined in the webgui.
// Pinout of the RFM31: 5-MOSI, 6-SCLK, 7-nSEL (active low CS), 8-MISO, 14-GND.
// In my original setup these were connected to 4, 12, 14 and 5.
// Try to avoid GPIO 15 as nSEL line because if the line is high during a reboot, and it is mostly high,
// the boot will fail!
// The Ventus W266 remote has the following sensor outputs:
// Humidity, Temperature, Wind direction, Wind avarage, Wind gust, Rainfall, UV and Lightning. That is
// Humidity, Temperature, Wind direction, Wind average, Wind gust, Rainfall, UV and Lightning. That is
// more than te maximum of 4 values per device for espeasy. The plugins functionality is therefore
// devided per sensorgroup. To read all the sensor data you need to run 6 instances of the plugin.
// divided per sensor group. To read all the sensor data you need to run 6 instances of the plugin.
// The plugin can (and should) be used more then one time, however only one plugin instance can be
// the main plugin. The plugin function can be selected by a dropdown and only the main plugin has
@@ -32,25 +32,25 @@
// The plugin uses two buffers, ine for the ISR routines and one for the other plugin instances.
// This plugin was originally released into th eplayground as Plugin 186, it is assimilated into the core as 046.
// This plugin was originally released into the playground as Plugin 186, it is assimilated into the core as 046.
// Why plugin nr 186? Well 266 is not possible, 206 (id on the back of the unit) is nit within the
// playground range and the W186 is an additinal external thermometer for the Ventus W266.
// playground range and the W186 is an additional external thermometer for the Ventus W266.
// The Ventus W266 is also known as the Renkforce W205GU.
// TaskDevicePluginConfig[x][0] = Instance function
// TaskDevicePluginConfig[x][1] = MOSI (eg. GPOI pin 4)
// TaskDevicePluginConfig[x][2] = SCLK (eg. GPIO pin 12)
// TaskDevicePluginConfig[x][3] = nSEL (eg. GPIO pin 14)
// TaskDevicePluginConfig[x][4] = MISO (eg. GPIO pin 5)
// TaskDevicePluginConfig[x][1] = MOSI (e.g. GPOI pin 4)
// TaskDevicePluginConfig[x][2] = SCLK (e.g. GPIO pin 12)
// TaskDevicePluginConfig[x][3] = nSEL (e.g. GPIO pin 14)
// TaskDevicePluginConfig[x][4] = MISO (e.g. GPIO pin 5)
// If you use GPIO 4&5, please disable the I2C/SPI option in the hardware tab.
// The buffers contain the following data:
// hhIDhh 1A tlth ?b tlth wb alahglgh rlrh?? uv ld?? lllhcrc
// 7F9827 1A B100 00 B100 06 00000000 1E0000 00 3F8A 2A0017
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2
// hh=header > This is actualy not part of the real payload but a wanted artifact of the sniffing method.
// hh=header > This is actually not part of the real payload but a wanted artifact of the sniffing method.
// hh=humidity (bcd) > Humidity is bcd encoded
// tlth=temperature-low/temphigh (*10) > Temperature is stored as a 16bit integer holding the temperature in Celcius * 10 but low byte first.
// tlth=temperature-low/temphigh (*10) > Temperature is stored as a 16bit integer holding the temperature in Celsius * 10 but low byte first.
// b=battery (1=low) > This byte is 00 but 01 when the battery of the transmitter runs low
// wb=bearing (cw0-15) > The windbearing in 16 clockwise steps (0 = north, 4 = east, 8 = south and C = west)
// alah=windaverage-low/high (m/s/2) > A 16 bit int holding the wind avarage in m/s * 2, low byte first
@@ -79,7 +79,7 @@
#ifdef PLUGIN_BUILD_DISABLED
// #ifdef PLUGIN_BUILD_TESTING
#define PLUGIN_046_DEBUG true // Shows recieved frames and crc in log@INFO
#define PLUGIN_046_DEBUG true // Shows received frames and crc in log@INFO
#define PLUGIN_046 // Mandatory framework constants
#define PLUGIN_ID_046 46
@@ -100,12 +100,12 @@ int8_t Plugin_046_MISOpin = -1;
byte Plugin_046_ISR_Buffer[Plugin_046_RAW_BUFFER_SIZE]; // Buffer used in ISR routine
//Test data: volatile byte Plugin_046_databuffer[] = {0x7F, 0x98, 0x33, 0x1A, 0xB0, 0x00, 0x00, 0xB0, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x3F, 0x8A, 0x25, 0x00, 0x49, 0x00}; // Buffer used by other instances
byte Plugin_046_databuffer[Plugin_046_RAW_BUFFER_SIZE]; // Buffer used by other instances
boolean Plugin_046_RecieveActive = false; // Active session in progress
boolean Plugin_046_ReceiveActive = false; // Active session in progress
boolean Plugin_046_MasterSlave = false; // Which pin o read? false=MOSI, true=MISO
boolean Plugin_046_newData = false; // "Valid" data ready, please process
byte Plugin_046_bitpointer; // Pointer for recieved bit
byte Plugin_046_bytepointer; // Pointe for ISR recieve buffer
byte Plugin_046_recievedData; // Byte to store recieved bits
byte Plugin_046_bitpointer; // Pointer for received bit
byte Plugin_046_bytepointer; // Pointer for ISR receive buffer
byte Plugin_046_receivedData; // Byte to store received bits
// Vars used for interpreting the data:
volatile unsigned long Plugin_046_lastrainctr; // Keep track of wdcounter (1/2 min tick)
@@ -294,7 +294,7 @@ boolean Plugin_046(byte function, struct EventStruct *event, String& string)
if (Plugin_046_newData) {
uint8_t crc = 0xff; // init = 0xff
char data; // CRC = MAXIM with modified init: poly 0x31, init 0xff, refin 1; refout 1, xorout 0x00
// Copy recieved data to buffer and check CRC
// Copy received data to buffer and check CRC
Plugin_046_databuffer[0] = Plugin_046_ISR_Buffer[0];
for (int i = 1; i < Plugin_046_bytepointer; i++) {
data = Plugin_046_ISR_Buffer[i];
@@ -458,39 +458,39 @@ boolean Plugin_046(byte function, struct EventStruct *event, String& string)
void Plugin_046_ISR_nSEL() // Interrupt on nSEL change
{
if (digitalRead(Plugin_046_nSELpin)) {
Plugin_046_RecieveActive = false; // nSEL high? Recieve done.
if (Plugin_046_MasterSlave) { // If MISO not active, no data recieved
Plugin_046_ReceiveActive = false; // nSEL high? Receive done.
if (Plugin_046_MasterSlave) { // If MISO not active, no data received
if (Plugin_046_bytepointer == Plugin_046_Payload) { // If not 23 then bad datapacket
Plugin_046_newData = true; // We have new data!
}
}
} else { // nSEL low? Start recieve
} else { // nSEL low? Start receive
if (!Plugin_046_newData) { // Only accept new data if the old is processed
Plugin_046_bitpointer = 7; // reset pointer (MSB first)
Plugin_046_bytepointer = 0; // reset pointers & flags
Plugin_046_MasterSlave = false;
Plugin_046_RecieveActive = true; // We are now recieving data
Plugin_046_ReceiveActive = true; // We are now receiving data
}
}
}
void Plugin_046_ISR_SCLK() // Interrupt on SCLK rising
{
if (Plugin_046_RecieveActive) { // Are we recieving or glitch?
if (Plugin_046_ReceiveActive) { // Are we receiving or glitch?
if (Plugin_046_MasterSlave) { // Read MISO or MOSI?
bitWrite(Plugin_046_recievedData, Plugin_046_bitpointer, digitalRead(Plugin_046_MISOpin));
bitWrite(Plugin_046_receivedData, Plugin_046_bitpointer, digitalRead(Plugin_046_MISOpin));
} else {
bitWrite(Plugin_046_recievedData, Plugin_046_bitpointer, digitalRead(Plugin_046_MOSIpin));
bitWrite(Plugin_046_receivedData, Plugin_046_bitpointer, digitalRead(Plugin_046_MOSIpin));
}
if (Plugin_046_bitpointer == 0) { // 8 bits done?
Plugin_046_bitpointer = 7;
if (Plugin_046_recievedData==Plugin_046_MagicByte) { // Switch data pins?
if (Plugin_046_receivedData==Plugin_046_MagicByte) { // Switch data pins?
Plugin_046_MasterSlave = true;
}
Plugin_046_ISR_Buffer[Plugin_046_bytepointer] = Plugin_046_recievedData;
Plugin_046_ISR_Buffer[Plugin_046_bytepointer] = Plugin_046_receivedData;
Plugin_046_bytepointer++; // TReady for the next byte ...
if (Plugin_046_bytepointer > Plugin_046_RAW_BUFFER_SIZE) {
Plugin_046_RecieveActive = false; // We don't want a bufferoverflow, so abort
Plugin_046_ReceiveActive = false; // We don't want a bufferoverflow, so abort
Plugin_046_MasterSlave = false;
}
} else {
+6 -5
View File
@@ -102,17 +102,18 @@ boolean Plugin_048(byte function, struct EventStruct *event, String& string) {
String tmpString = string;
String cmd = parseString(tmpString, 1);
String param1 = parseString(tmpString, 2);
String param2 = parseString(tmpString, 3);
String param3 = parseString(tmpString, 4);
String param4 = parseString(tmpString, 5);
String param5 = parseString(tmpString, 6);
// Commands:
// MotorShieldCMD,<DCMotor>,<Motornumber>,<Forward/Backward/Release>,<Speed>
if (cmd.equalsIgnoreCase(F("MotorShieldCMD")))
{
String param1 = parseString(tmpString, 2);
String param2 = parseString(tmpString, 3);
String param3 = parseString(tmpString, 4);
String param4 = parseString(tmpString, 5);
String param5 = parseString(tmpString, 6);
// Create the motor shield object with the default I2C address
AFMS = Adafruit_MotorShield(Plugin_048_MotorShield_address);
+163 -58
View File
@@ -17,6 +17,12 @@
#define PLUGIN_VALUENAME3_049 "U" // Undocumented, minimum measurement per time period?
#define PLUGIN_READ_TIMEOUT 3000
#define PLUGIN_049_FILTER_OFF 1
#define PLUGIN_049_FILTER_OFF_ALLSAMPLES 2
#define PLUGIN_049_FILTER_FAST 3
#define PLUGIN_049_FILTER_MEDIUM 4
#define PLUGIN_049_FILTER_SLOW 5
boolean Plugin_049_init = false;
// Default of the sensor is to run ABC
boolean Plugin_049_ABC_Disable = false;
@@ -25,17 +31,38 @@ boolean Plugin_049_ABC_MustApply = false;
#include <ESPeasySoftwareSerial.h>
ESPeasySoftwareSerial *Plugin_049_SoftSerial;
// 9-bytes CMD PPM read command
byte mhzCmdReadPPM[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
byte mhzResp[9]; // 9 bytes bytes response
byte mhzCmdCalibrateZero[9] = {0xFF,0x01,0x87,0x00,0x00,0x00,0x00,0x00,0x78};
byte mhzCmdABCEnable[9] = {0xFF,0x01,0x79,0xA0,0x00,0x00,0x00,0x00,0xE6};
byte mhzCmdABCDisable[9] = {0xFF,0x01,0x79,0x00,0x00,0x00,0x00,0x00,0x86};
byte mhzCmdReset[9] = {0xFF,0x01,0x8d,0x00,0x00,0x00,0x00,0x00,0x72};
byte mhzCmdMeasurementRange1000[9] = {0xFF,0x01,0x99,0x00,0x00,0x00,0x03,0xE8,0x7B};
byte mhzCmdMeasurementRange2000[9] = {0xFF,0x01,0x99,0x00,0x00,0x00,0x07,0xD0,0x8F};
byte mhzCmdMeasurementRange3000[9] = {0xFF,0x01,0x99,0x00,0x00,0x00,0x0B,0xB8,0xA3};
byte mhzCmdMeasurementRange5000[9] = {0xFF,0x01,0x99,0x00,0x00,0x00,0x13,0x88,0xCB};
enum mhzCommands : byte { mhzCmdReadPPM,
mhzCmdCalibrateZero,
mhzCmdABCEnable,
mhzCmdABCDisable,
mhzCmdReset,
mhzCmdMeasurementRange1000,
mhzCmdMeasurementRange2000,
mhzCmdMeasurementRange3000,
mhzCmdMeasurementRange5000 };
// 9 byte commands:
// mhzCmdReadPPM[] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
// mhzCmdCalibrateZero[] = {0xFF,0x01,0x87,0x00,0x00,0x00,0x00,0x00,0x78};
// mhzCmdABCEnable[] = {0xFF,0x01,0x79,0xA0,0x00,0x00,0x00,0x00,0xE6};
// mhzCmdABCDisable[] = {0xFF,0x01,0x79,0x00,0x00,0x00,0x00,0x00,0x86};
// mhzCmdReset[] = {0xFF,0x01,0x8d,0x00,0x00,0x00,0x00,0x00,0x72};
// mhzCmdMeasurementRange1000[] = {0xFF,0x01,0x99,0x03,0xE8,0x00,0x00,0x00,0x7B};
// mhzCmdMeasurementRange2000[] = {0xFF,0x01,0x99,0x07,0xD0,0x00,0x00,0x00,0x8F};
// mhzCmdMeasurementRange3000[] = {0xFF,0x01,0x99,0x0B,0xB8,0x00,0x00,0x00,0xA3};
// mhzCmdMeasurementRange5000[] = {0xFF,0x01,0x99,0x13,0x88,0x00,0x00,0x00,0xCB};
// Removing redundant data, just keeping offsets [2]..[4]:
const PROGMEM byte mhzCmdData[][3] = {
{0x86,0x00,0x00},
{0x87,0x00,0x00},
{0x79,0xA0,0x00},
{0x79,0x00,0x00},
{0x8d,0x00,0x00},
{0x99,0x03,0xE8},
{0x99,0x07,0xD0},
{0x99,0x0B,0xB8},
{0x99,0x13,0x88}};
byte mhzResp[9]; // 9 byte response buffer
enum
{
@@ -43,6 +70,56 @@ enum
ABC_disabled = 0x02
};
boolean Plugin_049_Check_and_ApplyFilter(unsigned int prevVal, unsigned int &newVal, uint32_t s, const int filterValue, String& log) {
if (s == 1) {
// S==1 => "A" version sensor bootup, do not use values.
return false;
}
if (prevVal < 400 || prevVal > 5000) {
// Prevent unrealistic values during start-up with filtering enabled.
// Just assume the entered value is correct.
return true;
}
boolean filterApplied = filterValue > PLUGIN_049_FILTER_OFF_ALLSAMPLES;
int32_t difference = newVal - prevVal;
if (s > 0 && s < 64 && filterValue != PLUGIN_049_FILTER_OFF) {
// Not the "B" version of the sensor, S value is used.
// S==0 => "B" version, else "A" version
// The S value is an indication of the stability of the reading.
// S == 64 represents a stable reading and any lower value indicates (unusual) fast change.
// Now we increase the delay filter for low values of S and increase response time when the
// value is more stable.
// This will make the reading useful in more turbulent environments,
// where the sensor would report more rapid change of measured values.
difference = difference * s;
difference /= 64;
log += F("Compensate Unstable ");
filterApplied = true;
}
switch (filterValue) {
case PLUGIN_049_FILTER_OFF: {
if (s != 0 && s != 64) {
log += F("Skip Unstable ");
return false;
}
filterApplied = false;
break;
}
// #Samples to reach >= 75% of step response
case PLUGIN_049_FILTER_OFF_ALLSAMPLES: filterApplied = false; break; // No Delay
case PLUGIN_049_FILTER_FAST: difference /= 2; break; // Delay: 2 samples
case PLUGIN_049_FILTER_MEDIUM: difference /= 4; break; // Delay: 5 samples
case PLUGIN_049_FILTER_SLOW: difference /= 8; break; // Delay: 11 samples
}
if (filterApplied) {
log += F("Raw PPM: ");
log += newVal;
log += F(" Filtered ");
}
newVal = static_cast<unsigned int>(prevVal + difference);
return true;
}
boolean Plugin_049(byte function, struct EventStruct *event, String& string)
{
bool success = false;
@@ -86,6 +163,16 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
String options[2] = { F("Normal"), F("ABC disabled") };
int optionValues[2] = { ABC_enabled, ABC_disabled };
addFormSelector(string, F("Auto Base Calibration"), F("plugin_049_abcdisable"), 2, options, optionValues, choice);
byte choiceFilter = Settings.TaskDevicePluginConfig[event->TaskIndex][1];
String filteroptions[5] = { F("Skip Unstable"), F("Use Unstable"), F("Fast Response"), F("Medium Response"), F("Slow Response") };
int filteroptionValues[5] = {
PLUGIN_049_FILTER_OFF,
PLUGIN_049_FILTER_OFF_ALLSAMPLES,
PLUGIN_049_FILTER_FAST,
PLUGIN_049_FILTER_MEDIUM,
PLUGIN_049_FILTER_SLOW };
addFormSelector(string, F("Filter"), F("plugin_049_filter"), 5, filteroptions, filteroptionValues, choiceFilter);
success = true;
break;
}
@@ -100,6 +187,8 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
Plugin_049_ABC_Disable = new_ABC_disable;
}
Settings.TaskDevicePluginConfig[event->TaskIndex][0] = formValue;
const int filterValue = getFormItemInt(F("plugin_049_filter"));
Settings.TaskDevicePluginConfig[event->TaskIndex][1] = filterValue;
success = true;
break;
}
@@ -130,56 +219,56 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
if (command == F("mhzcalibratezero"))
{
Plugin_049_SoftSerial->write(mhzCmdCalibrateZero, 9);
_P049_send_mhzCmd(mhzCmdCalibrateZero);
addLog(LOG_LEVEL_INFO, F("MHZ19: Calibrated zero point!"));
success = true;
}
if (command == F("mhzreset"))
{
Plugin_049_SoftSerial->write(mhzCmdReset, 9);
_P049_send_mhzCmd(mhzCmdReset);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent sensor reset!"));
success = true;
}
if (command == F("mhzabcenable"))
{
Plugin_049_SoftSerial->write(mhzCmdABCEnable, 9);
_P049_send_mhzCmd(mhzCmdABCEnable);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent sensor ABC Enable!"));
success = true;
}
if (command == F("mhzabcdisable"))
{
Plugin_049_SoftSerial->write(mhzCmdABCDisable, 9);
_P049_send_mhzCmd(mhzCmdABCDisable);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent sensor ABC Disable!"));
success = true;
}
if (command == F("mhzmeasurementrange1000"))
{
Plugin_049_SoftSerial->write(mhzCmdMeasurementRange1000, 9);
_P049_send_mhzCmd(mhzCmdMeasurementRange1000);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent measurement range 0-1000PPM!"));
success = true;
}
if (command == F("mhzmeasurementrange2000"))
{
Plugin_049_SoftSerial->write(mhzCmdMeasurementRange2000, 9);
_P049_send_mhzCmd(mhzCmdMeasurementRange2000);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent measurement range 0-2000PPM!"));
success = true;
}
if (command == F("mhzmeasurementrange3000"))
{
Plugin_049_SoftSerial->write(mhzCmdMeasurementRange3000, 9);
_P049_send_mhzCmd(mhzCmdMeasurementRange3000);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent measurement range 0-3000PPM!"));
success = true;
}
if (command == F("mhzmeasurementrange5000"))
{
Plugin_049_SoftSerial->write(mhzCmdMeasurementRange5000, 9);
_P049_send_mhzCmd(mhzCmdMeasurementRange5000);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent measurement range 0-5000PPM!"));
success = true;
}
@@ -193,7 +282,7 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
if (Plugin_049_init)
{
//send read PPM command
int nbBytesSent = Plugin_049_SoftSerial->write(mhzCmdReadPPM, 9);
byte nbBytesSent = _P049_send_mhzCmd(mhzCmdReadPPM);
if (nbBytesSent != 9) {
String log = F("MHZ19: Error, nb bytes sent != 9 : ");
log += nbBytesSent;
@@ -217,19 +306,15 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
}
unsigned int ppm = 0;
int i;
signed int temp = 0;
unsigned int s = 0;
float u = 0;
byte crc = 0;
for (i = 1; i < 8; i++) crc+=mhzResp[i];
crc = 255 - crc;
crc++;
byte checksum = _P049_calculateChecksum(mhzResp);
if ( !(mhzResp[8] == crc) ) {
String log = F("MHZ19: Read error : CRC = ");
log += String(crc); log += " / "; log += String(mhzResp[8]);
log += " bytes read => ";for (i = 0; i < 9; i++) {log += mhzResp[i];log += "/" ;}
if ( !(mhzResp[8] == checksum) ) {
String log = F("MHZ19: Read error: checksum = ");
log += String(checksum); log += " / "; log += String(mhzResp[8]);
log += " bytes read => ";for (byte i = 0; i < 9; i++) {log += mhzResp[i];log += "/" ;}
addLog(LOG_LEVEL_ERROR, log);
// Sometimes there is a misalignment in the serial read
@@ -237,24 +322,24 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
// This goes on forever.
// There must be a better way to handle this, but here
// we're trying to shift it so that 0xFF is the next byte
byte crcshift;
for (i = 1; i < 8; i++) {
crcshift = Plugin_049_SoftSerial->peek();
if (crcshift == 0xFF) {
byte checksum_shift;
for (byte i = 1; i < 8; i++) {
checksum_shift = Plugin_049_SoftSerial->peek();
if (checksum_shift == 0xFF) {
String log = F("MHZ19: Shifted ");
log += i;
log += F(" bytes to attempt to fix buffer alignment");
addLog(LOG_LEVEL_ERROR, log);
break;
} else {
crcshift = Plugin_049_SoftSerial->read();
checksum_shift = Plugin_049_SoftSerial->read();
}
}
success = false;
break;
// Process responses to 0x86
} else if (mhzResp[0] == 0xFF && mhzResp[1] == 0x86 && mhzResp[8] == crc) {
} else if (mhzResp[0] == 0xFF && mhzResp[1] == 0x86 && mhzResp[8] == checksum) {
//calculate CO2 PPM
unsigned int mhzRespHigh = (unsigned int) mhzResp[2];
@@ -288,32 +373,31 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
log += F("Will disable ABC when bootup complete. ");
}
success = false;
// If s = 0x40 the reading is stable; anything else should be ignored
} else if (s > 0 && s < 64) {
log += F("Unstable reading, ignoring! ");
success = false;
// Finally, stable readings are used for variables
} else {
UserVar[event->BaseVarIndex] = (float)ppm;
UserVar[event->BaseVarIndex + 1] = (float)temp;
UserVar[event->BaseVarIndex + 2] = (float)u;
if (Plugin_049_ABC_MustApply) {
// Send ABC enable/disable command based on the desired state.
if (Plugin_049_ABC_Disable) {
Plugin_049_SoftSerial->write(mhzCmdABCDisable, 9);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent sensor ABC Disable!"));
} else {
Plugin_049_SoftSerial->write(mhzCmdABCEnable, 9);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent sensor ABC Enable!"));
const int filterValue = Settings.TaskDevicePluginConfig[event->TaskIndex][1];
if (Plugin_049_Check_and_ApplyFilter(UserVar[event->BaseVarIndex], ppm, s, filterValue, log)) {
UserVar[event->BaseVarIndex] = (float)ppm;
UserVar[event->BaseVarIndex + 1] = (float)temp;
UserVar[event->BaseVarIndex + 2] = (float)u;
if (s==0 || s==64) {
// Reading is stable.
if (Plugin_049_ABC_MustApply) {
// Send ABC enable/disable command based on the desired state.
if (Plugin_049_ABC_Disable) {
_P049_send_mhzCmd(mhzCmdABCDisable);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent sensor ABC Disable!"));
} else {
_P049_send_mhzCmd(mhzCmdABCEnable);
addLog(LOG_LEVEL_INFO, F("MHZ19: Sent sensor ABC Enable!"));
}
Plugin_049_ABC_MustApply = false;
}
}
Plugin_049_ABC_MustApply = false;
success = true;
} else {
success = false;
}
success = true;
}
// Log values in all cases
@@ -329,7 +413,7 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
break;
// Sensor responds with 0x99 whenever we send it a measurement range adjustment
} else if (mhzResp[0] == 0xFF && mhzResp[1] == 0x99 && mhzResp[8] == crc) {
} else if (mhzResp[0] == 0xFF && mhzResp[1] == 0x99 && mhzResp[8] == checksum) {
addLog(LOG_LEVEL_INFO, F("MHZ19: Received measurement range acknowledgment! "));
addLog(LOG_LEVEL_INFO, F("Expecting sensor reset..."));
@@ -356,3 +440,24 @@ boolean Plugin_049(byte function, struct EventStruct *event, String& string)
}
return success;
}
byte _P049_calculateChecksum(byte *array)
{
byte checksum = 0;
for (byte i = 1; i < 8; i++)
checksum+=array[i];
checksum = 0xFF - checksum;
return (checksum+1);
}
size_t _P049_send_mhzCmd(byte CommandId)
{
// The receive buffer "mhzResp" is re-used to send a command here:
mhzResp[0] = 0xFF; // Start byte, fixed
mhzResp[1] = 0x01; // Sensor number, 0x01 by default
memcpy_P(&mhzResp[2], mhzCmdData[CommandId], sizeof(mhzCmdData[0]));
mhzResp[5] = mhzResp[6] = mhzResp[7] = 0x00;
mhzResp[8] = _P049_calculateChecksum(mhzResp);
return Plugin_049_SoftSerial->write(mhzResp, sizeof(mhzResp));
}
+1 -1
View File
@@ -5,7 +5,7 @@
Plugin originally written by: Daniel Tedenljung info__AT__tedenljungconsulting.com
Rewritten by: Mikael Trieb mikael__AT__triebconsulting.se
This plugin reads availble values of Senseair Co2 Sensors.
This plugin reads available values of Senseair Co2 Sensors.
Datasheet can be found here:
S8: http://www.senseair.com/products/oem-modules/senseair-s8/
K30: http://www.senseair.com/products/oem-modules/k30/
+2 -2
View File
@@ -4,8 +4,8 @@
//
// http://www.aqmd.gov/docs/default-source/aq-spec/resources-page/plantower-pms5003-manual_v2-3.pdf?sfvrsn=2
//
// The PMSx003 are particle sensors. Particles are measured by blowing air though the enclosue and,
// togther with a laser, count the amount of particles. These sensors have an integrated microcontroller
// The PMSx003 are particle sensors. Particles are measured by blowing air through the enclosure and,
// together with a laser, count the amount of particles. These sensors have an integrated microcontroller
// that counts particles and transmits measurement data over the serial connection.
#ifdef PLUGIN_BUILD_TESTING
+1 -1
View File
@@ -34,7 +34,7 @@
// Transceiver:
// SN75176 or MAX485 or LT1785 or ...
// Pin 5: GND
// Pin 2, 3, 8: +5V
// Pin 2, 3, 5: +5V
// Pin 4: to ESP D4
// Pin 6: DMX+ (hot)
// Pin 7: DMX- (cold)
+3 -3
View File
@@ -2,7 +2,7 @@
//#################################### Plugin 055: Chiming Mechanism ####################################
//#######################################################################################################
// ESPEasy plugin to strike up to 4 pysical bells and gongs with chiming sequences.
// ESPEasy plugin to strike up to 4 physical bells and gongs with chiming sequences.
// You also can use an antique door bell as a single strikes (not ringing) notification.
// Optional you can use it as hourly chiming clock
// written by Jochen Krapf (jk@nerd2nerd.org)
@@ -37,8 +37,8 @@
// save tokens with name "<HH><MM>" and enable NTP (advanced settings)
//
// examples:
// CHIMESAVE,0815,1111! Dayly Alarm at 8:15am
// CHIMESAVE,2015,11121 Dayly Alarm at 8:15pm
// CHIMESAVE,0815,1111! Daily Alarm at 8:15am
// CHIMESAVE,2015,11121 Daily Alarm at 8:15pm
// CHIMESAVE,2015 Delete Alarm at 8:15pm
// Electronics:
+83 -15
View File
@@ -33,7 +33,7 @@ boolean Plugin_056(byte function, struct EventStruct *event, String& string)
case PLUGIN_DEVICE_ADD:
{
Device[++deviceCount].Number = PLUGIN_ID_056;
Device[deviceCount].Type = DEVICE_TYPE_SINGLE;
Device[deviceCount].Type = DEVICE_TYPE_DUAL;
Device[deviceCount].VType = SENSOR_TYPE_DUAL;
Device[deviceCount].Ports = 0;
Device[deviceCount].PullUpOption = false;
@@ -42,7 +42,7 @@ boolean Plugin_056(byte function, struct EventStruct *event, String& string)
Device[deviceCount].ValueCount = 2;
Device[deviceCount].SendDataOption = true;
Device[deviceCount].TimerOption = true;
Device[deviceCount].TimerOptional = true;
Device[deviceCount].TimerOptional = false;
Device[deviceCount].GlobalSyncOption = true;
break;
}
@@ -59,11 +59,34 @@ boolean Plugin_056(byte function, struct EventStruct *event, String& string)
strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[1], PSTR(PLUGIN_VALUENAME2_056));
break;
}
case PLUGIN_WEBFORM_LOAD:
{
if (Plugin_056_hasTxPin(event)) {
addFormNumericBox(string, F("Sleep time"), F("plugin_056_sleeptime"),
Settings.TaskDevicePluginConfig[event->TaskIndex][0],
0, 30);
addUnit(string, F("Minutes"));
addFormNote(string, F("0 = continous, 1..30 = Work 30 seconds and sleep n*60-30 seconds"));
}
break;
}
case PLUGIN_WEBFORM_SAVE:
{
if (Plugin_056_hasTxPin(event)) {
// Communications to device should work.
const int newsleeptime = getFormItemInt(F("plugin_056_sleeptime"));
if (Settings.TaskDevicePluginConfig[event->TaskIndex][0] != newsleeptime) {
Settings.TaskDevicePluginConfig[event->TaskIndex][0] = getFormItemInt(F("plugin_056_sleeptime"));
Plugin_056_setWorkingPeriod(newsleeptime);
}
}
success = true;
break;
}
case PLUGIN_GET_DEVICEGPIONAMES:
{
event->String1 = F("GPIO &larr; TX");
//event->String2 = F("GPIO &#8674; RX (optional)");
event->String2 = F("GPIO &#8674; RX (optional)");
break;
}
@@ -71,8 +94,14 @@ boolean Plugin_056(byte function, struct EventStruct *event, String& string)
{
if (Plugin_056_SDS)
delete Plugin_056_SDS;
Plugin_056_SDS = new CjkSDS011(Settings.TaskDevicePin1[event->TaskIndex], -1);
addLog(LOG_LEVEL_INFO, F("SDS : Init OK "));
const int16_t serial_rx = Settings.TaskDevicePin1[event->TaskIndex];
const int16_t serial_tx = Settings.TaskDevicePin2[event->TaskIndex];
Plugin_056_SDS = new CjkSDS011(serial_rx, serial_tx);
String log = F("SDS : Init OK ESP GPIO-pin RX:");
log += serial_rx;
log += F(" TX:");
log += serial_tx;
addLog(LOG_LEVEL_INFO, log);
success = true;
break;
@@ -98,16 +127,18 @@ boolean Plugin_056(byte function, struct EventStruct *event, String& string)
if (Plugin_056_SDS->available())
{
const float pm2_5 = Plugin_056_SDS->GetPM2_5();
const float pm10 = Plugin_056_SDS->GetPM10_();
String log = F("SDS : act ");
log += Plugin_056_SDS->GetPM2_5();
log += pm2_5;
log += F(" ");
log += Plugin_056_SDS->GetPM10_();
log += pm10;
addLog(LOG_LEVEL_DEBUG, log);
if (Settings.TaskDeviceTimer[event->TaskIndex] == 0)
{
UserVar[event->BaseVarIndex + 0] = Plugin_056_SDS->GetPM2_5();
UserVar[event->BaseVarIndex + 1] = Plugin_056_SDS->GetPM10_();
UserVar[event->BaseVarIndex + 0] = pm2_5;
UserVar[event->BaseVarIndex + 1] = pm10;
event->sensorType = SENSOR_TYPE_DUAL;
sendData(event);
}
@@ -123,11 +154,11 @@ boolean Plugin_056(byte function, struct EventStruct *event, String& string)
break;
float pm25, pm10;
Plugin_056_SDS->ReadAverage(pm25, pm10);
UserVar[event->BaseVarIndex + 0] = pm25;
UserVar[event->BaseVarIndex + 1] = pm10;
success = true;
if (Plugin_056_SDS->ReadAverage(pm25, pm10)) {
UserVar[event->BaseVarIndex + 0] = pm25;
UserVar[event->BaseVarIndex + 1] = pm10;
success = true;
}
break;
}
}
@@ -135,4 +166,41 @@ boolean Plugin_056(byte function, struct EventStruct *event, String& string)
return success;
}
boolean Plugin_056_hasTxPin(struct EventStruct *event) {
const int16_t serial_tx = Settings.TaskDevicePin2[event->TaskIndex];
return serial_tx >= 0;
}
String Plugin_056_ErrorToString(int error) {
String log;
if (error < 0) {
log = F("comm error: ");
log += error;
}
return log;
}
String Plugin_056_WorkingPeriodToString(int workingPeriod) {
if (workingPeriod < 0) {
return Plugin_056_ErrorToString(workingPeriod);
}
String log;
if (workingPeriod > 0) {
log += workingPeriod;
log += F(" minutes");
} else {
log += F(" continuous");
}
return log;
}
void Plugin_056_setWorkingPeriod(int minutes) {
if (!Plugin_056_SDS)
return;
Plugin_056_SDS->SetWorkingPeriod(minutes);
String log = F("SDS : Working Period set to: ");
log += Plugin_056_WorkingPeriodToString(minutes);
addLog(LOG_LEVEL_INFO, log);
}
#endif //PLUGIN_BUILD_TESTING
+3 -26
View File
@@ -7,17 +7,16 @@
// Connection:
// Use 1st and 2nd GPIO for encoders A and B signal.
// Optional use 3rd GPIO for encoders I signel to reset counter to 0 at first trigger.
// Optional use 3rd GPIO for encoders I signal to reset counter to 0 at first trigger.
// If counter runs in wrong direction, change A and B GPIOs in settings page
// Note: Up to 4 encoders can be used simultaniously
// Note: Up to 4 encoders can be used simultaneously
#ifdef PLUGIN_BUILD_TESTING
#define PLUGIN_059
#define PLUGIN_ID_059 59
#define PLUGIN_NAME_059 "Switch Input - Rotary Encoder [TESTING]"
#define PLUGIN_NAME_059 "Switch Input - Rotary Encoder"
#define PLUGIN_VALUENAME1_059 "Counter"
#include <QEIx4.h>
@@ -167,28 +166,6 @@ boolean Plugin_059(byte function, struct EventStruct *event, String& string)
break;
}
case PLUGIN_WRITE:
{
if (Plugin_059_QE)
{
String log = "";
String command = parseString(string, 1);
if (command == F("encwrite"))
{
if (event->Par1 >= 0)
{
log = String(F("QEI : ")) + string;
addLog(LOG_LEVEL_INFO, log);
Plugin_059_QE->write(event->Par1);
success = true;
}
}
}
break;
}
}
return success;
}
#endif
+2 -2
View File
@@ -81,11 +81,11 @@ boolean Plugin_060(byte function, struct EventStruct *event, String& string)
addFormCheckBox(string, F("Calibration Enabled"), F("plugin_060_cal"), CONFIG(3));
addFormNumericBox(string, F("Point 1"), F("plugin_060_adc1"), Settings.TaskDevicePluginConfigLong[event->TaskIndex][0], 0, 4095);
addFormNumericBox(string, F("Point 1"), F("plugin_060_adc1"), Settings.TaskDevicePluginConfigLong[event->TaskIndex][0], 0, 1023);
string += F(" &#8793; ");
addTextBox(string, F("plugin_060_out1"), String(Settings.TaskDevicePluginConfigFloat[event->TaskIndex][0], 3), 10);
addFormNumericBox(string, F("Point 2"), F("plugin_060_adc2"), Settings.TaskDevicePluginConfigLong[event->TaskIndex][1], 0, 4095);
addFormNumericBox(string, F("Point 2"), F("plugin_060_adc2"), Settings.TaskDevicePluginConfigLong[event->TaskIndex][1], 0, 1023);
string += F(" &#8793; ");
addTextBox(string, F("plugin_060_out2"), String(Settings.TaskDevicePluginConfigFloat[event->TaskIndex][1], 3), 10);
+4 -9
View File
@@ -5,8 +5,8 @@
// ESPEasy Plugin to scan a 16 key touch pad chip TTP229
// written by Jochen Krapf (jk@nerd2nerd.org)
// Important: There are several types of TTP299 chips with different features available. They are namead all TTP229 but differ in the letter(s) followed.
// On the china boards (found on eBay and AliExpress) the TTP229-B is used which has NO! I2C-interface. It uses a properitary serial protocol with clock (SCL) and bidirectional data (SDO)
// Important: There are several types of TTP299 chips with different features available. They are named all TTP229 but differ in the letter(s) followed.
// On the china boards (found on eBay and AliExpress) the TTP229-B is used which has NO! I2C-interface. It uses a proprietary serial protocol with clock (SCL) and bidirectional data (SDO)
// ScanCode;
// Value 1...16 for the key number
@@ -19,15 +19,12 @@
// Electronics:
// Connect SCL to 1st GPIO and SDO to 2nd GPIO. Use 3.3 volt for VCC.
// Set the jumper for 16 key mode (TP2=jumper3). Additional set jumper for multi-key (TP3=jumper4, TP4=jumper5).
// Scematics: https://www.openimpulse.com/blog/wp-content/uploads/wpsc/downloadables/TTP229B-Schematic-Diagram.pdf
// Schematics: https://www.openimpulse.com/blog/wp-content/uploads/wpsc/downloadables/TTP229B-Schematic-Diagram.pdf
// Datasheet: http://www.datasheet4u.com/download_new.php?id=996751
#ifdef PLUGIN_BUILD_TESTING
#define PLUGIN_063
#define PLUGIN_ID_063 63
#define PLUGIN_NAME_063 "Keypad - TTP229 Touch [TESTING]"
#define PLUGIN_NAME_063 "Keypad - TTP229 Touch"
#define PLUGIN_VALUENAME1_063 "ScanCode"
// #include <*.h> no lib required
@@ -207,5 +204,3 @@ boolean Plugin_063(byte function, struct EventStruct *event, String& string)
}
return success;
}
#endif
+8 -8
View File
@@ -87,7 +87,7 @@ void SHT3X::get()
#define CONFIG(n) (Settings.TaskDevicePluginConfig[event->TaskIndex][n])
#endif
SHT3X* Plugin_068_SHT3x[TASKS_MAX] = { NULL, };
SHT3X* Plugin_068_SHT3x = NULL;
//==============================================
@@ -148,9 +148,9 @@ boolean Plugin_068(byte function, struct EventStruct *event, String& string)
case PLUGIN_INIT:
{
if (Plugin_068_SHT3x[event->TaskIndex])
delete Plugin_068_SHT3x[event->TaskIndex];
Plugin_068_SHT3x[event->TaskIndex] = new SHT3X(CONFIG(0));
if (Plugin_068_SHT3x)
delete Plugin_068_SHT3x;
Plugin_068_SHT3x = new SHT3X(CONFIG(0));
success = true;
break;
@@ -158,12 +158,12 @@ boolean Plugin_068(byte function, struct EventStruct *event, String& string)
case PLUGIN_READ:
{
if (!Plugin_068_SHT3x[event->TaskIndex])
if (!Plugin_068_SHT3x)
return success;
Plugin_068_SHT3x[event->TaskIndex]->get();
UserVar[event->BaseVarIndex + 0] = Plugin_068_SHT3x[event->TaskIndex]->tmp;
UserVar[event->BaseVarIndex + 1] = Plugin_068_SHT3x[event->TaskIndex]->hum;
Plugin_068_SHT3x->get();
UserVar[event->BaseVarIndex + 0] = Plugin_068_SHT3x->tmp;
UserVar[event->BaseVarIndex + 1] = Plugin_068_SHT3x->hum;
String log = F("SHT3x: Temperature: ");
log += UserVar[event->BaseVarIndex + 0];
addLog(LOG_LEVEL_INFO, log);
+2 -4
View File
@@ -41,7 +41,7 @@ class p073_7dgt
byte brightness;
boolean timesep;
};
p073_7dgt *Plugin_073_7dgt = NULL;
p073_7dgt *Plugin_073_7dgt;
//---------------------------------------------------
uint8_t p073_showbuffer[8];
@@ -236,7 +236,6 @@ boolean Plugin_073(byte function, struct EventStruct *event, String& string)
break;
}
}
success = true;
} else if (tmpString.equalsIgnoreCase(F("7dt"))) {
if (Plugin_073_7dgt->output != 0)
break;
@@ -292,7 +291,6 @@ boolean Plugin_073(byte function, struct EventStruct *event, String& string)
break;
}
}
success = true;
} else {
bool p073_validcmd = false;
bool p073_displayon;
@@ -319,7 +317,6 @@ boolean Plugin_073(byte function, struct EventStruct *event, String& string)
}
}
if (p073_validcmd) {
success = true;
switch (Plugin_073_7dgt->type)
{
case 0:
@@ -334,6 +331,7 @@ boolean Plugin_073(byte function, struct EventStruct *event, String& string)
}
}
}
success = true;
break;
}
+265
View File
@@ -0,0 +1,265 @@
//#######################################################################################################
//######################## Plugin 074 TSL2591 I2C Lux/IR Sensor #########################################
//#######################################################################################################
//
// by: https://github.com/krikk
// this plugin is based on the adafruit library
// written based on version 1.0.2 from https://github.com/adafruit/Adafruit_TSL2591_Library
// does need Adafruit Sensors Library
// added lux calculation improvement https://github.com/adafruit/Adafruit_TSL2591_Library/issues/14
// added fix for issue https://github.com/adafruit/Adafruit_TSL2591_Library/issues/17
#ifdef PLUGIN_BUILD_TESTING
#define PLUGIN_074
#define PLUGIN_ID_074 74
#define PLUGIN_NAME_074 "Light/Lux - TSL2591 [TESTING]"
#define PLUGIN_VALUENAME1_074 "Lux"
#define PLUGIN_VALUENAME2_074 "Full"
#define PLUGIN_VALUENAME3_074 "Visible"
#define PLUGIN_VALUENAME4_074 "IR"
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"
#ifndef CONFIG
#define CONFIG(n) (Settings.TaskDevicePluginConfig[event->TaskIndex][n])
#endif
Adafruit_TSL2591 tsl;
boolean TSL2591_initialized = false;
boolean Plugin_074(byte function, struct EventStruct *event, String& string)
{
boolean success = false;
switch (function)
{
case PLUGIN_DEVICE_ADD:
{
Device[++deviceCount].Number = PLUGIN_ID_074;
Device[deviceCount].Type = DEVICE_TYPE_I2C;
Device[deviceCount].Ports = 0;
Device[deviceCount].VType = SENSOR_TYPE_QUAD;
Device[deviceCount].PullUpOption = false;
Device[deviceCount].InverseLogicOption = false;
Device[deviceCount].FormulaOption = true;
Device[deviceCount].ValueCount = 4;
Device[deviceCount].SendDataOption = true;
Device[deviceCount].TimerOption = true;
Device[deviceCount].TimerOptional = false;
Device[deviceCount].GlobalSyncOption = true;
break;
}
case PLUGIN_GET_DEVICENAME:
{
string = F(PLUGIN_NAME_074);
break;
}
case PLUGIN_GET_DEVICEVALUENAMES:
{
strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[0], PSTR(PLUGIN_VALUENAME1_074));
strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[1], PSTR(PLUGIN_VALUENAME2_074));
strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[2], PSTR(PLUGIN_VALUENAME3_074));
strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[3], PSTR(PLUGIN_VALUENAME4_074));
break;
}
case PLUGIN_WEBFORM_LOAD:
{
int optionValues[1] = { TSL2591_ADDR };
addFormSelectorI2C(string, F("plugin_074_i2c_addr"), 1, optionValues, TSL2591_ADDR); //Only for display I2C address
// tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS); // shortest integration time (bright light)
// tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
// tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS); // longest integration time (dim light)
String optionsMode[6] = { F("100ms"), F("200ms"), F("300ms"), F("400ms"), F("500ms"), F("600ms") };
addFormSelector(string, F("Integration Time"), F("plugin_074_itime"), 6, optionsMode, NULL, CONFIG(1));
// TSL2591_GAIN_LOW = 0x00, // low gain (1x)
// TSL2591_GAIN_MED = 0x10, // medium gain (25x)
// TSL2591_GAIN_HIGH = 0x20, // medium gain (428x)
// TSL2591_GAIN_MAX = 0x30, // max gain (9876x)
String optionsGain[4] = {
F("low gain (1x)"),
F("medium gain (25x)"),
F("medium gain (428x)"),
F("max gain (9876x)") };
addFormSelector(string, F("Value Mapping"), F("plugin_074_gain"), 4, optionsGain, NULL, CONFIG(2));
success = true;
break;
}
case PLUGIN_WEBFORM_SAVE:
{
//CONFIG(0) = getFormItemInt(F("plugin_074_i2c_addr"));
CONFIG(1) = getFormItemInt(F("plugin_074_itime"));
CONFIG(2) = getFormItemInt(F("plugin_074_gain"));
success = true;
break;
}
case PLUGIN_INIT:
{
tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)
if (tsl.begin())
{
String log = F("TSL2591: Address: 0x");
log += String(TSL2591_ADDR,HEX);
// Changing the integration time gives you a longer time over which to sense light
// longer timelines are slower, but are good in very low light situtations!
switch (CONFIG(1))
{
default:
case 0:
{
tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS);
break;
}
case 1:
{
tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
break;
}
case 2:
{
tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
break;
}
case 3:
{
tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
break;
}
case 4:
{
tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
break;
}
case 5:
{
tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS);
break;
}
}
log += F(": Integration Time: ");
log += String((tsl.getTiming() + 1) * 100, DEC);
log += F(" ms");
// You can change the gain on the fly, to adapt to brighter/dimmer light situations
switch (CONFIG(2))
{
default:
case 0:
{
tsl.setGain(TSL2591_GAIN_LOW); // 1x gain (bright light)
break;
}
case 1:
{
tsl.setGain(TSL2591_GAIN_MED); // 25x gain
break;
}
case 2:
{
tsl.setGain(TSL2591_GAIN_HIGH); // 428x gain
break;
}
case 3:
{
tsl.setGain(TSL2591_GAIN_MAX); // 9876x gain
break;
}
}
/* Display the gain and integration time for reference sake */
log += (F(" Gain: "));
tsl2591Gain_t gain = tsl.getGain();
switch(gain)
{
case TSL2591_GAIN_LOW:
log += F("1x (Low)");
break;
case TSL2591_GAIN_MED:
log += F("25x (Medium)");
break;
case TSL2591_GAIN_HIGH:
log += F("428x (High)");
break;
case TSL2591_GAIN_MAX:
log += F("9876x (Max)");
break;
}
TSL2591_initialized = true;
addLog(LOG_LEVEL_INFO,log);
}
else
{
TSL2591_initialized = false;
addLog(LOG_LEVEL_ERROR,F("TSL2591: No sensor found ... check your wiring?"));
}
success = true;
break;
}
case PLUGIN_READ:
{
if (TSL2591_initialized)
{
// Simple data read example. Just read the infrared, fullspecrtrum diode
// or 'visible' (difference between the two) channels.
// This can take 100-600 milliseconds! Uncomment whichever of the following you want to read
float lux, full, visible, ir;
visible = tsl.getLuminosity(TSL2591_VISIBLE);
ir = tsl.getLuminosity(TSL2591_INFRARED);
full = tsl.getLuminosity(TSL2591_FULLSPECTRUM);
lux = tsl.calculateLuxf(full, ir); // get LUX
UserVar[event->BaseVarIndex + 0] = lux;
UserVar[event->BaseVarIndex + 1] = full;
UserVar[event->BaseVarIndex + 2] = visible;
UserVar[event->BaseVarIndex + 3] = ir;
String log = F("TSL2591: Lux: ");
log += String(lux);
log += F(" Full: ");
log += String(full);
log += F(" Visible: ");
log += String(visible);
log += F(" IR: ");
log += String(ir);
addLog(LOG_LEVEL_INFO,log);
}
else {
addLog(LOG_LEVEL_ERROR,F("TSL2591: Sensor not initialized!?"));
}
}
}
return success;
}
#endif
+2 -12
View File
@@ -133,7 +133,6 @@ void CPluginInit(void)
#endif
CPluginCall(CPLUGIN_PROTOCOL_ADD, 0);
CPluginCall(CPLUGIN_INIT, 0);
}
byte CPluginCall(byte Function, struct EventStruct *event)
@@ -149,18 +148,9 @@ byte CPluginCall(byte Function, struct EventStruct *event)
// Unconditional calls to all plugins
case CPLUGIN_PROTOCOL_ADD:
for (x = 0; x < CPLUGIN_MAX; x++)
if (CPlugin_id[x] != 0)
if (CPlugin_id[x] != 0){
checkRAM(F("CPluginCallADD"),x);
CPlugin_ptr[x](Function, event, dummyString);
return true;
break;
// calls to active plugins
case CPLUGIN_INIT:
case CPLUGIN_UDP_IN:
for (byte x=0; x < CONTROLLER_MAX; x++)
if (Settings.Protocol[x] != 0 && Settings.ControllerEnabled[x]) {
event->ProtocolIndex = getProtocolIndex(Settings.Protocol[x]);
CPlugin_ptr[event->ProtocolIndex](Function, event, dummyString);
}
return true;
break;
+7 -1
View File
@@ -1073,6 +1073,7 @@ byte PluginCall(byte Function, struct EventStruct *event, String& str)
{
// Unconditional calls to all plugins
case PLUGIN_DEVICE_ADD:
case PLUGIN_UNCONDITIONAL_POLL:
for (x = 0; x < PLUGIN_MAX; x++)
if (Plugin_id[x] != 0)
Plugin_ptr[x](Function, event, str);
@@ -1081,6 +1082,7 @@ byte PluginCall(byte Function, struct EventStruct *event, String& str)
// Call to all plugins. Return at first match
case PLUGIN_WRITE:
case PLUGIN_REQUEST:
for (x = 0; x < PLUGIN_MAX; x++)
if (Plugin_id[x] != 0)
if (Plugin_ptr[x](Function, event, str))
@@ -1104,8 +1106,10 @@ byte PluginCall(byte Function, struct EventStruct *event, String& str)
TempEvent.BaseVarIndex = y * VARS_PER_TASK;
//TempEvent.idx = Settings.TaskDeviceID[y]; todo check
TempEvent.sensorType = Device[DeviceIndex].VType;
if (Plugin_ptr[x](Function, event, str))
if (Plugin_ptr[x](Function, event, str)){
checkRAM(F("PluginCallUDP"),x);
return true;
}
}
}
}
@@ -1140,6 +1144,7 @@ byte PluginCall(byte Function, struct EventStruct *event, String& str)
{
if (Plugin_id[x] == Settings.TaskDeviceNumber[y])
{
checkRAM(F("PluginCall_s"),x);
Plugin_ptr[x](Function, &TempEvent, str);
}
}
@@ -1167,6 +1172,7 @@ byte PluginCall(byte Function, struct EventStruct *event, String& str)
if ((Plugin_id[x] != 0 ) && (Plugin_id[x] == Settings.TaskDeviceNumber[event->TaskIndex]))
{
event->BaseVarIndex = event->TaskIndex * VARS_PER_TASK;
checkRAM(F("PluginCall_init"),x);
return Plugin_ptr[x](Function, event, str);
}
}