Compare commits

...
292 Commits
Author SHA1 Message Date
ESPEasy release bot f59f25ee40 automaticly updated release notes for v2.0-20180510 2018-05-10 04:00:27 +02:00
Gijs NoorlanderandGitHub 14030ec15b Merge pull request #1395 from letscontrolit/revert-1389-patch-1
Revert "Update _P045_MPU6050.ino"
2018-05-09 23:42:50 +02:00
Gijs NoorlanderandGitHub 1fd6179408 Revert "Update _P045_MPU6050.ino" 2018-05-09 23:40:27 +02:00
Gijs NoorlanderandGitHub 22424fb03b Merge pull request #1389 from maartenpaauw/patch-1
Update _P045_MPU6050.ino
2018-05-09 23:33:26 +02:00
Maarten PaauwandGitHub 97cd06440e Update _P045_MPU6050.ino
Fix debug code (commented out code).
2018-05-08 23:14:08 +02:00
ESPEasy release bot 8346e39ac9 automaticly updated release notes for v2.0-20180322 2018-03-22 04:00:24 +01:00
TD-er 22371649a4 [WiFi] Take much more time for initial WiFi connect during setup
Accesspoint is still active, so it may take a lot more time to make the initial connection
2018-03-22 01:05:56 +01:00
Gijs NoorlanderandGitHub 8cbd9a0822 Merge pull request #1148 from TD-er/merge/mega_to_v2.0_0321
Merge/mega to v2.0 0321
2018-03-22 00:24:59 +01:00
TD-er 93f9d11738 [Memory] parseTemplate did not check if markers were found
"Free Mem" reported this function to be using quite a lot of memory.
Maybe that was related to parsing texts without matching ']' or '#'
Just added some checks to see if they were found.
2018-03-22 00:24:17 +01:00
TD-er cf3e0a3f0a [wifi] Make more robust checks and increase timeout
See #1145
2018-03-22 00:12:04 +01:00
s0170071andTD-er ccfd14dbd3 Serial WD crash 2018-03-22 00:11:48 +01:00
Bartlomiej ZimonandTD-er 3034738ad4 - P048 fetch params only when needed 2018-03-22 00:11:30 +01:00
TD-er 178d1c46a2 - P035 move strings to flash 2018-03-22 00:11:21 +01:00
Bartlomiej ZimonandTD-er cdfd1d986e - P023 fix command interpretation 2018-03-22 00:10:55 +01:00
Bartlomiej ZimonandTD-er 4b7aa53692 - P012 fix command interpretation 2018-03-22 00:10:50 +01:00
ESPEasy release bot cc02fa4481 automaticly updated release notes for v2.0-20180321 2018-03-21 04:00:21 +01:00
Gijs NoorlanderandGitHub ab3a406706 [merge issue] Forgotten #endif in merge 2018-03-20 23:46:43 +01:00
Unknown 3edfdbf5f7 [wifi] Setup with factory settings could not complete 2018-03-20 23:27:39 +01:00
ESPEasy release bot 1220c565c8 automaticly updated release notes for v2.0-20180320 2018-03-20 04:00:23 +01:00
Unknown f0987dab41 [issue #1097] WiFi connect with deepsleep enabled trigger watchdog reset
Did not allow for enough time to do background tasks while waiting for wifi connect with DeepSleep enabled.
2018-03-20 00:29:24 +01:00
Unknown af3e353181 Revert "Merge pull request #1116 from TD-er/feature/allow_own_defaults"
This reverts commit 8ccbdcadf0.
2018-03-19 22:51:23 +01:00
es-kaandUnknown c711d6ea51 Fix wiring description for SN75176 transceiver 2018-03-19 22:50:31 +01:00
ESPEasy release bot 1f084c51cc automaticly updated release notes for v2.0-20180319 2018-03-19 04:00:24 +01:00
Gijs NoorlanderandGitHub 85e8d98da8 Merge pull request #1121 from TD-er/merge/fixes_20180318_to_v2.0
Merge/fixes 20180318 to v2.0
2018-03-19 01:01:42 +01:00
Unknown 6d52a7e03a [merge] MIssing #endif due to merging. 2018-03-19 00:51:05 +01:00
Gijs Noorlander fa513b52f9 Merge pull request #1118 from TD-er/bugfix/mqtt_publish_after_deep_sleep
[issue #1097] MQTT publish after deep sleep
2018-03-19 00:46:03 +01:00
Unknown f98401524f Merge pull request #1116 from TD-er/feature/allow_own_defaults
[issue #1007] Allow user specific data in separate file
2018-03-19 00:45:52 +01:00
Unknown 4090b4f23c Merge pull request #1113 from TD-er/feature/reduce_impact_wifi_disconnect
[Relaxed WiFi] Perform WiFi initialization in steps
2018-03-19 00:42:58 +01:00
Gijs Noorlander b89c00008d Merge pull request #1114 from TD-er/feature/wifi_details_json
[JSON] Add uint name (#1099) and WiFi information (PR #1113)
2018-03-19 00:39:43 +01:00
Gijs Noorlander d57a617138 Merge pull request #1112 from uzi18/fix-p073
Fix p073 - #1111
2018-03-19 00:39:32 +01:00
Gijs Noorlander cefe6b4b7c Changed so that running all tasks immediately with deep sleep enabled… (#1110)
Changed so that running all tasks immediately with deep sleep enabled only happens on first iteration after wake up
2018-03-19 00:38:30 +01:00
Gijs Noorlander 2432740b41 - add encoder write command #1086 (#1103)
- add encoder write command #1086
2018-03-19 00:35:09 +01:00
Gijs Noorlander 44a934651c Add download button for current rule set (#1102)
Add download button for current rule set
2018-03-19 00:34:52 +01:00
ESPEasy release bot 6787bc8c0e automaticly updated release notes for v2.0-20180316 2018-03-16 04:00:23 +01:00
Gijs NoorlanderandGitHub cf644b45b1 Merge pull request #1095 from TD-er/merge/PR_1092_1093_1094
Merge/pr 1092 1093 1094
2018-03-16 00:43:16 +01:00
Unknown e6fe1c63a9 [issue #951] Changed System#Initialized => System#Wake
Changed System#Initialized  => System#Wake
New event name makes more sense and Initialized may be used later to indicate all needed connections, etc. are ready.
2018-03-16 00:38:00 +01:00
Unknown df978036f0 [issue #993] variable in MQTT subscribe topic
As [noted](https://github.com/letscontrolit/ESPEasy/issues/993#issuecomment-373140135) by @kluszcyn
2018-03-16 00:37:54 +01:00
Unknown 7cb375833d [issue #1057] AM PM display issue
X:XX PM (for hours 1...9)
X:XX AM (for hours 1...9)
XX:XX PM (for hours 10...12)
XX:XX AM (for hours 10...12)

Added for H:MM (without seconds) notations:
- `%systm_hm%`
-`%systm_hm_am%`
2018-03-16 00:37:45 +01:00
Gijs NoorlanderandGitHub 3218ea9839 Merge pull request #1091 from TD-er/merge/fixes_1073_1079_1081 into v2.0
Merge/fixes 1073 1079 1081 into v2.0
2018-03-15 23:05:06 +01:00
Gijs Noorlander eca8901fca Fixed multi instance problem on SHT3x #433 (#1081)
Fixed multi instance problem on SHT3x #433
2018-03-15 23:02:04 +01:00
Gijs Noorlander 6635eafe91 [issue #1066] Fix Webserver handle_control (#1079)
[issue #1066] Fix Webserver handle_control
2018-03-15 23:01:52 +01:00
Gijs Noorlander fe4d1f952f MCP3221 allow values for calibration (#1073)
MCP3221 allow values for calibration
2018-03-15 23:01:39 +01:00
Gijs NoorlanderandGitHub 4475a225cc Merge pull request #1090 from TD-er/merge/split_globals_v2.0
Merge/split globals v2.0
2018-03-15 22:46:46 +01:00
Unknown 2aece1c143 [v2.0 split globals] Base split on v2.0 version of ESPEasy.ino 2018-03-15 22:23:59 +01:00
Bartlomiej ZimonandUnknown 70df225e7e Merge branch 'mega' of github.com:letscontrolit/ESPEasy into mega
# Conflicts:
#	src/ESPEasy.ino
2018-03-15 22:05:36 +01:00
Unknown 19af52a3ef - move all structs from ESPEasy.ino into header file
- add some fix for headers
- add const to rtttl notes array
2018-03-15 22:05:22 +01:00
Gijs NoorlanderandGitHub 3d396575ff Merge pull request #1088 from TD-er/merge/rules_fix__and_globalsync_toV2.0
Merge/rules fix  and globalsync to v2.0
2018-03-15 21:52:41 +01:00
mvdbroandUnknown 826deaac89 Rules fix 2018-03-14 21:28:24 +01:00
mvdbroandUnknown cce621cff8 #893, part 2 receiving 2018-03-14 21:28:15 +01:00
mvdbroandUnknown 57eb38dbd0 Custom controller GUI option 2018-03-14 21:28:08 +01:00
mvdbroandUnknown fd2451bb07 #893 part1, send messages 2018-03-14 21:27:50 +01:00
ESPEasy release bot cc0b3dac26 automaticly updated release notes for v2.0-20180313 2018-03-13 04:00:23 +01:00
Gijs NoorlanderandGitHub d3434eb4d2 Merge/fix rules trailing spaces (#1065) #1074
Merge/fix rules trailing spaces (#1065)
2018-03-12 23:18:22 +01:00
Bartlomiej ZimonandUnknown bd2665041f - remove double trimm() 2018-03-12 23:15:48 +01:00
Bartlomiej ZimonandUnknown 1fd429a029 - fix for #1065 2018-03-12 23:15:40 +01:00
ESPEasy release bot e4d4463eab automaticly updated release notes for v2.0-20180312 2018-03-12 04:00:19 +01:00
Gijs NoorlanderandGitHub b29f56c6f4 Merge pull request #1063 from TD-er/merge/rule_engine_fix
Rule Engine minor fix and added dev debugging
2018-03-12 00:55:49 +01:00
Unknown 779514481d Rule Engine minor fix and added dev debugging 2018-03-12 00:52:30 +01:00
Gijs NoorlanderandGitHub 0a752dd26f Merge pull request #1062 from TD-er/merge/issue_1039
Merge/issue 1039
2018-03-12 00:44:02 +01:00
Unknown 8112e0e67a [webserver] Improve chunked transfer
Do chunked transfer using full buffer on all data sent to the streaming webserver.
2018-03-12 00:42:08 +01:00
Unknown 89a9f842fd [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:41:44 +01:00
ESPEasy release bot 92932fddb2 automaticly updated release notes for v2.0-20180311 2018-03-11 04:00:19 +01:00
Unknown 89581fd0fb [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:59:51 +01:00
Unknown 3f84a961ad [DNS lookup] Controllers sometimes try to connect to 0.0.0.0
See issue #824
2018-03-11 01:38:50 +01:00
Unknown 96bfaa27f5 [OLED] fix drawProgressBar
See this PR: https://github.com/ThingPulse/esp8266-oled-ssd1306/pull/178
2018-03-10 23:04:03 +01:00
Unknown bcca0514dd [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 23:03:55 +01:00
Gijs NoorlanderandGitHub bb9f8fc809 Merge pull request #1046 from TD-er/merge/mega_to_v2.0
Merge/mega to v2.0
2018-03-10 22:03:14 +01:00
Unknown 4d9504bce0 [P073] Remove tm1637_bitDelay()
Not used anymore
2018-03-10 22:01:27 +01:00
Unknown ff3a769033 Update P07 Plugin
added suppor for other version of TM1637 modules (4dgt+colon, 4dgt+dots,6dgt+dots)
2018-03-10 22:01:20 +01:00
Unknown e3de56a7a8 [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 22:01:04 +01:00
Gijs NoorlanderandGitHub 2682b0bd2f [v2.0] Merge/rules process speed improvements (#1045)
[v2.0] Merge/rules process speed improvements
2018-03-10 21:55:25 +01:00
Unknown 5097157a09 Final ruleset speed-up
It's now down from 100 mSec to 19 mSec for 1 fully loaded non matching ruleset.
2018-03-10 21:41:13 +01:00
Unknown 02ea957894 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 21:39:51 +01:00
mvdbroandUnknown c2b0d76595 Rule Engine, stop waisting time on non matching rules 2018-03-10 21:38:01 +01:00
Unknown 91b7cbe075 Improve flash read performance 2018-03-10 21:37:47 +01:00
ESPEasy release bot 64b38df187 automaticly updated release notes for v2.0-20180310 2018-03-10 04:00:20 +01:00
Gijs NoorlanderandGitHub 76f6dfdc59 Merge Mega -> v2.0: conversions & delay wifi init (#1037)
Merge Mega -> v2.0: conversions  & delay wifi init
2018-03-09 23:20:47 +01:00
Unknown 3a6f7acd15 [Conversions] Use more decimals in conversions and add AM/PM for time.
See comments on #1015
2018-03-09 23:19:19 +01:00
Unknown d65b126f84 Move plugin init before WiFi init
As suggested at PR #1032 by @M0ebiu5
2018-03-09 23:18:10 +01:00
ESPEasy release bot 8299e38b24 automaticly updated release notes for v2.0-20180309 2018-03-09 04:00:22 +01:00
Gijs NoorlanderandGitHub 67a28a7f97 Add other simple conversions like Celsius to Fahrenheit (#1033)
[issue #1015] Add other simple conversions like Celsius to Fahrenheit…
2018-03-09 00:35:06 +01:00
Unknown 18b8e61d32 [issue #1015] Add other simple conversions like Celsius to Fahrenheit, etc.
- %c_w_dir%   -  getBearing 
- %c_c2f%   -    String(CelsiusToFahrenheit) 
- %c_ms2Bft%   - String(m_secToBeaufort) 
- %c_cm2imp%   - centimeterToImperialLength 
- %c_mm2imp%   - millimeterToImperialLength 
- %c_m2day%   -  String(minutesToDay) 
- %c_m2dh%   -   minutesToDayHour 
- %c_m2dhm%   -  minutesToDayHourMinute 
- %c_s2dhms%   - secondsToDayHourMinuteSecond
2018-03-09 00:31:27 +01:00
Unknown 5821b0709c [issue #1015] Add other simple conversions like Celsius to Fahrenheit, etc.
- %c_w_dir%   -  getBearing 
- %c_c2f%   -    String(CelsiusToFahrenheit) 
- %c_ms2Bft%   - String(m_secToBeaufort) 
- %c_cm2imp%   - centimeterToImperialLength 
- %c_mm2imp%   - millimeterToImperialLength 
- %c_m2day%   -  String(minutesToDay) 
- %c_m2dh%   -   minutesToDayHour 
- %c_m2dhm%   -  minutesToDayHourMinute 
- %c_s2dhms%   - secondsToDayHourMinuteSecond
2018-03-09 00:29:52 +01:00
Unknown ec783fe03b [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 23:00:33 +01:00
ESPEasy release bot 9122565431 automaticly updated release notes for v2.0-20180307 2018-03-07 04:00:21 +01:00
Unknown 64a0f79e02 [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:56:23 +01:00
Gijs Noorlander 92e4a8da9b [CSS] Quick fix for smaller displays (#1026)
[CSS] Quick fix for smaller displays by @doxikus
2018-03-06 21:53:54 +01:00
ESPEasy release bot 40e2d7ec8e automaticly updated release notes for v2.0-20180306 2018-03-06 04:00:17 +01:00
Gijs NoorlanderandDatuX 7318e87965 Fixes P073 plugin for latest TM1637 based 7 segments displays modules (#996) (#1022)
Fixes P073 plugin for latest TM1637 based 7 segments displays modules
2018-03-05 20:17:51 +01:00
ESPEasy release bot 9c3a28439f automaticly updated release notes for v2.0-20180305 2018-03-05 04:00:20 +01:00
Gijs NoorlanderandGitHub 127627a22c [issue #1003 ] Add conversion of wind direction to string (#1014)
[issue #1003 ] Add conversion of wind direction to string
2018-03-05 00:37:44 +01:00
Gijs NoorlanderandGitHub e59401e24f [issue #528] Set DOUT flash mode for all 1M builds (#1013)
[issue #528] Set DOUT flash mode for all 1M builds
2018-03-05 00:36:39 +01:00
Unknown 769f76d3dc [issue #1003 ] Add conversion of wind direction to string
Also made some clean-up of calls to string replacements.
Improved the lookup function to determine the wind direction (was 11.25 degree off)
Now it is also possible to add simple standard conversions like Celcius-Fahrenheit, m/s - Beaufort, etc.
2018-03-05 00:28:32 +01:00
Unknown 4eb7cf0859 [issue #528] Set DOUT flash mode for all 1M builds
See [this elaborate post on the different flash modes](https://www.esp32.com/viewtopic.php?t=1250)
2018-03-04 22:30:13 +01:00
Edwin Eefting a464f638ad automaticly updated release notes for v2.0-20180304b 2018-03-04 18:20:49 +01:00
Edwin Eefting a5cfe1beec dont build in silent mode to prevent travis timeouts 2018-03-04 18:14:27 +01:00
ESPEasy release bot a8fcb420e7 automaticly updated release notes for v2.0-20180304 2018-03-04 04:00:19 +01:00
Gijs NoorlanderandGitHub 3ed6564063 [issue #892 ] Only use sensor type when really needed (#1004)
[issue #892 ] Only use sensor type when really needed
2018-03-04 00:45:52 +01:00
Unknown 5f575c0224 [issue #892 ] Only use sensor type when really needed
Only the Domoticz controllers need the sensor type. The rest just needs the number of sensor values.
2018-03-04 00:37:18 +01:00
Gijs NoorlanderandGitHub 34c1ba158f [issue #993] Add %unit% variable in MQTT subscribe topic (PR #1002)
[issue #993] Add %unit% variable in MQTT subscribe topic
2018-03-03 22:40:18 +01:00
Unknown 04ca424085 [issue #993] Add %unit% variable in MQTT subscribe topic 2018-03-03 22:39:09 +01:00
Gijs Noorlander 7a8f476e05 _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:30:22 +01:00
Gijs Noorlander e42ab85f4b 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:38:13 +01:00
ESPEasy release bot 3094cb5260 automaticly updated release notes for v2.0-20180303 2018-03-03 04:00:19 +01:00
Gijs NoorlanderandGitHub 0e67480f46 Merge pull request #995 from TD-er/bugfix/mqtt_proper_case
Bugfix/mqtt proper case
2018-03-03 02:19:49 +01:00
Unknown c32f2cc89d Add AND/OR to rules & prevent unwanted case changes in strings (#994) 2018-03-03 02:09:41 +01:00
Unknown ad489f0db2 [Issue #827] MQTT not using proper case for %sysname% variable.
Some functions and plugins could change strings to lowercase.
Added some check also to help debugging.
2018-03-03 02:03:20 +01:00
Gijs NoorlanderandGitHub d9267fa9c2 Add Task device type to json by @s0170071 (#991)
Add Task device type to json by @s0170071
2018-03-02 22:40:20 +01:00
Unknown e82fb37870 Add Task device type to json by @s0170071
Taken from his branch, he forgot to PR.
2018-03-02 22:30:55 +01:00
Gijs NoorlanderandGitHub 26f00dcdec [issue #293] json output nan values not double quoted (#990)
[issue #293] json output nan values not double quoted
2018-03-02 22:03:07 +01:00
Unknown b2bb1d039b [issue #293] json output nan values not double quoted
Generate valid JSON output
2018-03-02 21:49:06 +01:00
Unknown c58e975b7e revert json to non-chunking #988 from s0170071/mega
revert json to non-chunking
2018-03-02 20:40:13 +01:00
ESPEasy release bot 08312cbcb7 automaticly updated release notes for v2.0-20180302 2018-03-02 04:00:21 +01:00
Gijs NoorlanderandGitHub 953a53bb9a Merge pull request #985 from TD-er/bugfix/json_content-length
backport of "rule wildcard" + improve formatting of Webserver's StreamingBuffer
2018-03-02 01:58:53 +01:00
Unknown e9fac7926f [webserver] Layout of code to improve readability
Indentation was completely off, which made it hard to read.
Also added member json_format, which is set at start of stream.
2018-03-02 01:53:40 +01:00
mvdbroandUnknown 810a0b2aa9 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 23:41:42 +01:00
Gijs NoorlanderandGitHub 5d9137d1d2 Merge pull request #976 from TD-er/bugfix/P053_PMSx003DustPlugin
[issue #914] _P053_PMSx003 Dust Sensor looses sync
2018-03-01 23:07:38 +01:00
Gijs Noorlander 8de49cd38e Merge pull request #983 from kahvm/mega
Added support for degree sign on LCD1602/2004
2018-03-01 22:42:58 +01:00
Gijs NoorlanderandGitHub fe1c44f6b3 Merge pull request #980 from uzi18/formatout
Format output marge from mega to v2.0
2018-03-01 22:34:08 +01:00
Gijs NoorlanderandGitHub e39d588530 Merge pull request #975 from TD-er/merge/important_fixes_from_mega
Merge/important fixes from mega
2018-03-01 22:31:36 +01:00
Unknown 4ca318f5a6 [Build error fix] Must-keep-focus-when-pressing-buttons...
Quickly commit + merge is never a good idea when some visitors arrive...
Fixed now.
2018-03-01 20:08:51 +01:00
Bartłomiej ZimońandBartlomiej Zimon 37a24933f5 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-28 23:06:01 +01:00
Bartlomiej Zimon a6b447600f Merge branch 'v2.0' of github.com:letscontrolit/ESPEasy into v2.0 2018-02-28 22:43:52 +01:00
Unknown 5fbb900e5b [issue #914] Check first 2 bytes of packet 2018-02-28 22:39:34 +01:00
ESPEasy release bot aa5dee01fb automaticly updated release notes for v2.0-20180228 2018-02-28 04:00:20 +01:00
Unknown 1a44ed6578 [issue #914] _P053_PMSx003 Dust Sensor looses sync
- Use peek instead of read, to make sure a complete packet is in the buffer.
- Flush buffer after processing a packet.
- Increased software serial buffer to the size of 3 packets.
- Peek (+ read garbage) 10 times per second to get the buffer in sync to start with start byte of packet.
- Decent delete + clean up of software serial allocation when changing settings (prevent memory leak)
- Move log String allocation to inside scope of function, not permanent allocated.
- Split into separate functions to make it better readable.
2018-02-28 02:11:33 +01:00
Bartłomiej ZimońandUnknown e86667e37e 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-28 00:00:37 +01:00
s0170071andUnknown 0db1f78421 Add Factory Reset button to web interface (#954) 2018-02-27 23:59:31 +01:00
Bartłomiej ZimońandUnknown 780c34846e 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-27 23:58:50 +01:00
Gijs NoorlanderandDatuX a938bc78c1 [issue #968] Use template parser for OLED commands (#974)
N.B. Now even task values can be used in commands, next to special characters.
2018-02-27 23:43:18 +01:00
Gijs NoorlanderandDatuX d2c7743197 [issue #966] Add %sysweekday% and %sysweekday_s% (#973)
- %sysweekday%  number of the day (Sunday = 1)
- %sysweekday_s%  3 letter String of the weekday (Sun, Mon, Tue, ...)
2018-02-27 23:43:01 +01:00
ESPEasy release bot d35a50be17 automaticly updated release notes for v2.0-20180227 2018-02-27 04:00:22 +01:00
Edwin Eefting 04de145dbb [test suite] changes from mega to 2.0 2018-02-27 00:41:27 +01:00
Edwin Eefting 21840d0b26 [test suite] changes from mega to 2.0 2018-02-27 00:41:21 +01:00
Gijs NoorlanderandDatuX 555ccbe229 [BuildError] StreamingBuffer code cleanup + fix order member initialize (#961)
The order in which the members are defined should also be the order in which they will be initialized.

Also applied #958
2018-02-26 22:52:27 +01:00
ESPEasy release bot b5e4994392 automaticly updated release notes for v2.0-20180226 2018-02-26 04:00:21 +01:00
s0170071andUnknown 51ede17d2a Update WebServer.ino 2018-02-25 21:15:33 +01:00
s0170071andUnknown 97ee69b371 V20 Webserver@LowMemory 2018-02-25 21:15:24 +01:00
Unknown f77ce9c8f7 [ping lib] Added ping library
It was linked as a dependency in PlatformIO.ini, but apparently will add complexity to Arduino IDE users.
2018-02-25 21:14:07 +01:00
Gijs NoorlanderandDatuX 848f43b704 [2k Webserver] Proper initialisation of StreamingBuffer members. (#941)
Was reported in Travis as build error.
2018-02-25 17:17:47 +01:00
Edwin Eefting 3a5ef5da81 device page doesnt need next/previous page buttons anymore 2018-02-25 17:12:45 +01:00
Gijs NoorlanderandDatuX 54628bfca9 [timeouts] Improve response when hosts are not reachable (#939)
See #922 and #847

Problem with DNS resolve is that it is quite slow when resulting in a failure and it tends to keep the ESP occupied and make it unresponsive.

Changed the way it is connecting to a controller.
Not sure if http requests are still OK, maybe we should make an exception for those when selected to use DNS.
2018-02-25 14:15:56 +01:00
Gijs NoorlanderandDatuX aed566b6db [v2.0] Use ESPeasySoftwareSerial (#936)
This one has virtual destructor and will use less memory.
See issue #930.
2018-02-25 14:12:33 +01:00
Gijs NoorlanderandDatuX 504ea0c813 [v2.0 merge] 2kwebserver_merge_to_mega #929 (#934)
The v2.0 branch merge of the 2k webserver PR.
As test build, please try [these builds](https://www.dropbox.com/s/ky6ldixh6wgzd8k/2k_webserver_build_v2.0_20180221.rar?dl=0)
2018-02-25 14:12:11 +01:00
Gijs NoorlanderandDatuX 4ca5ef3f72 [v2.0] Added Vcc-binaries to deploy process #933 (#935)
PR for the V2.0 branch to add the VCC binaries to the deploy process.
2018-02-25 14:11:34 +01:00
Bartłomiej ZimońandDatuX 67c8477a61 provide System@Sleep event (#875) (#931)
- 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-25 14:01:40 +01:00
Gijs NoorlanderandDatuX 3d07466904 [MQTT] LWT "Connected" message doesn't have the retained flag (#925)
See comments of [Superpiffer](https://github.com/letscontrolit/ESPEasy/commit/a93a078c0b8ae4090c22717eacc8bc8ba92ad780#commitcomment-27718045)
2018-02-25 13:10:58 +01:00
Bartłomiej ZimońandBartlomiej Zimon 03ee569510 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-23 19:57:01 +01:00
ESPEasy release bot af519748a6 automaticly updated release notes for v2.0-20180221 2018-02-21 04:00:20 +01:00
Edwin Eefting 2bece45712 apply PUYA patch to all available frameworks 2018-02-21 02:08:06 +01:00
Gijs NoorlanderandDatuX 10c73a001a [issue #899 ] Backport of DHT22 implementation on Mega (#913)
It has quite some changes, but according to [litrinhos](https://github.com/letscontrolit/ESPEasy/issues/899#issuecomment-366940174) it works, instead of the v2.0 implementation.
2018-02-21 01:26:08 +01:00
ESPEasy release bot 233ca2bf43 automaticly updated release notes for v2.0-20180220 2018-02-20 04:00:19 +01:00
Edwin Eefting edeea02f71 SENSOR_TYPE_TEMP_BARO changed, was probably implemented incorrectly before 2018-02-20 01:56:40 +01:00
Gijs NoorlanderandDatuX b31b1d913f [issue #893] Fix globalSync not working when no controllers active (#896)
* [issue #893] Fix globalSync not working when no controllers active

See #893 and [this topic on the forum](https://www.letscontrolit.com/forum/viewtopic.php?p=24851#p24851)

* [issue #893] Global Sync call when no other controllers active
2018-02-20 00:52:43 +01:00
Gijs NoorlanderandDatuX fa3d4af8cb [Cleanup] Move String manipulating functions to single file (#895)
Makes it easier to re-use functions and improve them.
2018-02-20 00:52:18 +01:00
Gijs NoorlanderandDatuX 29320aab90 [isue #877] Add VCC enable firmware file to release list (#894)
* [isue #877] Add VCC enable firmware file to release list

Added one for the testing build.
Not sure if we should add one for every build, since these flags will lead to an explosion of release versions. 
But at least we will test builds with FEATURE_ADC_VCC define enabled more often.

* Add define FEATURE_ADC_VCC to the PUYA build

Since it is so hard to make a puya version on your own.
2018-02-20 00:50:56 +01:00
Gijs NoorlanderandGitHub 3bc8609611 Merge pull request #905 from TD-er/bugfix/DHTinit_sequence_wrong
[issue #899] DHT22 readings not received
2018-02-20 00:16:51 +01:00
Gijs NoorlanderandGitHub c43d6b3769 Merge pull request #904 from TD-er/feature/log_event_name
[Event Log] Add event name to event processing time log
2018-02-20 00:16:19 +01:00
Gijs NoorlanderandGitHub e9e2ea32ed Merge pull request #903 from TD-er/bugfix/OpenHAB_MQTT_topic_parser_fix
[issue #847] Fix last letter of command is cut in OpenHAB MQTT
2018-02-20 00:15:51 +01:00
Unknown 24b7d1f438 [issue #899] DHT22 readings not received
Applied fix as suggested here: https://github.com/adafruit/DHT-sensor-library/issues/48
2018-02-20 00:04:13 +01:00
Unknown 4febf08501 [Event Log] Add event name to event processing time log
As suggested on the forum by [Methusalem](https://www.letscontrolit.com/forum/viewtopic.php?p=24887#p24887)
2018-02-19 23:31:19 +01:00
Unknown 7f4eae19f4 [issue #847] Fix last letter of command is cut in OpenHAB MQTT
Thanks [jivkopavlovski](https://github.com/letscontrolit/ESPEasy/commit/f23d9fa3d3def506e1401c2208c8a19a1d5d1da2#commitcomment-27660279) for pointing this out (and testing ofcourse)
2018-02-19 22:57:57 +01:00
ESPEasy release bot c13952d04c automaticly updated release notes for v2.0-20180219 2018-02-19 04:00:19 +01:00
Gijs NoorlanderandDatuX e51f7683a5 [issue #890] Split overlap for both Domoticz controllers to helper (#891)
* [issue #890] Split overlap for both Domoticz controllers to helper

Both Domoticz controllers had quite some overlap in code.
And where they differ, one of them was faulty and/or already fixed.

Now this overlap is split into a Domoticz helper file to keep code duplication to a minimum.

* [issue #890] Fix some wierd data corruption

Do not store references in a Json object, but just the string :)

* [Domoticz] Add WiFi strength and battery info
2018-02-18 13:18:23 +01:00
Gijs NoorlanderandDatuX 1ad6fd6ea0 [issue #885] MAC address as system variable (#887)
%mac% will be replaced by the MAC-address of the ESP board.
%mac_int% will show the integer representation of the last 24 bits (MAC address without the OUI part) for use in rules.
2018-02-18 13:16:42 +01:00
ESPEasy release bot d2ec15a4bf automaticly updated release notes for v2.0-20180218 2018-02-18 04:00:11 +01:00
Gijs NoorlanderandDatuX f23d9fa3d3 [issue #847 ] OpenHAB MQTT rewrite topic parser (#886)
* [issue #847 ] OpenHAB MQTT rewrite topic parser

When OpenHAB MQTT controller was selected, the web interface becomes unresponsive when the controller tab was selected.
Also the ESP almost freezes when MQTT messages were sent.

This is an attempt to make them work faster.
Also a lot of string manipulation, copies and resizes are now no longer needed and the received values are checked to be valid int or float before used.

* signed unsigned warning
2018-02-17 13:18:52 +01:00
ESPEasy release bot 3cea522ec4 automaticly updated release notes for v2.0-20180217 2018-02-17 04:00:18 +01:00
Gijs NoorlanderandDatuX a93a078c0b [issue #869] Added 'LWT' to last will topic and improved CPU load (#883)
* [issue #869] Added 'LWT' to last will topic and improved CPU load

See #869 for discussion on Last Will Topic.
Also changed the way it tried to reconnect to make it return a lot faster when connection is not (yet) possible and call the PubSubClient::loop() at a much slower pace to reduce CPU usage. (See #847)
This higher CPU load was probably introduced when fixing #683.

* [MQTT] Fix error reporting success status with longer payloads

Applied PR https://github.com/knolleary/pubsubclient/pull/360/files

* made MQTT_CALLBACK_SIGNATURE for esp32 functional

Applied PR https://github.com/knolleary/pubsubclient/pull/336
2018-02-16 21:32:53 +01:00
Gijs NoorlanderandDatuX 0e0e7be95a [OLED Framed] ESP Easy logo (#876) 2018-02-16 21:29:44 +01:00
Gijs NoorlanderandDatuX ce02c9e039 [issue #853] Favicon.ico (#874)
* [issue #853] Favicon.ico

Added a very small favicon.ico of the ESPeasy logo. (1150 Bytes, 16x16)

* [Favicon] Added instructions to change icon.

In the comments. Just use 'xxd' from the (Linux) commandline.
2018-02-16 21:27:58 +01:00
Gijs NoorlanderandDatuX 1e9dc1d14c [issue 866] Try to stop logging to serial when serial is not read. (#868)
First attempt, not clear yet how to detect it.
See #866

Also preparation for future improvement on logging. (to detect whether there is some logging active so Strings may not have to be prepared.
2018-02-16 21:26:18 +01:00
ESPEasy release bot 9a6f7360da automaticly updated release notes for v2.0-20180214 2018-02-14 04:00:21 +01:00
Edwin Eefting d835ef679c updated deploy script for PUYA 2018-02-14 03:23:50 +01:00
Edwin Eefting 9144e7901b travis build fix for PUYA 2018-02-14 03:10:30 +01:00
Edwin Eefting 858ce397c3 workaround for PUYA flash chips with write issues #650 2018-02-14 03:01:42 +01:00
Gijs NoorlanderandDatuX 78c9ff70be [v2.0] Blynk controller (#865)
* update Blynk controller

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

* 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

* [v2.0] Blynk controller
2018-02-14 00:23:59 +01:00
ESPEasy release bot 40eb3e7ceb automaticly updated release notes for v2.0-20180213 2018-02-13 04:00:20 +01:00
Gijs NoorlanderandDatuX 88320d25fc [MQTT] Allow for background tests while waiting for wifi (#860)
Recent changes in 'early exit' when not connected, triggered lots of retry events.
Added some function to allow to wait for WiFi and in the meantime do some background tasks.
2018-02-13 03:01:15 +01:00
Gijs NoorlanderandDatuX d49197a621 [issue #825] Change labels and password form for Thingspeak controller (#849)
See #825

Added option for controllers to change their display string on some controller fields in the web interface.
When password field label is non-default it also implies to use a visible textfield instead of a password field.
2018-02-13 01:17:04 +01:00
Gijs NoorlanderandDatuX 9abdd097c9 Formatting user vars (re-do of PR#482) + enabled check OpenHabMQTT (#851)
Re-implementation of PR #482 which was done on Mega branch.
Just to keep merges simple between branches. (and improve readabilit)

Also added a simple check to C005 (OpenHAB MQTT) on receiving messages. (see #847 )
2018-02-13 01:07:24 +01:00
Gijs NoorlanderandDatuX f8849cb601 Bugfix/oled framed less memory (#859)
* [OLED] Move font to oled lib dir

It is specific for use wth that library.

* [OLED framed] Stop reading from flash constantly and live update WiFi

See #857
The OLED Framed plugin was reading from spiffs all of the time (on every display update)
Now the data is only read from SPIFFS when needed.
Also made the WiFi strength indicator update every second (only when changed) to be able to see changes in WiFi status much easier.
2018-02-13 01:05:36 +01:00
soifandDatuX b293e8fee0 P012 - Fix/handle lines exceeding LCD width + allow to clear line b4 print (#852)
* Update Library LiquidCrystal_I2C to the latest version

* Fix LCD command (when message is longer than columns) that get split into the wrong lines - issue #603

* Added a "LCD command mode" parameter to handle how exceeding message would be treated, and if the line should be first padded with space.
2018-02-13 01:03:24 +01:00
Gijs NoorlanderandDatuX 11b1c8505a [v2.0] Fix compile errors on ESP32 (#848)
Cherry pick from Mega branch to avoid future merge conflicts.
2018-02-13 00:39:12 +01:00
Gijs NoorlanderandDatuX 9cb3ceed83 [P001 Switch] Fix a mixup in previous fix for switch (#845)
It was causing issues when people upgraded from previous builds.
Leaving it would cause high CPU loads, instable wifi, and incorrect set switch type when upgrading from older builds.

Only thing is when people were using it as a dimmer and used one of the builds in the last few weeks.
Then it will be used as a 'switch', not a dimmer. Change and set and all is fine again.
2018-02-13 00:38:51 +01:00
Gijs NoorlanderandDatuX 2ac1df9482 [issue #839] Add command support for setting contrast for OLED Framed (#841)
* [issue #839] Add command support for setting contrast for OLED Framed

See #839

* [issue #839] Should not use 0 as off value, since that is default

With 0 as "off", the display would be off when not set.
Changed it to 1, which is not a value that can be set other than with the commands
2018-02-13 00:38:01 +01:00
Gijs NoorlanderandDatuX d4e5742b1c [#804] Degree symbol for non-framed OLED display (#835) 2018-02-13 00:24:32 +01:00
ESPEasy release bot f815564dc7 automaticly updated release notes for v2.0-20180212 2018-02-12 04:00:22 +01:00
Gijs NoorlanderandDatuX 2b51a4d7c4 [Issue #831] Use DOUT flash mode (#834)
Set DOUT flash mode in the firmware image.
2018-02-12 02:24:16 +01:00
soifandDatuX 01d0723424 Add Device Name in /json page (#815)
* Add Name in /json page

* Json dev friendly (updatable) syntax

* Reorder Json field
2018-02-12 02:11:01 +01:00
ESPEasy release bot aec539be43 automaticly updated release notes for v2.0-20180209 2018-02-09 04:00:26 +01:00
wdonkerandDatuX e49f31121c Add trigger for rulesprocessing (#826)
* Update _C002.ino

Trigger rulesprocessing om MQTT receive message

* Replace direct call by createRuleEvents

Change to createRuleEvents
2018-02-08 19:33:32 +01:00
ESPEasy release bot bd874c4a13 automaticly updated release notes for v2.0-20180206 2018-02-06 05:00:21 +01:00
Gijs NoorlanderandDatuX 6b8ea6c15b [issue #727] Proper user interface to set DST rules (#823)
See #727
And it only took 4 bytes extra storage :)

When initialized with an invalid setting for DST, (like fresh after flashing), it will use the CEST/CET setting.
2018-02-06 00:42:45 +01:00
Gijs NoorlanderandDatuX a62dd5ce8f [issue #817] Added mail header to SMTP (#820)
* [issue #817] Added mail header to SMTP

N.B. use only mail address (no name, no '<>' etc) as sender.

* [SMTP] Add user/pass to send email.

* [issue #817] Added user + passwd authentication to SMTP notifications

Tested with smtp2go.com (non TLS mail proxy)
It is now possible to add username + passwd when sending mail.
If both left empty, authentication will not be used.
2018-02-05 23:59:24 +01:00
Gijs NoorlanderandDatuX 92889b6cf1 Backport OLED framed from mega + support special characters (#818)
* [OLED framed] Backport of OLED lib upgrade from Mega to v2.0

Lots of issues with older lib and the newer version in the Mega branch appeared to be very stable.

* [OLED framed] Use less string allocations

And a first attempt to display the Euro sign. (does not yet work)

* [Special Char] Allow to use special characters

For some special characters, it is often hard to find them and/or use them in URL or JSON streams.
For a subset of supported special characters, a short notation and HTML equivalent is added.
These can be used anywhere.

* [OLED lib] Fixed memory leak

Man library did some allocs without free.
Also unneeded allocs.

* Applied pull requests from esp8266-oled-ssd1306:
https://github.com/squix78/esp8266-oled-ssd1306/pull/169
https://github.com/squix78/esp8266-oled-ssd1306/pull/157
https://github.com/squix78/esp8266-oled-ssd1306/pull/144

And applied the suggestions from issues:
https://github.com/squix78/esp8266-oled-ssd1306/issues/170
https://github.com/squix78/esp8266-oled-ssd1306/issues/161

* [OLED] Support multiple display resolutions

Applied PR from esp8266-oled-ssd1306:
https://github.com/squix78/esp8266-oled-ssd1306/pull/133

* [OLED] Better Brightness / Contrast control

Suggestions taken from this issue:
https://github.com/squix78/esp8266-oled-ssd1306/issues/134

* [OLED] Set contrast to High by default, when no choice was made

Sounds like a valid choice, based on the findings in issue #821

* Compiler error on comments

As suggested here: https://github.com/TD-er/ESPEasy/pull/3/files
2018-02-05 23:56:17 +01:00
soifandDatuX b5479575eb All Advanced Settings as 'DEFAULT_' Defines (#813)
* Implements all Advanced Settings as "DEFAULT_" defines

* Organise and comment "DEFAULT_" defines
2018-02-05 23:50:48 +01:00
ESPEasy release bot 6fead68f34 automaticly updated release notes for v2.0-20180203 2018-02-03 05:00:20 +01:00
GrovkillenandGitHub 2f26cd13bc Update README.md 2018-02-02 12:52:12 +01:00
ESPEasy release bot 3a9ef290e8 automaticly updated release notes for v2.0-20180202 2018-02-02 05:00:23 +01:00
soifandDatuX 36a9bdae72 Json page also Shows Git Build (#808)
* remove un-needed spaces in JSON (save some memory?)

* Add the Git Build string in the /json page
2018-02-02 03:11:02 +01:00
soifandDatuX ebfa0a45a6 Custom define file (#807)
* Allows to use a Custom.h file to change defaults setting without changing the repo file

* Custom.h example
2018-02-02 02:40:56 +01:00
soifandDatuX c2e70360c4 Allows to define the IP address when in AP Mode (#806) 2018-02-02 02:39:47 +01:00
DatuXandGitHub 712a5e80d0 Update README.md 2018-02-02 01:23:42 +01:00
DatuXandGitHub a44069ae26 Update README.md 2018-02-02 01:17:06 +01:00
soifandDatuX bb88225cab Fix Syslog : include Hosname instead of Unit Number - now RFC3164 compliant (#805) 2018-02-02 00:40:04 +01:00
Gijs NoorlanderandDatuX 3089b288b2 [issue #739] Reconnect MQTT when Unit Name has changed. (#803)
See #739
When %sysname% has changed, force a reconnect of the MQTT client.

Also made the client ID guaranteed unique by using the MAC address.
2018-02-02 00:38:28 +01:00
soifandDatuX 6abea46eb5 Fixes invalid '/json' page output format : DateTimeString is now correctly quoted (#802) 2018-02-02 00:37:01 +01:00
Gijs NoorlanderandDatuX ffa73aee59 [v2.0] Resource friendly string replacement (#798)
As part of #698 and also since these system variable replacement may grow.
Some replacement strings may need some work to create and such effort is wasted if the matching string does not occur.
To improve this and still remain readable, I added a simple macro to check first and then create the strings only when needed.
Some strings are already present, so these do not use the macro since searching first and then look again to replace will take more effort.
2018-02-02 00:34:02 +01:00
Gijs NoorlanderandDatuX f4b7e97997 [issue #794] Add longpulse_ms command (#796)
See #794
2018-02-02 00:30:49 +01:00
ESPEasy release bot 66d0de684a automaticly updated release notes for v2.0-20180130 2018-01-30 05:00:23 +01:00
Gijs NoorlanderandDatuX 23d5709957 [Log] Clean up of log routines and more intuitive log level input (#788)
As part of #781, #747 and the general cleanup issue #698.
2018-01-30 01:50:24 +01:00
Gijs NoorlanderandDatuX 16eb08afa0 [#784] Add %rssi% as system variable (#786)
* [#784] Add %rssi% as system variable

See #784

* [#787] Add %unit% and %ssid% system variable

See #787
Unit is the unit number of the ESP device.
SSID is the name of the WiFi accesspoint the ESP device is connected with.
2018-01-29 22:51:26 +01:00
Gijs NoorlanderandDatuX b9b7ceccb6 Bugfix/issue 740 allow mqtt as controller 2 3 (#785)
* [issue #740] Allow MQTT controller to be on any controller

See #740

Still there is an issue when >1 MQTT controller is selected and enabled.
Currently only one MQTT controller may be active.

* [issue #740] Add warning when >1 MQTT controller is active

Add a warning to the web interface when >1 MQTT controller is active.
See #740
2018-01-29 18:12:47 +01:00
Edwin Eefting 5c4bf52b66 forgot to commit last framed oled display fix 2018-01-29 17:30:01 +01:00
ESPEasy release bot 34369d268e automaticly updated release notes for v2.0-20180126 2018-01-26 05:00:22 +01:00
Gijs NoorlanderandDatuX 3292051bae Update _C007.ino (#774) (#776)
This change allows to send the switch state to Emoncms, previously it was ignored
2018-01-25 22:07:07 +01:00
Gijs NoorlanderandDatuX d492347f31 [V2.0] Allow IRremoteESP8266 to be built with core 2.4.0 (#773)
* [V2.0] Allow IRremoteESP8266 to be build with core 2.4.0

A partial cherrypick of #772, to make merging easier.
Just some simple patches on the use of min() and max() in the library to allow it to compile using the 2.4.0 core lib. Actual use of this core lib is still prohibited by the check in ESPEasy.ino.

* [core 2.3.0] Force PlatformIO to use the 2.3.0 core libs

This update forces the PlatformIO environment to load the 1.5.0 version of espressif8266@1.5.0, which uses Core 2.3.0
2018-01-25 22:04:54 +01:00
Gijs NoorlanderandDatuX 56f9bc9c3a [issue #759] Disable Senseair ABC due to firmware issues (#771)
See #759

Just commented the Set ABC functionality. People may compile it for themselves, but be aware of possible consequences.
2018-01-25 15:48:21 +01:00
ESPEasy release bot 82cea3db2e automaticly updated release notes for v2.0-20180124 2018-01-24 05:00:20 +01:00
Edwin Eefting 2f32799b67 fix #718. also update display on save and removed graphical boot logo to conserve space. also fixes #713. (web interface will be non repsonsive during scrolling now, but there is no easy fix for that) 2018-01-24 02:58:25 +01:00
Gijs NoorlanderandDatuX fd5da94f9c [issue #758] P029 MQTT helper does not log anymore (#764)
See #758
2018-01-23 23:54:34 +01:00
ESPEasy release bot 0694fcc5fb automaticly updated release notes for v2.0-20180123 2018-01-23 05:00:20 +01:00
Edwin Eefting bc91939757 request mainpage when checking if reboot is complete 2018-01-23 04:57:20 +01:00
Edwin Eefting eb743f95cf added easy reboot warning and function to work around several issues 2018-01-23 04:49:16 +01:00
Edwin Eefting ed4cdc3d90 clear custom task and controller settings when selecting a different device or protocol. replaces #762 . fixes #721 2018-01-23 02:37:02 +01:00
Edwin Eefting 8e72ace3b5 test suite: espcli can now do stuff for all configured nodes 2018-01-23 00:50:00 +01:00
Gijs NoorlanderandDatuX 2527cbe097 Central function for system variable replacement (#757)
* Central function for system variable replacement

Related to:
- #698 => Not complete
- #709 => fixed
- #751 => fixed

Redesign of PR #485 (in mega branch)

One note: no sensor values can be used in controllers. Is this what we want, or should we call parseTemplate everywhere parseSystemVariables is being used?
Also not all controllers apparently allow system variables. Is this also correct?

* [issue 757] Add %lcltime% to display date + time

As requested by @PsychoAndi at PR #757

* [issue 757] Add local time to JSON output

As suggested by @PsychoAndi
2018-01-22 23:38:14 +01:00
Edwin Eefting 5b0e9d934c test suite: now possible to run all tests at once. fixes 2018-01-22 23:32:46 +01:00
ESPEasy release bot 19429e8507 automaticly updated release notes for v2.0-20180122 2018-01-22 05:00:19 +01:00
Gijs NoorlanderandDatuX 0c637da19f [#732] Only process P029 MQTT helper when enabled (#743)
See #732
Also did some small optimizations for when no Domoticz MQTT controller enabled and/or task enabled.
2018-01-21 17:10:08 +01:00
Gijs NoorlanderandDatuX 48f168da9d [issue #745] Set IPaddress to 0.0.0.0 when read from empty string (#754)
Also str2ip now uses IPAddress.fromString()
2018-01-21 17:08:15 +01:00
ESPEasy release bot 3357eb287c automaticly updated release notes for v2.0-20180121 2018-01-21 05:00:13 +01:00
Edwin Eefting 5da1c54b70 test suite: fixes. testing boot gpio states 2018-01-21 04:28:12 +01:00
Edwin Eefting c5bbdb401a test suite: lots of refactoring and fixing 2018-01-21 03:23:22 +01:00
Edwin Eefting f69b84d24b test suite: fixed issues, started working on nodo 2018-01-21 01:53:22 +01:00
Edwin Eefting 1250e09fef cleaned up nodo logging. fixed domotics SENSOR_TYPE_WIND inconsistency 2018-01-21 01:52:36 +01:00
Edwin Eefting fbf22ba7af test suite: generelized controller testing in test005 2018-01-20 21:49:24 +01:00
ESPEasy release bot 5c26d50227 automaticly updated release notes for v2.0-20180120 2018-01-20 05:00:12 +01:00
Edwin Eefting 47be037be9 Merge branch 'v2.0' of github.com:letscontrolit/ESPEasy into v2.0 2018-01-19 05:45:10 +01:00
Edwin Eefting bc4f7d390c test suite: started on testcase to test all sensor types via the dummy plugin 2018-01-19 05:44:57 +01:00
Edwin Eefting 9fe64834f9 added QUAD to c002. fixed getBearing and SENSOR_TYPE_WIND. 2018-01-19 05:43:50 +01:00
ESPEasy release bot 4d943c2386 automaticly updated release notes for v2.0-20180119 2018-01-19 05:00:18 +01:00
Edwin Eefting 51b76682cf test suite: added dht22 2018-01-19 02:35:38 +01:00
Edwin Eefting 400ee82686 test suite domoticz mqtt + found few fixmes 2018-01-19 01:28:14 +01:00
ESPEasy release bot 485f97bdc2 automaticly updated release notes for v2.0-20180118 2018-01-18 05:00:19 +01:00
Edwin Eefting e6e3c1ddee refactoring test suite controller stuff 2018-01-18 03:37:25 +01:00
Gijs NoorlanderandDatuX 017aad051e [issue 728] Proper reconnect for MQTT controllers (#737)
See #728
Also looked into the very strange configuration settings lookup for MQTT settings. The way it was, the settings for the first MQTT controller were used even when the actual MQTT controller was inactive or using different settings.

Now the controller selected in the the plugin is being used and when no plugin setting is available (and also for P037 MQTT import) the first active MQTT controller will be used.
2018-01-18 01:04:55 +01:00
Gijs NoorlanderandDatuX 8a30659015 [issue 733] Fix for negative values on MQTT import (#735)
See #733.
The '-' was parsed, but not copied to the tmp char array to be converted.
2018-01-18 00:44:08 +01:00
ESPEasy release bot b61c638f0a automaticly updated release notes for v2.0-20180116 2018-01-16 05:00:21 +01:00
Edwin Eefting 09e5d6abcd now supports powercycle to test for bugs like #719 2018-01-16 04:15:48 +01:00
Edwin Eefting 2aafbb57a8 made test resumable and importable 2018-01-16 03:41:29 +01:00
Edwin Eefting 744f22112b Merge branch 'v2.0' of github.com:letscontrolit/ESPEasy into v2.0 2018-01-15 23:04:48 +01:00
Edwin Eefting b38edfb672 fixed custom build path 2018-01-15 23:04:40 +01:00
Gijs NoorlanderandDatuX a73875a2e2 [AutoDST] Added Auto DST (Bugfix/v2.0 issue569) (#726)
* [Time] Moved time related code to separate file

* [AutoDST] Added Auto DST

Preliminary support for Auto DST, as requested in #569
Also did a little refactorin of time related code, with #698 in mind.
All time related code is split into a few files based on its function.

The currently selected DST will start on Last Sunday March 2am and end on Last Sunday October 3am.
This is the most frequently used DST, according to https://en.wikipedia.org/wiki/Daylight_saving_time_by_country

To change it, currently the code has to be changed in the function applyTimeZone(). Several examples are given right below that function.
Problem is where to store the information of the timezone, how to use it in the web interface and how convenient it is to set by hand.
The UTC offset in minutes still has to be entered and whether or not DST should be enabled.
2018-01-15 21:51:15 +01:00
ESPEasy release bot f7ea185f80 automaticly updated release notes for v2.0-20180113 2018-01-13 05:00:20 +01:00
Edwin Eefting 11a94aae25 testsuite: working on generic http/mqtt controller emulatior receiving 2018-01-13 03:21:09 +01:00
Edwin Eefting 57c6fbbaab ESPEasy v2.0 only supports compiling under arduino core 2.3.0 to prevent issues like #705 when people use Arduino IDE to compile with arduino core 2.4.0 2018-01-13 02:53:15 +01:00
Edwin Eefting 7a9726063d dont make same release twice 2018-01-12 02:02:43 +01:00
Edwin Eefting d6680b604f dont make same release twice 2018-01-12 02:02:27 +01:00
Edwin Eefting 25ef1803e0 release bot fixes 2018-01-12 01:59:03 +01:00
Edwin Eefting 2bc72151bc automaticly updated release notes for v2.0-20180112 2018-01-12 01:56:54 +01:00
Edwin Eefting 93ceae3bef fixed releasebot issues with multiple branches 2018-01-12 01:56:34 +01:00
Edwin Eefting 2bf31a1985 testsuite requirements 2018-01-12 01:40:20 +01:00
Gijs NoorlanderandDatuX 5796f50439 [v2.0 #470] Do not send invalid values to a controller (#701)
Prevent sending of invalid values (NaN, inf) to any controller.
Simple test is to output any plugin value with formula set to "%value%/0" and try to send it to any controller.
Is a fix for #470 and #693
2018-01-12 01:06:36 +01:00
Edwin Eefting 36415d424e first http domoticz test works 2018-01-12 01:04:47 +01:00
Edwin Eefting 76be5dd8d9 added http server emulation and domotics http to testsuite 2018-01-12 00:50:45 +01:00
Gijs NoorlanderandDatuX 6e760cd25b [Issue 699] Incorrect shown device name (#700)
And some improvements in readability and performance of webserver.
2018-01-11 22:45:50 +01:00
ESPEasy release bot 69c03cafb9 automaticly updated release notes for v2.0-20180111 2018-01-11 05:00:18 +01:00
Edwin Eefting b20d4a10ba working on http mocker for test suite 2018-01-11 03:26:30 +01:00
Edwin Eefting 548bf8b867 added frame oled test 2018-01-11 01:49:57 +01:00
Edwin Eefting 0b68e16894 test suite fixes 2018-01-11 01:35:32 +01:00
Edwin Eefting 33e46addbb analysed some code and added comments 2018-01-11 00:54:19 +01:00
Edwin Eefting 628ff925b7 Merge branch 'v2.0' of github.com:letscontrolit/ESPEasy into v2.0 2018-01-11 00:48:44 +01:00
Edwin Eefting 6fddf25a39 copied test-stuff from mega to v2.0 to do some testing 2018-01-11 00:48:24 +01:00
Gijs NoorlanderandDatuX 84e58285af [v2.0_kamstrup] Plugin configuration does not load (#697)
Could not change the device settings. The PLUGIN_WEBFORM_LOAD case was not handled.
2018-01-10 23:22:40 +01:00
Edwin Eefting 3a8323faab Merge branch 'v2.0' of github.com:letscontrolit/ESPEasy into v2.0 2018-01-10 19:19:57 +01:00
Edwin Eefting fe1944922c changed devicecombobox handling to save a lot of memory on device page. fixes #654 #676 and could be triggered by #683 in some cases. 2018-01-10 19:19:48 +01:00
Gijs NoorlanderandDatuX 7ea0c767fa [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 19:15:35 +01:00
Edwin Eefting ec18e5c530 updates version numbering documentation 2018-01-10 16:34:58 +01:00
ESPEasy release bot 885781850b automaticly updated release notes for v2.0-20180110 2018-01-10 16:14:23 +01:00
ESPEasy release bot 443b46f383 added releasebot to v2.0 branch 2018-01-10 16:13:24 +01:00
Edwin Eefting 801a591282 fixed plugin id of "Communication - Kamstrup Multical 401". (accidental octal notation) 2018-01-10 15:09:10 +01:00
Gijs NoorlanderandDatuX 740efcb763 [Adafruit MPR121] Change deprecated name setThreshholds to setThresholds (#685)
See #684
2018-01-10 02:45:50 +01:00
Edwin Eefting 67fa39f4ed moved mqtt stuff outside of backgroundtasks(). fixes #683 in my test scenario 2018-01-10 02:25:01 +01:00
Edwin Eefting 7a8bb7c0e0 actually ignore MQTT messages that are too big. 2018-01-10 01:56:05 +01:00
Gijs NoorlanderandDatuX 961b1106aa 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
2018-01-10 00:49:47 +01:00
Gijs NoorlanderandDatuX 9dc549e62d [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.
2018-01-10 00:35:27 +01:00
chunter1andDatuX c1a11ff6e4 ABC calibration feature added (#606) 2018-01-05 17:11:29 +01:00
Gijs NoorlanderandDatuX 151bf18cc6 [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.
2018-01-05 17:03:44 +01:00
Edwin Eefting e4d68b9d0e readme updates 2018-01-03 01:32:02 +01:00
Edwin Eefting b5e093bc80 changed readme title 2018-01-03 01:06:48 +01:00
148 changed files with 16957 additions and 7735 deletions
+5 -4
View File
@@ -1,9 +1,10 @@
# cmd: "cd {PROJECT_PATH}; platformio"
cmd: "platformio"
name: "Build with error highlighting (dev_4096)"
name: "Build with error highlighting (dev_ESP8266_4096)"
args:
- run --environment dev_4096
sh: true,
cwd: .
- run --environment dev_ESP8266_4096
sh: true
cwd: "{PROJECT_PATH}"
# env:
# VARIABLE1: "VALUE1"
# VARIABLE2: "VALUE2"
+1
View File
@@ -4,3 +4,4 @@
.piolibdeps
lib/readme.txt
src/Custom.h
+6 -1
View File
@@ -27,7 +27,12 @@ install:
script:
- 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 -s
- PLATFORMIO_BUILD_FLAGS="-D CONTINUOUS_INTEGRATION" platformio run
# patch platformio core libs for PUYA bug (https://github.com/letscontrolit/ESPEasy/issues/650)
- cd patches; ./check_puya_patch; cd ..
- PLATFORMIO_BUILD_FLAGS="-D CONTINUOUS_INTEGRATION" platformio run -s --environment dev_ESP8266PUYA_1024
before_deploy:
- ./before_deploy
+20 -15
View File
@@ -1,18 +1,23 @@
# ESPEasy (mega branch)
# ESPEasy (v2.0 stable branch)
Build status: [![Build Status](https://travis-ci.org/letscontrolit/ESPEasy.svg?branch=v2.0)](https://travis-ci.org/letscontrolit/ESPEasy)
Introduction and wiki: https://www.letscontrolit.com/wiki/index.php/ESPEasy#Introduction
This is the development branch for the next upcoming release (2.0.0). This is also known as ESPEasyMega.
**v2.0**
:warning:This is the stable branch for the next upcoming ESPeasy release (2.0.0).: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.
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.0-devX: these are the current development releases. use these if you want bleeding edge features, or if you want to help us testing and developing. new release every month.
* v2.0.0-betaX: as soon as we think its stable/complete enough for real testing, we will start numbering beta's.
* v2.0.0-rcX: release candidates (probably stable)
* 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.
## Firmware binary releases
@@ -21,19 +26,19 @@ Binary development releases are here: https://github.com/letscontrolit/ESPEasy/r
Depending on your needs, we release different types of files.
For version 2.0.0-dev13 and higer:
This uses version v2.0-20181001 as an example.
Firmware name | Hardware | Included plugins |
----------------------------------------------|-------------------------|-----------------------------|
ESPEasy_v2.0.0-dev13_normal_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable |
ESPEasy_v2.0.0-dev13_test_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable + Test |
ESPEasy_v2.0.0-dev13_dev_ESP8266_1024.bin | ESP8266 with 1Mb flash | Stable + Test + Development |
ESPEasy_v2.0.0-dev13_normal_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable |
ESPEasy_v2.0.0-dev13_test_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable + Test |
ESPEasy_v2.0.0-dev13_dev_ESP8266_4096.bin | ESP8266 with 4Mb flash | Stable + Test + Development |
ESPEasy_v2.0.0-dev13_normal_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable |
ESPEasy_v2.0.0-dev13_test_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable + Test |
ESPEasy_v2.0.0-dev13_dev_ESP8285_1024.bin | ESP8285 with 1Mb flash | Stable + Test + Development |
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 |
## More info
+25 -14
View File
@@ -1,24 +1,32 @@
#!/bin/bash
VERSION=$(git describe)
echo "Creating release archives for $VERSION ..."
#binaries
#ESP_Easy_v[version]-[build type]-dev[dev number]-ESP[chip type]-[size].bin
#Naming convention:
# ESP_Easy_[github version]_[plugin set]_[chip type]_[flash memory].bin
#cp .pioenvs/mini_512/firmware.bin dist/"ESPEasy_$VERSION""_mini_512.bin"
cp .pioenvs/normal_ESP8266_1024/firmware.bin dist/"ESP_Easy_$VERSION""_normal_ESP8266_1024.bin"
cp .pioenvs/normal_ESP8266_4096/firmware.bin dist/"ESP_Easy_$VERSION""_normal_ESP8266_4096.bin"
cp .pioenvs/normal_ESP8285_1024/firmware.bin dist/"ESP_Easy_$VERSION""_normal_ESP8285_1024.bin"
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\
test_ESP8285_1024\
dev_ESP8266_1024\
dev_ESP8266_4096\
dev_ESP8285_1024\
dev_ESP8266PUYA_1024\
dev_ESP8266PUYA_1024_VCC;\
do
echo
echo "### Deploying environment $ENV for version $VERSION"
BIN=.pioenvs/$ENV/firmware.bin
cp $BIN dist/"ESP_Easy_$VERSION""_$ENV.bin"
done
cp .pioenvs/test_ESP8266_1024/firmware.bin dist/"ESP_Easy_$VERSION""_test_ESP8266_1024.bin"
cp .pioenvs/test_ESP8266_4096/firmware.bin dist/"ESP_Easy_$VERSION""_test_ESP8266_4096.bin"
cp .pioenvs/test_ESP8285_1024/firmware.bin dist/"ESP_Easy_$VERSION""_test_ESP8285_1024.bin"
cp .pioenvs/dev_ESP8266_1024/firmware.bin dist/"ESP_Easy_$VERSION""_dev_ESP8266_1024.bin"
cp .pioenvs/dev_ESP8266_4096/firmware.bin dist/"ESP_Easy_$VERSION""_dev_ESP8266_4096.bin"
cp .pioenvs/dev_ESP8285_1024/firmware.bin dist/"ESP_Easy_$VERSION""_dev_ESP8285_1024.bin"
#create a source structure that is the same as the original ESPEasy project (and works with the howto on the wiki)
rm -rf dist/Source 2>/dev/null
@@ -28,4 +36,7 @@ cp -r src dist/Source/
cp platformio.ini dist/Source/
cd dist
echo
echo "### Creating zip archive"
zip ../ESPEasy_$VERSION.zip -r .
+701
View File
@@ -1,3 +1,704 @@
-------------------------------------------------
Changes in release v2.0-20180510 (since v2.0-20180322)
-------------------------------------------------
Release date: Thu May 10 04:00:27 CEST 2018
Gijs Noorlander (1):
Revert "Update _P045_MPU6050.ino"
Maarten Paauw (1):
Update _P045_MPU6050.ino
-------------------------------------------------
Changes in release v2.0-20180322 (since v2.0-20180321)
-------------------------------------------------
Release date: Thu Mar 22 04:00:24 CET 2018
Bartlomiej Zimon (3):
- P012 fix command interpretation
- P023 fix command interpretation
- P048 fetch params only when needed
TD-er (4):
- P035 move strings to flash
[wifi] Make more robust checks and increase timeout
[Memory] parseTemplate did not check if markers were found
[WiFi] Take much more time for initial WiFi connect during setup
s0170071 (1):
Serial WD crash
-------------------------------------------------
Changes in release v2.0-20180321 (since v2.0-20180320)
-------------------------------------------------
Release date: Wed Mar 21 04:00:21 CET 2018
Gijs Noorlander (1):
[merge issue] Forgotten #endif in merge
Unknown (1):
[wifi] Setup with factory settings could not complete
-------------------------------------------------
Changes in release v2.0-20180320 (since v2.0-20180319)
-------------------------------------------------
Release date: Tue Mar 20 04:00:23 CET 2018
Unknown (2):
Revert "Merge pull request #1116 from TD-er/feature/allow_own_defaults"
[issue #1097] WiFi connect with deepsleep enabled trigger watchdog reset
es-ka (1):
Fix wiring description for SN75176 transceiver
-------------------------------------------------
Changes in release v2.0-20180319 (since v2.0-20180316)
-------------------------------------------------
Release date: Mon Mar 19 04:00:24 CET 2018
Gijs Noorlander (6):
Add download button for current rule set (#1102)
- add encoder write command #1086 (#1103)
Changed so that running all tasks immediately with deep sleep enabled… (#1110)
Merge pull request #1112 from uzi18/fix-p073
Merge pull request #1114 from TD-er/feature/wifi_details_json
Merge pull request #1118 from TD-er/bugfix/mqtt_publish_after_deep_sleep
Unknown (3):
Merge pull request #1113 from TD-er/feature/reduce_impact_wifi_disconnect
Merge pull request #1116 from TD-er/feature/allow_own_defaults
[merge] MIssing #endif due to merging.
-------------------------------------------------
Changes in release v2.0-20180316 (since v2.0-20180313)
-------------------------------------------------
Release date: Fri Mar 16 04:00:23 CET 2018
Bartlomiej Zimon (1):
Merge branch 'mega' of github.com:letscontrolit/ESPEasy into mega
Gijs Noorlander (3):
MCP3221 allow values for calibration (#1073)
[issue #1066] Fix Webserver handle_control (#1079)
Fixed multi instance problem on SHT3x #433 (#1081)
Unknown (5):
- move all structs from ESPEasy.ino into header file
[v2.0 split globals] Base split on v2.0 version of ESPEasy.ino
[issue #1057] AM PM display issue
[issue #993] variable in MQTT subscribe topic
[issue #951] Changed System#Initialized => System#Wake
mvdbro (4):
#893 part1, send messages
Custom controller GUI option
#893, part 2 receiving
Rules fix
-------------------------------------------------
Changes in release v2.0-20180313 (since v2.0-20180312)
-------------------------------------------------
Release date: Tue Mar 13 04:00:23 CET 2018
Bartlomiej Zimon (2):
- fix for #1065
- remove double trimm()
-------------------------------------------------
Changes in release v2.0-20180312 (since v2.0-20180311)
-------------------------------------------------
Release date: Mon Mar 12 04:00:19 CET 2018
Unknown (3):
[issue #1039 ] Change CSS to show topmost SSID on large screens
[webserver] Improve chunked transfer
Rule Engine minor fix and added dev debugging
-------------------------------------------------
Changes in release v2.0-20180311 (since v2.0-20180310)
-------------------------------------------------
Release date: Sun Mar 11 04:00:19 CET 2018
Unknown (10):
Improve flash read performance
Add read buffer to rule processing to speedup parsing
Final ruleset speed-up
[AM/PM] Am/Pm notation doesn't have '0' hours
Update P07 Plugin
[P073] Remove tm1637_bitDelay()
[deepsleep] Make sure the 'shortcut' of running all services when sleep enabled
[OLED] fix drawProgressBar
[DNS lookup] Controllers sometimes try to connect to 0.0.0.0
[issue #1039] Topmost SSID are covered on mobile Browser
mvdbro (1):
Rule Engine, stop waisting time on non matching rules
-------------------------------------------------
Changes in release v2.0-20180310 (since v2.0-20180309)
-------------------------------------------------
Release date: Sat Mar 10 04:00:20 CET 2018
Unknown (2):
Move plugin init before WiFi init
[Conversions] Use more decimals in conversions and add AM/PM for time.
-------------------------------------------------
Changes in release v2.0-20180309 (since v2.0-20180307)
-------------------------------------------------
Release date: Fri Mar 9 04:00:22 CET 2018
Unknown (3):
[Rule Events] Add a number of events to handle in rules and awake timer
[issue #1015] Add other simple conversions like Celsius to Fahrenheit, etc.
[issue #1015] Add other simple conversions like Celsius to Fahrenheit, etc.
-------------------------------------------------
Changes in release v2.0-20180307 (since v2.0-20180306)
-------------------------------------------------
Release date: Wed Mar 7 04:00:21 CET 2018
Gijs Noorlander (1):
[CSS] Quick fix for smaller displays (#1026)
Unknown (1):
[issue #1012] Removed Content-Length header + improved webserver speed
-------------------------------------------------
Changes in release v2.0-20180306 (since v2.0-20180305)
-------------------------------------------------
Release date: Tue Mar 6 04:00:17 CET 2018
Gijs Noorlander (1):
Fixes P073 plugin for latest TM1637 based 7 segments displays modules (#996) (#1022)
-------------------------------------------------
Changes in release v2.0-20180305 (since v2.0-20180304b)
-------------------------------------------------
Release date: Mon Mar 5 04:00:20 CET 2018
Unknown (2):
[issue #528] Set DOUT flash mode for all 1M builds
[issue #1003 ] Add conversion of wind direction to string
-------------------------------------------------
Changes in release v2.0-20180304b (since v2.0-20180304)
-------------------------------------------------
Release date: Sun Mar 4 18:20:49 CET 2018
Edwin Eefting (1):
dont build in silent mode to prevent travis timeouts
-------------------------------------------------
Changes in release v2.0-20180304 (since v2.0-20180303)
-------------------------------------------------
Release date: Sun Mar 4 04:00:19 CET 2018
Gijs Noorlander (2):
Merge pull request #1000 from uzi18/test3 (more comparisions in IF condition)
_P072_HDC1080 allow to send values to the controllers (#999)
Unknown (2):
[issue #993] Add %unit% variable in MQTT subscribe topic
[issue #892 ] Only use sensor type when really needed
-------------------------------------------------
Changes in release v2.0-20180303 (since v2.0-20180302)
-------------------------------------------------
Release date: Sat Mar 3 04:00:19 CET 2018
Unknown (5):
revert json to non-chunking #988 from s0170071/mega
[issue #293] json output nan values not double quoted
Add Task device type to json by @s0170071
[Issue #827] MQTT not using proper case for %sysname% variable.
Add AND/OR to rules & prevent unwanted case changes in strings (#994)
-------------------------------------------------
Changes in release v2.0-20180302 (since v2.0-20180228)
-------------------------------------------------
Release date: Fri Mar 2 04:00:21 CET 2018
Bartłomiej Zimoń (4):
provide System@Sleep event (#875)
add format #O to templates to show OFF/ON instead 0/1 (#949)
fix #964, add timeStringToSeconds and use it to compare time conditions (#965)
add format #O to templates to show OFF/ON instead 0/1 (#949)
Gijs Noorlander (1):
Merge pull request #983 from kahvm/mega
Unknown (4):
[issue #914] _P053_PMSx003 Dust Sensor looses sync
[issue #914] Check first 2 bytes of packet
[Build error fix] Must-keep-focus-when-pressing-buttons...
[webserver] Layout of code to improve readability
mvdbro (1):
Rule wildcard option on literal events
s0170071 (1):
Add Factory Reset button to web interface (#954)
-------------------------------------------------
Changes in release v2.0-20180228 (since v2.0-20180227)
-------------------------------------------------
Release date: Wed Feb 28 04:00:19 CET 2018
Gijs Noorlander (2):
[issue #966] Add %sysweekday% and %sysweekday_s% (#973)
[issue #968] Use template parser for OLED commands (#974)
-------------------------------------------------
Changes in release v2.0-20180227 (since v2.0-20180226)
-------------------------------------------------
Release date: Tue Feb 27 04:00:22 CET 2018
Edwin Eefting (2):
[test suite] changes from mega to 2.0
[test suite] changes from mega to 2.0
Gijs Noorlander (1):
[BuildError] StreamingBuffer code cleanup + fix order member initialize (#961)
-------------------------------------------------
Changes in release v2.0-20180226 (since v2.0-20180221)
-------------------------------------------------
Release date: Mon Feb 26 04:00:21 CET 2018
Bartłomiej Zimoń (1):
provide System@Sleep event (#875) (#931)
Edwin Eefting (1):
device page doesnt need next/previous page buttons anymore
Gijs Noorlander (6):
[MQTT] LWT "Connected" message doesn't have the retained flag (#925)
[v2.0] Added Vcc-binaries to deploy process #933 (#935)
[v2.0 merge] 2kwebserver_merge_to_mega #929 (#934)
[v2.0] Use ESPeasySoftwareSerial (#936)
[timeouts] Improve response when hosts are not reachable (#939)
[2k Webserver] Proper initialisation of StreamingBuffer members. (#941)
Unknown (1):
[ping lib] Added ping library
s0170071 (2):
V20 Webserver@LowMemory
Update WebServer.ino
-------------------------------------------------
Changes in release v2.0-20180221 (since v2.0-20180220)
-------------------------------------------------
Release date: Wed Feb 21 04:00:20 CET 2018
Edwin Eefting (1):
apply PUYA patch to all available frameworks
Gijs Noorlander (1):
[issue #899 ] Backport of DHT22 implementation on Mega (#913)
-------------------------------------------------
Changes in release v2.0-20180220 (since v2.0-20180219)
-------------------------------------------------
Release date: Tue Feb 20 04:00:19 CET 2018
Edwin Eefting (1):
SENSOR_TYPE_TEMP_BARO changed, was probably implemented incorrectly before
Gijs Noorlander (3):
[isue #877] Add VCC enable firmware file to release list (#894)
[Cleanup] Move String manipulating functions to single file (#895)
[issue #893] Fix globalSync not working when no controllers active (#896)
Unknown (3):
[issue #847] Fix last letter of command is cut in OpenHAB MQTT
[Event Log] Add event name to event processing time log
[issue #899] DHT22 readings not received
-------------------------------------------------
Changes in release v2.0-20180219 (since v2.0-20180218)
-------------------------------------------------
Release date: Mon Feb 19 04:00:19 CET 2018
Gijs Noorlander (2):
[issue #885] MAC address as system variable (#887)
[issue #890] Split overlap for both Domoticz controllers to helper (#891)
-------------------------------------------------
Changes in release v2.0-20180218 (since v2.0-20180217)
-------------------------------------------------
Release date: Sun Feb 18 04:00:11 CET 2018
Gijs Noorlander (1):
[issue #847 ] OpenHAB MQTT rewrite topic parser (#886)
-------------------------------------------------
Changes in release v2.0-20180217 (since v2.0-20180214)
-------------------------------------------------
Release date: Sat Feb 17 04:00:18 CET 2018
Gijs Noorlander (4):
[issue 866] Try to stop logging to serial when serial is not read. (#868)
[issue #853] Favicon.ico (#874)
[OLED Framed] ESP Easy logo (#876)
[issue #869] Added 'LWT' to last will topic and improved CPU load (#883)
-------------------------------------------------
Changes in release v2.0-20180214 (since v2.0-20180213)
-------------------------------------------------
Release date: Wed Feb 14 04:00:21 CET 2018
Edwin Eefting (3):
workaround for PUYA flash chips with write issues #650
travis build fix for PUYA
updated deploy script for PUYA
Gijs Noorlander (1):
[v2.0] Blynk controller (#865)
-------------------------------------------------
Changes in release v2.0-20180213 (since v2.0-20180212)
-------------------------------------------------
Release date: Tue Feb 13 04:00:20 CET 2018
Gijs Noorlander (8):
[#804] Degree symbol for non-framed OLED display (#835)
[issue #839] Add command support for setting contrast for OLED Framed (#841)
[P001 Switch] Fix a mixup in previous fix for switch (#845)
[v2.0] Fix compile errors on ESP32 (#848)
Bugfix/oled framed less memory (#859)
Formatting user vars (re-do of PR#482) + enabled check OpenHabMQTT (#851)
[issue #825] Change labels and password form for Thingspeak controller (#849)
[MQTT] Allow for background tests while waiting for wifi (#860)
soif (1):
P012 - Fix/handle lines exceeding LCD width + allow to clear line b4 print (#852)
-------------------------------------------------
Changes in release v2.0-20180212 (since v2.0-20180209)
-------------------------------------------------
Release date: Mon Feb 12 04:00:22 CET 2018
Gijs Noorlander (1):
[Issue #831] Use DOUT flash mode (#834)
soif (1):
Add Device Name in /json page (#815)
-------------------------------------------------
Changes in release v2.0-20180209 (since v2.0-20180206)
-------------------------------------------------
Release date: Fri Feb 9 04:00:26 CET 2018
wdonker (1):
Add trigger for rulesprocessing (#826)
-------------------------------------------------
Changes in release v2.0-20180206 (since v2.0-20180203)
-------------------------------------------------
Release date: Tue Feb 6 05:00:21 CET 2018
Gijs Noorlander (3):
Backport OLED framed from mega + support special characters (#818)
[issue #817] Added mail header to SMTP (#820)
[issue #727] Proper user interface to set DST rules (#823)
soif (1):
All Advanced Settings as 'DEFAULT_' Defines (#813)
-------------------------------------------------
Changes in release v2.0-20180203 (since v2.0-20180202)
-------------------------------------------------
Release date: Sat Feb 3 05:00:20 CET 2018
Grovkillen (1):
Update README.md
-------------------------------------------------
Changes in release v2.0-20180202 (since v2.0-20180130)
-------------------------------------------------
Release date: Fri Feb 2 05:00:23 CET 2018
DatuX (2):
Update README.md
Update README.md
Gijs Noorlander (3):
[issue #794] Add longpulse_ms command (#796)
[v2.0] Resource friendly string replacement (#798)
[issue #739] Reconnect MQTT when Unit Name has changed. (#803)
soif (5):
Fixes invalid '/json' page output format : DateTimeString is now correctly quoted (#802)
Fix Syslog : include Hosname instead of Unit Number - now RFC3164 compliant (#805)
Allows to define the IP address when in AP Mode (#806)
Custom define file (#807)
Json page also Shows Git Build (#808)
-------------------------------------------------
Changes in release v2.0-20180130 (since v2.0-20180126)
-------------------------------------------------
Release date: Tue Jan 30 05:00:23 CET 2018
Edwin Eefting (1):
forgot to commit last framed oled display fix
Gijs Noorlander (3):
Bugfix/issue 740 allow mqtt as controller 2 3 (#785)
[#784] Add %rssi% as system variable (#786)
[Log] Clean up of log routines and more intuitive log level input (#788)
-------------------------------------------------
Changes in release v2.0-20180126 (since v2.0-20180124)
-------------------------------------------------
Release date: Fri Jan 26 05:00:22 CET 2018
Gijs Noorlander (3):
[issue #759] Disable Senseair ABC due to firmware issues (#771)
[V2.0] Allow IRremoteESP8266 to be built with core 2.4.0 (#773)
Update _C007.ino (#774) (#776)
-------------------------------------------------
Changes in release v2.0-20180124 (since v2.0-20180123)
-------------------------------------------------
Release date: Wed Jan 24 05:00:19 CET 2018
Edwin Eefting (1):
fix #718. also update display on save and removed graphical boot logo to conserve space. also fixes #713. (web interface will be non repsonsive during scrolling now, but there is no easy fix for that)
Gijs Noorlander (1):
[issue #758] P029 MQTT helper does not log anymore (#764)
-------------------------------------------------
Changes in release v2.0-20180123 (since v2.0-20180122)
-------------------------------------------------
Release date: Tue Jan 23 05:00:20 CET 2018
Edwin Eefting (5):
test suite: now possible to run all tests at once. fixes
test suite: espcli can now do stuff for all configured nodes
clear custom task and controller settings when selecting a different device or protocol. replaces #762 . fixes #721
added easy reboot warning and function to work around several issues
request mainpage when checking if reboot is complete
Gijs Noorlander (1):
Central function for system variable replacement (#757)
-------------------------------------------------
Changes in release v2.0-20180122 (since v2.0-20180121)
-------------------------------------------------
Release date: Mon Jan 22 05:00:19 CET 2018
Gijs Noorlander (2):
[issue #745] Set IPaddress to 0.0.0.0 when read from empty string (#754)
[#732] Only process P029 MQTT helper when enabled (#743)
-------------------------------------------------
Changes in release v2.0-20180121 (since v2.0-20180120)
-------------------------------------------------
Release date: Sun Jan 21 05:00:12 CET 2018
Edwin Eefting (5):
test suite: generelized controller testing in test005
cleaned up nodo logging. fixed domotics SENSOR_TYPE_WIND inconsistency
test suite: fixed issues, started working on nodo
test suite: lots of refactoring and fixing
test suite: fixes. testing boot gpio states
-------------------------------------------------
Changes in release v2.0-20180120 (since v2.0-20180119)
-------------------------------------------------
Release date: Sat Jan 20 05:00:12 CET 2018
Edwin Eefting (2):
added QUAD to c002. fixed getBearing and SENSOR_TYPE_WIND.
test suite: started on testcase to test all sensor types via the dummy plugin
-------------------------------------------------
Changes in release v2.0-20180119 (since v2.0-20180118)
-------------------------------------------------
Release date: Fri Jan 19 05:00:18 CET 2018
Edwin Eefting (2):
test suite domoticz mqtt + found few fixmes
test suite: added dht22
-------------------------------------------------
Changes in release v2.0-20180118 (since v2.0-20180116)
-------------------------------------------------
Release date: Thu Jan 18 05:00:19 CET 2018
Edwin Eefting (1):
refactoring test suite controller stuff
Gijs Noorlander (2):
[issue 733] Fix for negative values on MQTT import (#735)
[issue 728] Proper reconnect for MQTT controllers (#737)
-------------------------------------------------
Changes in release v2.0-20180116 (since v2.0-20180113)
-------------------------------------------------
Release date: Tue Jan 16 05:00:21 CET 2018
Edwin Eefting (3):
fixed custom build path
made test resumable and importable
now supports powercycle to test for bugs like #719
Gijs Noorlander (1):
[AutoDST] Added Auto DST (Bugfix/v2.0 issue569) (#726)
-------------------------------------------------
Changes in release v2.0-20180113 (since v2.0-20180112)
-------------------------------------------------
Release date: Sat Jan 13 05:00:20 CET 2018
Edwin Eefting (5):
release bot fixes
dont make same release twice
dont make same release twice
ESPEasy v2.0 only supports compiling under arduino core 2.3.0 to prevent issues like #705 when people use Arduino IDE to compile with arduino core 2.4.0
testsuite: working on generic http/mqtt controller emulatior receiving
-------------------------------------------------
Changes in release v2.0-20180112 (since v2.0-20180111)
-------------------------------------------------
Release date: Fri Jan 12 01:56:54 CET 2018
Edwin Eefting (4):
added http server emulation and domotics http to testsuite
first http domoticz test works
testsuite requirements
fixed releasebot issues with multiple branches
Gijs Noorlander (2):
[Issue 699] Incorrect shown device name (#700)
[v2.0 #470] Do not send invalid values to a controller (#701)
-------------------------------------------------
Changes in release v2.0-20180111 (since mega-20180111)
-------------------------------------------------
Release date: Thu Jan 11 05:00:18 CET 2018
-------------------------------------------------
Changes in release v2.0-20180110 (since mega-20180104)
-------------------------------------------------
Release date: Wed Jan 10 16:14:23 CET 2018
ESPEasy release bot (1):
added releasebot to v2.0 branch
Edwin Eefting (5):
changed readme title
readme updates
actually ignore MQTT messages that are too big.
moved mqtt stuff outside of backgroundtasks(). fixes #683 in my test scenario
fixed plugin id of "Communication - Kamstrup Multical 401". (accidental octal notation)
Gijs Noorlander (4):
[switch] Fixed switch behavior and default settings. (#675)
[Flash info] Detailed flash information (#678)
Bugfix/v2.0 crash switch (#682)
[Adafruit MPR121] Change deprecated name setThreshholds to setThresholds (#685)
chunter1 (1):
ABC calibration feature added (#606)
-------------------------------------------------
Changes in release v2.0.0-dev13 (since v2.0.0-dev12)
-------------------------------------------------
+10 -10
View File
@@ -1,16 +1,16 @@
/***************************************************
/***************************************************
This is a library for the MPR121 I2C 12-chan Capacitive Sensor
Designed specifically to work with the MPR121 sensor from Adafruit
----> https://www.adafruit.com/products/1982
These sensors use I2C to communicate, 2+ pins are required to
These sensors use I2C to communicate, 2+ pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
@@ -21,26 +21,26 @@ Adafruit_MPR121::Adafruit_MPR121() {
boolean Adafruit_MPR121::begin(uint8_t i2caddr) {
Wire.begin();
_i2caddr = i2caddr;
// soft reset
writeRegister(MPR121_SOFTRESET, 0x63);
delay(1);
for (uint8_t i=0; i<0x7F; i++) {
// Serial.print("$"); Serial.print(i, HEX);
// Serial.print("$"); Serial.print(i, HEX);
// Serial.print(": 0x"); Serial.println(readRegister8(i));
}
writeRegister(MPR121_ECR, 0x0);
uint8_t c = readRegister8(MPR121_CONFIG2);
if (c != 0x24) return false;
setThreshholds(12, 6);
setThresholds(12, 6);
writeRegister(MPR121_MHDR, 0x01);
writeRegister(MPR121_NHDR, 0x01);
writeRegister(MPR121_NCLR, 0x0E);
@@ -0,0 +1,241 @@
/*
ESPeasySoftwareSerial.cpp - Implementation of the Arduino software serial for ESP8266.
Copyright (c) 2015-2016 Peter Lerup. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
// The Arduino standard GPIO routines are not enough,
// must use some from the Espressif SDK as well
extern "C" {
#include "gpio.h"
}
#include <ESPeasySoftwareSerial.h>
#define MAX_PIN 15
#define USABLE_PINS 10
#define NR_CONCURRENT_SOFT_SERIALS 3
// As the Arduino attachInterrupt has no parameter, lists of objects
// and callbacks corresponding to each possible GPIO pins have to be defined
static ESPeasySoftwareSerial *ObjList[NR_CONCURRENT_SOFT_SERIALS];
static uint8_t PinControllerMap[NR_CONCURRENT_SOFT_SERIALS]={}; // Zero all elements
void ICACHE_RAM_ATTR sws_isr_0() { ObjList[0]->rxRead(); };
void ICACHE_RAM_ATTR sws_isr_1() { ObjList[1]->rxRead(); };
void ICACHE_RAM_ATTR sws_isr_2() { ObjList[2]->rxRead(); };
/*void ICACHE_RAM_ATTR sws_isr_3() { ObjList[3]->rxRead(); };
void ICACHE_RAM_ATTR sws_isr_4() { ObjList[4]->rxRead(); };
void ICACHE_RAM_ATTR sws_isr_5() { ObjList[5]->rxRead(); };
// Pin 6 to 11 can not be used
void ICACHE_RAM_ATTR sws_isr_12() { ObjList[6]->rxRead(); };
void ICACHE_RAM_ATTR sws_isr_13() { ObjList[7]->rxRead(); };
void ICACHE_RAM_ATTR sws_isr_14() { ObjList[8]->rxRead(); };
void ICACHE_RAM_ATTR sws_isr_15() { ObjList[9]->rxRead(); };
*/
static void (*ISRList[NR_CONCURRENT_SOFT_SERIALS])() = {
sws_isr_0,
sws_isr_1,
sws_isr_2 /*,
sws_isr_3,
sws_isr_4,
sws_isr_5,
// Pin 6 to 11 can not be used
sws_isr_12,
sws_isr_13,
sws_isr_14,
sws_isr_15
*/
};
ESPeasySoftwareSerial::ESPeasySoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic, uint16_t buffSize) {
m_rxValid = m_txValid = m_txEnableValid = false;
m_buffer = NULL;
m_invert = inverse_logic;
if (isValidGPIOpin(receivePin)) {
m_rxPin = receivePin;
m_buffSize = buffSize;
m_buffer = (uint8_t*)malloc(m_buffSize);
if (m_buffer != NULL) {
m_rxValid = true;
m_inPos = m_outPos = 0;
pinMode(m_rxPin, INPUT);
const uint8_t index = pinToIndex(m_rxPin);
if (index == NR_CONCURRENT_SOFT_SERIALS) {
return; // Not possible to add software Serial.
}
ObjList[index] = this;
enableRx(true);
}
}
if (isValidGPIOpin(transmitPin)) {
m_txValid = true;
m_txPin = transmitPin;
pinMode(m_txPin, OUTPUT);
digitalWrite(m_txPin, !m_invert);
}
// Default speed
begin(9600);
}
ESPeasySoftwareSerial::~ESPeasySoftwareSerial() {
enableRx(false);
if (m_rxValid) {
const uint8_t index = pinToIndex(m_rxPin);
if (index < NR_CONCURRENT_SOFT_SERIALS) {
PinControllerMap[index] = 0;
ObjList[index] = NULL;
}
}
if (m_buffer)
free(m_buffer);
}
bool ESPeasySoftwareSerial::isValidGPIOpin(uint8_t pin) {
if (pin >= 0 && pin <= 5) {
return true;
}
if (pin >= 12 && pin <= MAX_PIN) {
return true;
}
return false;
}
uint8_t ESPeasySoftwareSerial::pinToIndex(uint8_t pin) {
// Pin will be stored in the map, only "1" will be added,
// to allow simple initialize to 0 and still use GPIO-0.
const uint8_t stored_pin = pin + 1;
for (unsigned i = 0; i < NR_CONCURRENT_SOFT_SERIALS; ++i) {
if (PinControllerMap[i] == stored_pin) return i;
}
// Not found, add as first free option.
for (unsigned i = 0; i < NR_CONCURRENT_SOFT_SERIALS; ++i) {
if (PinControllerMap[i] == 0) {
PinControllerMap[i] = stored_pin;
return i;
}
}
// No more controllers available.
return NR_CONCURRENT_SOFT_SERIALS;
}
void ESPeasySoftwareSerial::begin(long speed) {
// Use getCycleCount() loop to get as exact timing as possible
m_bitTime = ESP.getCpuFreqMHz()*1000000/speed;
}
void ESPeasySoftwareSerial::setTransmitEnablePin(uint8_t transmitEnablePin) {
if (isValidGPIOpin(transmitEnablePin)) {
m_txEnableValid = true;
m_txEnablePin = transmitEnablePin;
pinMode(m_txEnablePin, OUTPUT);
digitalWrite(m_txEnablePin, LOW);
} else {
m_txEnableValid = false;
}
}
void ESPeasySoftwareSerial::enableRx(bool on) {
if (m_rxValid) {
if (on) {
attachInterrupt(m_rxPin, ISRList[pinToIndex(m_rxPin)], m_invert ? RISING : FALLING);
} else {
detachInterrupt(m_rxPin);
}
}
}
int ESPeasySoftwareSerial::read() {
if (!m_rxValid || (m_inPos == m_outPos)) return -1;
uint8_t ch = m_buffer[m_outPos];
m_outPos = (m_outPos+1) % m_buffSize;
return ch;
}
int ESPeasySoftwareSerial::available() {
if (!m_rxValid) return 0;
int avail = m_inPos - m_outPos;
if (avail < 0) avail += m_buffSize;
return avail;
}
#define WAIT { while (ESP.getCycleCount()-start < wait); wait += m_bitTime; }
size_t ESPeasySoftwareSerial::write(uint8_t b) {
if (!m_txValid) return 0;
if (m_invert) b = ~b;
// Disable interrupts in order to get a clean transmit
cli();
if (m_txEnableValid) digitalWrite(m_txEnablePin, HIGH);
unsigned long wait = m_bitTime;
digitalWrite(m_txPin, HIGH);
unsigned long start = ESP.getCycleCount();
// Start bit;
digitalWrite(m_txPin, LOW);
WAIT;
for (int i = 0; i < 8; i++) {
digitalWrite(m_txPin, (b & 1) ? HIGH : LOW);
WAIT;
b >>= 1;
}
// Stop bit
digitalWrite(m_txPin, HIGH);
WAIT;
if (m_txEnableValid) digitalWrite(m_txEnablePin, LOW);
sei();
return 1;
}
void ESPeasySoftwareSerial::flush() {
m_inPos = m_outPos = 0;
}
int ESPeasySoftwareSerial::peek() {
if (!m_rxValid || (m_inPos == m_outPos)) return -1;
return m_buffer[m_outPos];
}
void ICACHE_RAM_ATTR ESPeasySoftwareSerial::rxRead() {
// Advance the starting point for the samples but compensate for the
// initial delay which occurs before the interrupt is delivered
unsigned long wait = m_bitTime + m_bitTime/3 - 500;
unsigned long start = ESP.getCycleCount();
uint8_t rec = 0;
for (uint8_t i = 0; i < 8; i++) {
WAIT;
rec >>= 1;
if (digitalRead(m_rxPin))
rec |= 0x80;
}
if (m_invert) rec = ~rec;
// Stop bit
WAIT;
// Store the received value in the buffer unless we have an overflow
uint16_t next = (m_inPos+1) % m_buffSize;
if (next != m_inPos) {
m_buffer[m_inPos] = rec;
m_inPos = next;
}
// Must clear this bit in the interrupt register,
// it gets set even when interrupts are disabled
GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, 1 << m_rxPin);
}
@@ -0,0 +1,78 @@
/*
ESPeasySoftwareSerial.h
ESPeasySoftwareSerial.cpp - Implementation of the Arduino software serial for ESP8266.
Copyright (c) 2015-2016 Peter Lerup. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ESPeasySoftwareSerial_h
#define ESPeasySoftwareSerial_h
#include <inttypes.h>
#include <Stream.h>
// This class is compatible with the corresponding AVR one,
// the constructor however has an optional rx buffer size.
// Speed up to 115200 can be used.
class ESPeasySoftwareSerial : public Stream
{
public:
ESPeasySoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false, uint16_t buffSize = 64);
virtual ~ESPeasySoftwareSerial();
void begin(long speed);
void setTransmitEnablePin(uint8_t transmitEnablePin);
int peek();
virtual size_t write(uint8_t byte);
virtual int read();
virtual int available();
virtual void flush();
operator bool() {return m_rxValid || m_txValid;}
// Disable or enable interrupts on the rx pin
void enableRx(bool on);
void rxRead();
using Print::write;
private:
bool isValidGPIOpin(uint8_t pin);
uint8_t pinToIndex(uint8_t pin);
// Member variables
uint8_t m_rxPin, m_txPin, m_txEnablePin;
bool m_rxValid, m_txValid, m_txEnableValid;
bool m_invert;
unsigned long m_bitTime;
uint16_t m_inPos, m_outPos;
uint16_t m_buffSize;
uint8_t *m_buffer;
};
// If only one tx or rx wanted then use this as parameter for the unused pin
#define SW_SERIAL_UNUSED_PIN -1
#endif
+11
View File
@@ -0,0 +1,11 @@
# EspESPeasySoftwareSerial
Implementation of the Arduino software serial library for the ESP8266
Same functionality as the corresponding AVR library but several instances can be active at the same time.
Speed up to 115200 baud is supported. The constructor also has an optional input buffer size.
Please note that due to the fact that the ESP always have other activities ongoing, there will be some inexactness in interrupt
timings. This may lead to bit errors when having heavy data traffic in high baud rates.
@@ -0,0 +1,27 @@
#include <ESPeasySoftwareSerial.h>
ESPeasySoftwareSerial swSer(14, 12, false, 256);
void setup() {
Serial.begin(115200);
swSer.begin(115200);
Serial.println("\nSoftware serial test started");
for (char ch = ' '; ch <= 'z'; ch++) {
swSer.write(ch);
}
swSer.println("");
}
void loop() {
while (swSer.available() > 0) {
Serial.write(swSer.read());
}
while (Serial.available() > 0) {
swSer.write(Serial.read());
}
}
+31
View File
@@ -0,0 +1,31 @@
#######################################
# Syntax Coloring Map for ESPeasySoftwareSerial
# (esp8266)
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
ESPeasySoftwareSerial KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
read KEYWORD2
write KEYWORD2
available KEYWORD2
flush KEYWORD2
overflow KEYWORD2
peek KEYWORD2
listen KEYWORD2
end KEYWORD2
isListening KEYWORD2
stopListening KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
+15
View File
@@ -0,0 +1,15 @@
{
"name": "EspESPeasySoftwareSerial",
"version": "3.3.1",
"keywords": [
"serial", "io", "softwareserial"
],
"description": "Implementation of the Arduino software serial for ESP8266. Adjusted to reduce memory footprint for ESPeasy",
"repository":
{
"type": "git",
"url": "https://github.com/plerup/espsoftwareserial"
},
"frameworks": "arduino",
"platforms": "espressif8266"
}
@@ -0,0 +1,9 @@
name=ESPeasySoftwareSerial
version=1.0
author=Peter Lerup
maintainer=Peter Lerup <peter@lerup.com>
sentence=Implementation of the Arduino software serial for ESP8266.
paragraph=
category=Signal Input/Output
url=
architectures=esp8266
+456
View File
@@ -0,0 +1,456 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
+40
View File
@@ -0,0 +1,40 @@
# ESP8266Ping
Let the ESP8266 ping a remote machine.
With this library an ESP8266 can ping a remote machine and know if it's reachable.
It provide some basic measurements on ping messages (avg response time).
## Usage
First, include the library in your sketch along with WiFi library:
```Arduino
#include <ESP8266WiFi.h>
#include <ESP8266Ping.h>
```
Next, simply call the `Ping.ping()` function
```Arduino
IPAddress ip (192, 168, 0, 1); // The remote ip to ping
bool ret = Ping.ping(ip);
```
`ret` will be true if the remote responded to pings, false if not reachable.
The library supports hostname too, just pass a string instead of the ip address:
```Arduino
bool ret = Ping.ping("www.google.com");
```
Additionally, the function accept a second integer parameter `count` that specify how many pings has to be sent:
```Arduino
bool ret = Ping.ping(ip_or_host, 10);
```
After `Ping.ping()` has been called, the average response time (in milliseconds) can be retrieved with
```Arduino
int avg_time_ms = Ping.averageTime();
```
@@ -0,0 +1,43 @@
/*
* This example show how to ping a remote machine using it's hostname
*/
#include <ESP8266WiFi.h>
#include <ESP8266Ping.h>
const char* ssid = "ssid";
const char* password = "passphrase";
const char* remote_host = "www.google.com";
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println();
Serial.print("WiFi connected with ip ");
Serial.println(WiFi.localIP());
Serial.print("Pinging host ");
Serial.println(remote_host);
if(Ping.ping(remote_host)) {
Serial.println("Success!!");
} else {
Serial.println("Error :(");
}
}
void loop() { }
@@ -0,0 +1,44 @@
/*
* With this library an ESP8266 can ping a remote machine and know if it's reachable.
* It provides some basic measurements on ping messages (avg response time).
*/
#include <ESP8266WiFi.h>
#include <ESP8266Ping.h>
const char* ssid = "ssid";
const char* password = "passphrase";
const IPAddress remote_ip(192, 168, 0, 1);
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println();
Serial.print("WiFi connected with ip ");
Serial.println(WiFi.localIP());
Serial.print("Pinging ip ");
Serial.println(remote_ip);
if(Ping.ping(remote_ip)) {
Serial.println("Success!!");
} else {
Serial.println("Error :(");
}
}
void loop() { }
+26
View File
@@ -0,0 +1,26 @@
#######################################
# Syntax Coloring Map For ESP8266Ping
#######################################
#######################################
# Library (KEYWORD3)
#######################################
ESP8266Ping KEYWORD3
#######################################
# Datatypes (KEYWORD1)
#######################################
Ping KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
ping KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
@@ -0,0 +1,9 @@
name=ESPEasy_ESP8266Ping
version=1.0
author=Daniele Colanardi
maintainer=Daniele Colanardi <dancol90@gmail.com>
sentence=Let the ESP8266 ping a remote machine.
paragraph=With this library an ESP8266 can ping a remote machine and know if it's reachable. It provide some basic measurements on ping messages (avg response time). Lib name renamed to avoid conflicts in Arduino IDE.
category=Communication
url=
architectures=esp8266
+59
View File
@@ -0,0 +1,59 @@
/*
ESP8266Ping - Ping library for ESP8266
Copyright (c) 2015 Daniele Colanardi. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef ESP8266Ping_H
#define ESP8266Ping_H
#include <Arduino.h>
#include <ESP8266WiFi.h>
extern "C" {
#include <ping.h>
}
#ifdef ENABLE_DEBUG_PING
#define DEBUG_PING(...) Serial.printf(__VA_ARGS__)
#else
#define DEBUG_PING(...)
#endif
class PingClass {
public:
PingClass();
bool ping(IPAddress dest, byte count = 5);
bool ping(const char* host, byte count = 5);
int averageTime();
protected:
static void _ping_sent_cb(void *opt, void *pdata);
static void _ping_recv_cb(void *opt, void *pdata);
IPAddress _dest;
ping_option _options;
static byte _expected_count, _errors, _success;
static int _avg_time;
};
#include "ESP8266Ping.impl.h"
PingClass Ping;
#endif
@@ -0,0 +1,111 @@
/*
ESP8266Ping - Ping library for ESP8266
Copyright (c) 2015 Daniele Colanardi. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
extern "C" void esp_schedule();
extern "C" void esp_yield();
PingClass::PingClass() {}
bool PingClass::ping(IPAddress dest, byte count) {
_expected_count = count;
_errors = 0;
_success = 0;
_avg_time = 0;
memset(&_options, 0, sizeof(struct ping_option));
// Repeat count (how many time send a ping message to destination)
_options.count = count;
// Time interval between two ping (seconds??)
_options.coarse_time = 1;
// Destination machine
_options.ip = dest;
// Callbacks
_options.recv_function = reinterpret_cast<ping_recv_function>(&PingClass::_ping_recv_cb);
_options.sent_function = NULL; //reinterpret_cast<ping_sent_function>(&_ping_sent_cb);
// Let's go!
if(ping_start(&_options)) {
// Suspend till the process end
esp_yield();
}
return (_success > 0);
}
bool PingClass::ping(const char* host, byte count) {
IPAddress remote_addr;
if (WiFi.hostByName(host, remote_addr))
return ping(remote_addr, count);
return false;
}
int PingClass::averageTime() {
return _avg_time;
}
void PingClass::_ping_recv_cb(void *opt, void *resp) {
// Cast the parameters to get some usable info
ping_resp* ping_resp = reinterpret_cast<struct ping_resp*>(resp);
//ping_option* ping_opt = reinterpret_cast<struct ping_option*>(opt);
// Error or success?
if (ping_resp->ping_err == -1)
_errors++;
else {
_success++;
_avg_time += ping_resp->resp_time;
}
// Some debug info
DEBUG_PING(
"DEBUG: ping reply\n"
"\ttotal_count = %d \n"
"\tresp_time = %d \n"
"\tseqno = %d \n"
"\ttimeout_count = %d \n"
"\tbytes = %d \n"
"\ttotal_bytes = %d \n"
"\ttotal_time = %d \n"
"\tping_err = %d \n",
ping_resp->total_count, ping_resp->resp_time, ping_resp->seqno,
ping_resp->timeout_count, ping_resp->bytes, ping_resp->total_bytes,
ping_resp->total_time, ping_resp->ping_err
);
// Is it time to end?
// Don't using seqno because it does not increase on error
if (_success + _errors == _expected_count) {
_avg_time = _avg_time / _expected_count;
DEBUG_PING("Avg resp time %d ms\n", _avg_time);
// Done, return to main functiom
esp_schedule();
}
}
byte PingClass::_expected_count = 0;
byte PingClass::_errors = 0;
byte PingClass::_success = 0;
int PingClass::_avg_time = 0;
+4 -4
View File
@@ -93,8 +93,8 @@ bool ICACHE_FLASH_ATTR IRKelvinatorAC::getPower() {
// Set the temp. in deg C
void ICACHE_FLASH_ATTR IRKelvinatorAC::setTemp(uint8_t temp) {
temp = max(KELVINATOR_MIN_TEMP, temp);
temp = min(KELVINATOR_MAX_TEMP, temp);
temp = max(static_cast<uint8_t>(KELVINATOR_MIN_TEMP), temp);
temp = min(static_cast<uint8_t>(KELVINATOR_MAX_TEMP), temp);
remote_state[1] = (remote_state[1] & 0xF0U) | (temp - KELVINATOR_MIN_TEMP);
remote_state[9] = remote_state[1]; // Duplicate to the 2nd command chunk.
}
@@ -106,12 +106,12 @@ uint8_t ICACHE_FLASH_ATTR IRKelvinatorAC::getTemp() {
// Set the speed of the fan, 0-5, 0 is auto, 1-5 is the speed
void ICACHE_FLASH_ATTR IRKelvinatorAC::setFan(uint8_t fan) {
fan = min(KELVINATOR_FAN_MAX, fan); // Bounds check
fan = min(static_cast<uint8_t>(KELVINATOR_FAN_MAX), fan); // Bounds check
// Only change things if we need to.
if (fan != getFan()) {
// Set the basic fan values.
uint8_t fan_basic = min(KELVINATOR_BASIC_FAN_MAX, fan);
uint8_t fan_basic = min(static_cast<uint8_t>(KELVINATOR_BASIC_FAN_MAX), fan);
remote_state[0] = (remote_state[0] & KELVINATOR_BASIC_FAN_MASK) |
(fan_basic << KELVINATOR_FAN_OFFSET);
remote_state[8] = remote_state[0]; // Duplicate to the 2nd command chunk.
+3 -3
View File
@@ -77,8 +77,8 @@ bool ICACHE_FLASH_ATTR IRMitsubishiAC::getPower() {
// Set the temp. in deg C
void ICACHE_FLASH_ATTR IRMitsubishiAC::setTemp(uint8_t temp) {
temp = max(MITSUBISHI_AC_MIN_TEMP, temp);
temp = min(MITSUBISHI_AC_MAX_TEMP, temp);
temp = max(static_cast<uint8_t>(MITSUBISHI_AC_MIN_TEMP), temp);
temp = min(static_cast<uint8_t>(MITSUBISHI_AC_MAX_TEMP), temp);
remote_state[7] = temp - MITSUBISHI_AC_MIN_TEMP;
}
@@ -136,7 +136,7 @@ void ICACHE_FLASH_ATTR IRMitsubishiAC::setMode(uint8_t mode) {
// Set the requested vane operation mode of the a/c unit.
void ICACHE_FLASH_ATTR IRMitsubishiAC::setVane(uint8_t mode) {
mode = max(mode, B111); // bounds check
mode = max(mode, static_cast<uint8_t>(B111)); // bounds check
mode |= B1000;
mode <<= 3;
remote_state[9] |= mode;
+7 -7
View File
@@ -155,7 +155,7 @@ void ICACHE_FLASH_ATTR IRsend::sendNEC (unsigned long data, int nbits,
// Footer
mark(NEC_BIT_MARK);
// Gap to next command.
space(max(0, NEC_MIN_COMMAND_LENGTH - usecs.elapsed()));
space(max(0ul, NEC_MIN_COMMAND_LENGTH - usecs.elapsed()));
// Optional command repeat sequence.
for (unsigned int i = 0; i < repeat; i++) {
@@ -164,7 +164,7 @@ void ICACHE_FLASH_ATTR IRsend::sendNEC (unsigned long data, int nbits,
space(NEC_RPT_SPACE);
mark(NEC_BIT_MARK);
// Gap till next command.
space(max(0, NEC_MIN_COMMAND_LENGTH - usecs.elapsed()));
space(max(0ul, NEC_MIN_COMMAND_LENGTH - usecs.elapsed()));
}
}
@@ -236,7 +236,7 @@ void ICACHE_FLASH_ATTR IRsend::sendSony(unsigned long data, int nbits,
// Footer
// The Sony protocol requires us to wait 45ms from start of a code to the
// start of the next one. A 10ms minimum gap is also required.
space(max(10000, 45000 - usecs.elapsed()));
space(max(10000u, 45000 - usecs.elapsed()));
}
// A space() is always performed last, so no need to turn off the LED.
}
@@ -367,7 +367,7 @@ void ICACHE_FLASH_ATTR IRsend::sendRCMM(uint32_t data, uint8_t nbits) {
mark(RCMM_BIT_MARK);
// Protocol requires us to wait at least RCMM_RPT_LENGTH usecs from the start
// or RCMM_MIN_GAP usecs.
space(max(RCMM_RPT_LENGTH - usecs.elapsed(), RCMM_MIN_GAP));
space(max(RCMM_RPT_LENGTH - usecs.elapsed(), static_cast<uint32_t>(RCMM_MIN_GAP)));
}
void ICACHE_FLASH_ATTR IRsend::sendPanasonic(unsigned int address,
@@ -415,7 +415,7 @@ void ICACHE_FLASH_ATTR IRsend::sendJVC(unsigned long data, int nbits,
// Footer
mark(JVC_BIT_MARK);
// Wait till the end of the repeat time window before we send another code.
space(max(0, JVC_RPT_LENGTH - usecs.elapsed()));
space(max(0u, JVC_RPT_LENGTH - usecs.elapsed()));
usecs.reset();
}
// No need to turn off the LED as we will always end with a space().
@@ -647,7 +647,7 @@ void ICACHE_FLASH_ATTR IRsend::sendSherwood(unsigned long data, int nbits,
unsigned int repeat) {
// Sherwood remote codes appear to be NEC codes with a manditory repeat code.
// i.e. repeat should be >= 1.
sendNEC(data, nbits, max(1, repeat));
sendNEC(data, nbits, max(1u, repeat));
}
void ICACHE_FLASH_ATTR IRsend::sendMitsubishiAC(unsigned char data[]) {
@@ -911,7 +911,7 @@ bool ICACHE_FLASH_ATTR IRrecv::decode(decode_results *results,
// Nr. of ticks.
uint32_t IRrecv::ticksLow(uint32_t usecs, uint8_t tolerance) {
// max() used to ensure the result can't drop below 0 before the cast.
return((uint32_t) max(usecs * (1.0 - tolerance/100.)/USECPERTICK, 0));
return((uint32_t) max(usecs * (1.0 - tolerance/100.)/USECPERTICK, 0.0));
}
// Calculate the upper bound of the nr. of ticks.
+21 -11
View File
@@ -1,11 +1,4 @@
//www.DFRobot.com
//last updated on 21/12/2011
//Tim Starling Fix the reset bug (Thanks Tim)
//wiki doc http://www.dfrobot.com/wiki/index.php?title=I2C/TWI_LCD1602_Module_(SKU:_DFR0063)
//Support Forum: http://www.dfrobot.com/forum/
//Compatible with the Arduino IDE 1.0
//Library version:1.1
// Based on the work by DFRobot
#include "LiquidCrystal_I2C.h"
#include <inttypes.h>
@@ -16,7 +9,7 @@
#define printIIC(args) Wire.write(args)
inline size_t LiquidCrystal_I2C::write(uint8_t value) {
send(value, Rs);
return 0;
return 1;
}
#else
@@ -59,6 +52,11 @@ LiquidCrystal_I2C::LiquidCrystal_I2C(uint8_t lcd_Addr,uint8_t lcd_cols,uint8_t l
_backlightval = LCD_NOBACKLIGHT;
}
void LiquidCrystal_I2C::oled_init(){
_oled = true;
init_priv();
}
void LiquidCrystal_I2C::init(){
init_priv();
}
@@ -134,6 +132,7 @@ void LiquidCrystal_I2C::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {
void LiquidCrystal_I2C::clear(){
command(LCD_CLEARDISPLAY);// clear display, set cursor position to zero
delayMicroseconds(2000); // this command takes a long time!
if (_oled) setCursor(0,0);
}
void LiquidCrystal_I2C::home(){
@@ -221,6 +220,15 @@ void LiquidCrystal_I2C::createChar(uint8_t location, uint8_t charmap[]) {
}
}
//createChar with PROGMEM input
void LiquidCrystal_I2C::createChar(uint8_t location, const char *charmap) {
location &= 0x7; // we only have 8 locations 0-7
command(LCD_SETCGRAMADDR | (location << 3));
for (int i=0; i<8; i++) {
write(pgm_read_byte_near(charmap++));
}
}
// Turn the (optional) backlight off/on
void LiquidCrystal_I2C::noBacklight(void) {
_backlightval=LCD_NOBACKLIGHT;
@@ -309,6 +317,8 @@ void LiquidCrystal_I2C::printstr(const char c[]){
// unsupported API functions
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
void LiquidCrystal_I2C::off(){}
void LiquidCrystal_I2C::on(){}
void LiquidCrystal_I2C::setDelay (int cmdDelay,int charDelay) {}
@@ -318,5 +328,5 @@ uint8_t LiquidCrystal_I2C::init_bargraph(uint8_t graphtype){return 0;}
void LiquidCrystal_I2C::draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end){}
void LiquidCrystal_I2C::draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_row_end){}
void LiquidCrystal_I2C::setContrast(uint8_t new_val){}
#pragma GCC diagnostic pop
+7 -2
View File
@@ -1,4 +1,4 @@
//DFRobot.com
//YWROBOT
#ifndef LiquidCrystal_I2C_h
#define LiquidCrystal_I2C_h
@@ -77,14 +77,18 @@ public:
void autoscroll();
void noAutoscroll();
void createChar(uint8_t, uint8_t[]);
void createChar(uint8_t location, const char *charmap);
// Example: const char bell[8] PROGMEM = {B00100,B01110,B01110,B01110,B11111,B00000,B00100,B00000};
void setCursor(uint8_t, uint8_t);
#if defined(ARDUINO) && ARDUINO >= 100
#if defined(ARDUINO) && ARDUINO >= 100
virtual size_t write(uint8_t);
#else
virtual void write(uint8_t);
#endif
void command(uint8_t);
void init();
void oled_init();
////compatibility API function aliases
void blink_on(); // alias for blink()
@@ -118,6 +122,7 @@ private:
uint8_t _displaycontrol;
uint8_t _displaymode;
uint8_t _numlines;
bool _oled = false;
uint8_t _cols;
uint8_t _rows;
uint8_t _backlightval;
+2
View File
@@ -0,0 +1,2 @@
# LiquidCrystal_I2C
LiquidCrystal Arduino library for the DFRobot I2C LCD displays
-69
View File
@@ -1,69 +0,0 @@
1,6c1
< //www.DFRobot.com
< //last updated on 26/11/2010
< //Tim Starling Fix the reset bug (Thanks Tim)
< //wiki doc http://www.dfrobot.com/wiki/index.php?title=I2C/TWI_LCD1602_Module_(SKU:_DFR0063)
< //Support Forum: http://www.dfrobot.com/forum/
<
---
> // LiquidCrystal_I2C V2.0
10d4
< #include "WProgram.h"
12c6
<
---
> #include "Arduino.h"
67c61
< delay(50);
---
> delayMicroseconds(50000);
77,90c71,84
< // we start in 8bit mode, try to set 4 bit mode
< write4bits(0x03 << 4);
< delayMicroseconds(4500); // wait min 4.1ms
<
< // second try
< write4bits(0x03 << 4);
< delayMicroseconds(4500); // wait min 4.1ms
<
< // third go!
< write4bits(0x03 << 4);
< delayMicroseconds(150);
<
< // finally, set to 4-bit interface
< write4bits(0x02 << 4);
---
> // we start in 8bit mode, try to set 4 bit mode
> write4bits(0x03);
> delayMicroseconds(4500); // wait min 4.1ms
>
> // second try
> write4bits(0x03);
> delayMicroseconds(4500); // wait min 4.1ms
>
> // third go!
> write4bits(0x03);
> delayMicroseconds(150);
>
> // finally, set to 4-bit interface
> write4bits(0x02);
225c219
< inline void LiquidCrystal_I2C::write(uint8_t value) {
---
> inline size_t LiquidCrystal_I2C::write(uint8_t value) {
226a221
> return 0;
235,238c230,233
< uint8_t highnib=value&0xf0;
< uint8_t lownib=(value<<4)&0xf0;
< write4bits((highnib)|mode);
< write4bits((lownib)|mode);
---
> uint8_t highnib=value>>4;
> uint8_t lownib=value & 0x0F;
> write4bits((highnib)|mode);
> write4bits((lownib)|mode);
248c243
< Wire.send((int)(_data) | _backlightval);
---
> Wire.write((int)(_data) | _backlightval);
+4 -4
View File
@@ -1,4 +1,4 @@
//DFRobot.com
//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <Wire.h>
@@ -19,7 +19,7 @@ uint8_t check[8] = {0x0,0x1,0x3,0x16,0x1c,0x8,0x0};
uint8_t cross[8] = {0x0,0x1b,0xe,0x4,0xe,0x1b,0x0};
uint8_t retarrow[8] = { 0x1,0x1,0x5,0x9,0x1f,0x8,0x4};
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
@@ -52,7 +52,7 @@ void displayKeyCodes(void) {
while (1) {
lcd.clear();
lcd.print("Codes 0x"); lcd.print(i, HEX);
lcd.print("-0x"); lcd.print(i+16, HEX);
lcd.print("-0x"); lcd.print(i+15, HEX);
lcd.setCursor(0, 1);
for (int j=0; j<16; j++) {
lcd.printByte(i+j);
@@ -67,4 +67,4 @@ void loop()
{
}
+11 -3
View File
@@ -1,20 +1,28 @@
//DFRobot.com
//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
lcd.init(); // initialize the lcd
lcd.init();
// Print a message to the LCD.
lcd.backlight();
lcd.setCursor(3,0);
lcd.print("Hello, world!");
lcd.setCursor(2,1);
lcd.print("Ywrobot Arduino!");
lcd.setCursor(0,2);
lcd.print("Arduino LCM IIC 2004");
lcd.setCursor(2,3);
lcd.print("Power By Ec-yuan!");
}
void loop()
{
}
+2 -2
View File
@@ -1,14 +1,14 @@
/*
* Displays text sent over the serial port (e.g. from the Serial Monitor) on
* an attached LCD.
* DFRobot.com
* YWROBOT
*Compatible with the Arduino IDE 1.0
*Library version:1.1
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
View File
+16
View File
@@ -0,0 +1,16 @@
{
"name": "LiquidCrystal_I2C",
"keywords": "LCD, liquidcrystal, I2C",
"description": "A library for DFRobot I2C LCD displays",
"repository":
{
"type": "git",
"url": "https://github.com/marcoschwartz/LiquidCrystal_I2C.git"
},
"frameworks": "arduino",
"platforms":
[
"atmelavr",
"espressif8266"
]
}
+9
View File
@@ -0,0 +1,9 @@
name=LiquidCrystal_I2C
version=1.1.4
author=Frank de Brabander
maintainer=Marco Schwartz <marcolivier.schwartz@gmail.com>
sentence=A library for I2C LCD displays.
paragraph= The library allows to control I2C displays with functions extremely similar to LiquidCrystal library. THIS LIBRARY MIGHT NOT BE COMPATIBLE WITH EXISTING SKETCHES.
category=Display
url=https://github.com/marcoschwartz/LiquidCrystal_I2C
architectures=avr
+7 -7
View File
@@ -26,7 +26,7 @@
#include <SensorSerial.h>
SensorSerial::SensorSerial(int receivePin, int transmitPin, bool inverse_logic, unsigned int buffSize) : SoftwareSerial(receivePin, transmitPin, inverse_logic, buffSize)
SensorSerial::SensorSerial(int receivePin, int transmitPin, bool inverse_logic, unsigned int buffSize) : ESPeasySoftwareSerial(receivePin, transmitPin, inverse_logic, buffSize)
{
//boolean sws = isValidGPIOpin(receivePin);
_hw = receivePin < 0;
@@ -37,7 +37,7 @@ void SensorSerial::begin(long speed)
if (_hw)
Serial.begin(speed);
else
SoftwareSerial::begin(speed);
ESPeasySoftwareSerial::begin(speed);
}
int SensorSerial::peek()
@@ -45,7 +45,7 @@ int SensorSerial::peek()
if (_hw)
return Serial.peek();
else
return SoftwareSerial::peek();
return ESPeasySoftwareSerial::peek();
}
size_t SensorSerial::write(uint8_t byte)
@@ -53,7 +53,7 @@ size_t SensorSerial::write(uint8_t byte)
if (_hw)
return Serial.write(byte);
else
return SoftwareSerial::write(byte);
return ESPeasySoftwareSerial::write(byte);
}
int SensorSerial::read()
@@ -61,7 +61,7 @@ int SensorSerial::read()
if (_hw)
return Serial.read();
else
return SoftwareSerial::read();
return ESPeasySoftwareSerial::read();
}
int SensorSerial::available()
@@ -69,7 +69,7 @@ int SensorSerial::available()
if (_hw)
return Serial.available();
else
return SoftwareSerial::available();
return ESPeasySoftwareSerial::available();
}
void SensorSerial::flush()
@@ -77,5 +77,5 @@ void SensorSerial::flush()
if (_hw)
Serial.flush();
else
SoftwareSerial::flush();
ESPeasySoftwareSerial::flush();
}
+2 -2
View File
@@ -27,9 +27,9 @@
#define _SENSORSERIAL_H_
#include "Arduino.h"
#include <SoftwareSerial.h>
#include <ESPeasySoftwareSerial.h>
class SensorSerial : public SoftwareSerial
class SensorSerial : public ESPeasySoftwareSerial
{
public:
SensorSerial(int receivePin, int transmitPin = -1, bool inverse_logic = false, unsigned int buffSize = 64);
@@ -0,0 +1,490 @@
/**The MIT License (MIT)
Copyright (c) 2015 by Daniel Eichhorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
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!
const char Dialog_plain_12[] PROGMEM = {
0x0D, // Width: 13
0x0F, // Height: 15
0x20, // First Char: 32
0xE0, // Numbers of Chars: 224
// Jump Table:
0xFF, 0xFF, 0x00, 0x04, // 32:65535
0x00, 0x00, 0x06, 0x05, // 33:0
0x00, 0x06, 0x07, 0x05, // 34:6
0x00, 0x0D, 0x11, 0x0A, // 35:13
0x00, 0x1E, 0x0E, 0x08, // 36:30
0x00, 0x2C, 0x16, 0x0C, // 37:44
0x00, 0x42, 0x12, 0x09, // 38:66
0x00, 0x54, 0x03, 0x03, // 39:84
0x00, 0x57, 0x06, 0x05, // 40:87
0x00, 0x5D, 0x08, 0x05, // 41:93
0x00, 0x65, 0x0B, 0x07, // 42:101
0x00, 0x70, 0x12, 0x0A, // 43:112
0x00, 0x82, 0x04, 0x03, // 44:130
0x00, 0x86, 0x08, 0x05, // 45:134
0x00, 0x8E, 0x04, 0x03, // 46:142
0x00, 0x92, 0x07, 0x04, // 47:146
0x00, 0x99, 0x0E, 0x08, // 48:153
0x00, 0xA7, 0x0C, 0x07, // 49:167
0x00, 0xB3, 0x0C, 0x07, // 50:179
0x00, 0xBF, 0x0C, 0x07, // 51:191
0x00, 0xCB, 0x0E, 0x08, // 52:203
0x00, 0xD9, 0x0C, 0x07, // 53:217
0x00, 0xE5, 0x0E, 0x08, // 54:229
0x00, 0xF3, 0x0D, 0x08, // 55:243
0x01, 0x00, 0x0E, 0x08, // 56:256
0x01, 0x0E, 0x0E, 0x08, // 57:270
0x01, 0x1C, 0x04, 0x03, // 58:284
0x01, 0x20, 0x04, 0x03, // 59:288
0x01, 0x24, 0x12, 0x0A, // 60:292
0x01, 0x36, 0x12, 0x0A, // 61:310
0x01, 0x48, 0x12, 0x0A, // 62:328
0x01, 0x5A, 0x09, 0x06, // 63:346
0x01, 0x63, 0x16, 0x0C, // 64:355
0x01, 0x79, 0x10, 0x08, // 65:377
0x01, 0x89, 0x0E, 0x08, // 66:393
0x01, 0x97, 0x10, 0x09, // 67:407
0x01, 0xA7, 0x10, 0x09, // 68:423
0x01, 0xB7, 0x0C, 0x07, // 69:439
0x01, 0xC3, 0x0B, 0x07, // 70:451
0x01, 0xCE, 0x12, 0x0A, // 71:462
0x01, 0xE0, 0x10, 0x09, // 72:480
0x01, 0xF0, 0x04, 0x03, // 73:496
0x01, 0xF4, 0x04, 0x03, // 74:500
0x01, 0xF8, 0x0E, 0x08, // 75:504
0x02, 0x06, 0x0C, 0x06, // 76:518
0x02, 0x12, 0x12, 0x0A, // 77:530
0x02, 0x24, 0x10, 0x09, // 78:548
0x02, 0x34, 0x12, 0x0A, // 79:564
0x02, 0x46, 0x0D, 0x08, // 80:582
0x02, 0x53, 0x12, 0x0A, // 81:595
0x02, 0x65, 0x10, 0x09, // 82:613
0x02, 0x75, 0x0E, 0x08, // 83:629
0x02, 0x83, 0x0D, 0x07, // 84:643
0x02, 0x90, 0x10, 0x09, // 85:656
0x02, 0xA0, 0x0F, 0x08, // 86:672
0x02, 0xAF, 0x15, 0x0C, // 87:687
0x02, 0xC4, 0x10, 0x08, // 88:708
0x02, 0xD4, 0x0D, 0x07, // 89:724
0x02, 0xE1, 0x10, 0x09, // 90:737
0x02, 0xF1, 0x06, 0x05, // 91:753
0x02, 0xF7, 0x08, 0x04, // 92:759
0x02, 0xFF, 0x08, 0x05, // 93:767
0x03, 0x07, 0x11, 0x0A, // 94:775
0x03, 0x18, 0x0C, 0x06, // 95:792
0x03, 0x24, 0x05, 0x06, // 96:804
0x03, 0x29, 0x0E, 0x08, // 97:809
0x03, 0x37, 0x0E, 0x08, // 98:823
0x03, 0x45, 0x0C, 0x07, // 99:837
0x03, 0x51, 0x0E, 0x08, // 100:849
0x03, 0x5F, 0x0E, 0x08, // 101:863
0x03, 0x6D, 0x07, 0x04, // 102:877
0x03, 0x74, 0x0E, 0x08, // 103:884
0x03, 0x82, 0x0C, 0x07, // 104:898
0x03, 0x8E, 0x04, 0x03, // 105:910
0x03, 0x92, 0x04, 0x03, // 106:914
0x03, 0x96, 0x0C, 0x07, // 107:918
0x03, 0xA2, 0x04, 0x03, // 108:930
0x03, 0xA6, 0x14, 0x0B, // 109:934
0x03, 0xBA, 0x0C, 0x07, // 110:954
0x03, 0xC6, 0x0E, 0x08, // 111:966
0x03, 0xD4, 0x0E, 0x08, // 112:980
0x03, 0xE2, 0x0E, 0x08, // 113:994
0x03, 0xF0, 0x09, 0x05, // 114:1008
0x03, 0xF9, 0x0C, 0x07, // 115:1017
0x04, 0x05, 0x08, 0x05, // 116:1029
0x04, 0x0D, 0x0C, 0x07, // 117:1037
0x04, 0x19, 0x0D, 0x07, // 118:1049
0x04, 0x26, 0x11, 0x0A, // 119:1062
0x04, 0x37, 0x0C, 0x07, // 120:1079
0x04, 0x43, 0x0D, 0x07, // 121:1091
0x04, 0x50, 0x0E, 0x07, // 122:1104
0x04, 0x5E, 0x0C, 0x07, // 123:1118
0x04, 0x6A, 0x06, 0x05, // 124:1130
0x04, 0x70, 0x0B, 0x07, // 125:1136
0x04, 0x7B, 0x11, 0x0A, // 126:1147
0x04, 0x8C, 0x0C, 0x07, // 127:1164
0x04, 0x98, 0x0C, 0x07, // 128:1176
0x04, 0xA4, 0x0C, 0x07, // 129:1188
0x04, 0xB0, 0x0C, 0x07, // 130:1200
0x04, 0xBC, 0x0C, 0x07, // 131:1212
0x04, 0xC8, 0x0C, 0x07, // 132:1224
0x04, 0xD4, 0x0C, 0x07, // 133:1236
0x04, 0xE0, 0x0C, 0x07, // 134:1248
0x04, 0xEC, 0x0C, 0x07, // 135:1260
0x04, 0xF8, 0x0C, 0x07, // 136:1272
0x05, 0x04, 0x0C, 0x07, // 137:1284
0x05, 0x10, 0x0C, 0x07, // 138:1296
0x05, 0x1C, 0x0C, 0x07, // 139:1308
0x05, 0x28, 0x0C, 0x07, // 140:1320
0x05, 0x34, 0x0C, 0x07, // 141:1332
0x05, 0x40, 0x0C, 0x07, // 142:1344
0x05, 0x4C, 0x0C, 0x07, // 143:1356
0x05, 0x58, 0x0C, 0x07, // 144:1368
0x05, 0x64, 0x0C, 0x07, // 145:1380
0x05, 0x70, 0x0C, 0x07, // 146:1392
0x05, 0x7C, 0x0C, 0x07, // 147:1404
0x05, 0x88, 0x0C, 0x07, // 148:1416
0x05, 0x94, 0x0C, 0x07, // 149:1428
0x05, 0xA0, 0x0C, 0x07, // 150:1440
0x05, 0xAC, 0x0C, 0x07, // 151:1452
0x05, 0xB8, 0x0C, 0x07, // 152:1464
0x05, 0xC4, 0x0C, 0x07, // 153:1476
0x05, 0xD0, 0x0C, 0x07, // 154:1488
0x05, 0xDC, 0x0C, 0x07, // 155:1500
0x05, 0xE8, 0x0C, 0x07, // 156:1512
0x05, 0xF4, 0x0C, 0x07, // 157:1524
0x06, 0x00, 0x0C, 0x07, // 158:1536
0x06, 0x0C, 0x0C, 0x07, // 159:1548
0xFF, 0xFF, 0x00, 0x04, // 160:65535
0x06, 0x18, 0x06, 0x05, // 161:1560
0x06, 0x1E, 0x0E, 0x08, // 162:1566
0x06, 0x2C, 0x0E, 0x08, // 163:1580
0x06, 0x3A, 0x0C, 0x07, // 164:1594
0x06, 0x46, 0x0C, 0x07, // 165:1606
0x06, 0x52, 0x06, 0x05, // 166:1618
0x06, 0x58, 0x0C, 0x07, // 167:1624
0x06, 0x64, 0x07, 0x05, // 168:1636
0x06, 0x6B, 0x16, 0x0D, // 169:1643
0x06, 0x81, 0x0A, 0x06, // 170:1665
0x06, 0x8B, 0x0E, 0x08, // 171:1675
0x06, 0x99, 0x12, 0x0A, // 172:1689
0x06, 0xAB, 0x08, 0x05, // 173:1707
0x06, 0xB3, 0x16, 0x0D, // 174:1715
0x06, 0xC9, 0x09, 0x06, // 175:1737
0x06, 0xD2, 0x09, 0x06, // 176:1746
0x06, 0xDB, 0x12, 0x0A, // 177:1755
0x06, 0xED, 0x08, 0x05, // 178:1773
0x06, 0xF5, 0x07, 0x05, // 179:1781
0x06, 0xFC, 0x09, 0x06, // 180:1788
0x07, 0x05, 0x0E, 0x07, // 181:1797
0x07, 0x13, 0x0C, 0x07, // 182:1811
0x07, 0x1F, 0x03, 0x03, // 183:1823
0x07, 0x22, 0x08, 0x06, // 184:1826
0x07, 0x2A, 0x07, 0x05, // 185:1834
0x07, 0x31, 0x0C, 0x07, // 186:1841
0x07, 0x3D, 0x0E, 0x07, // 187:1853
0x07, 0x4B, 0x16, 0x0B, // 188:1867
0x07, 0x61, 0x16, 0x0C, // 189:1889
0x07, 0x77, 0x16, 0x0B, // 190:1911
0x07, 0x8D, 0x0A, 0x06, // 191:1933
0x07, 0x97, 0x10, 0x08, // 192:1943
0x07, 0xA7, 0x10, 0x08, // 193:1959
0x07, 0xB7, 0x10, 0x08, // 194:1975
0x07, 0xC7, 0x10, 0x08, // 195:1991
0x07, 0xD7, 0x0E, 0x07, // 196:2007
0x07, 0xE5, 0x0E, 0x07, // 197:2021
0x07, 0xF3, 0x14, 0x0B, // 198:2035
0x08, 0x07, 0x10, 0x09, // 199:2055
0x08, 0x17, 0x0C, 0x07, // 200:2071
0x08, 0x23, 0x0C, 0x07, // 201:2083
0x08, 0x2F, 0x0C, 0x07, // 202:2095
0x08, 0x3B, 0x0C, 0x07, // 203:2107
0x08, 0x47, 0x04, 0x03, // 204:2119
0x08, 0x4B, 0x05, 0x03, // 205:2123
0x08, 0x50, 0x05, 0x03, // 206:2128
0x08, 0x55, 0x07, 0x05, // 207:2133
0x08, 0x5C, 0x10, 0x09, // 208:2140
0x08, 0x6C, 0x10, 0x09, // 209:2156
0x08, 0x7C, 0x12, 0x0A, // 210:2172
0x08, 0x8E, 0x12, 0x0A, // 211:2190
0x08, 0xA0, 0x12, 0x0A, // 212:2208
0x08, 0xB2, 0x12, 0x0A, // 213:2226
0x08, 0xC4, 0x12, 0x0A, // 214:2244
0x08, 0xD6, 0x10, 0x0A, // 215:2262
0x08, 0xE6, 0x12, 0x0A, // 216:2278
0x08, 0xF8, 0x10, 0x09, // 217:2296
0x09, 0x08, 0x10, 0x09, // 218:2312
0x09, 0x18, 0x10, 0x09, // 219:2328
0x09, 0x28, 0x10, 0x09, // 220:2344
0x09, 0x38, 0x0D, 0x07, // 221:2360
0x09, 0x45, 0x0E, 0x08, // 222:2373
0x09, 0x53, 0x0E, 0x08, // 223:2387
0x09, 0x61, 0x0E, 0x08, // 224:2401
0x09, 0x6F, 0x0E, 0x08, // 225:2415
0x09, 0x7D, 0x0E, 0x08, // 226:2429
0x09, 0x8B, 0x0E, 0x08, // 227:2443
0x09, 0x99, 0x0E, 0x08, // 228:2457
0x09, 0xA7, 0x0E, 0x08, // 229:2471
0x09, 0xB5, 0x16, 0x0C, // 230:2485
0x09, 0xCB, 0x0C, 0x07, // 231:2507
0x09, 0xD7, 0x0E, 0x08, // 232:2519
0x09, 0xE5, 0x0E, 0x08, // 233:2533
0x09, 0xF3, 0x0E, 0x08, // 234:2547
0x0A, 0x01, 0x0E, 0x08, // 235:2561
0x0A, 0x0F, 0x04, 0x03, // 236:2575
0x0A, 0x13, 0x05, 0x03, // 237:2579
0x0A, 0x18, 0x05, 0x03, // 238:2584
0x0A, 0x1D, 0x05, 0x03, // 239:2589
0x0A, 0x22, 0x0E, 0x08, // 240:2594
0x0A, 0x30, 0x0C, 0x07, // 241:2608
0x0A, 0x3C, 0x0E, 0x08, // 242:2620
0x0A, 0x4A, 0x0E, 0x08, // 243:2634
0x0A, 0x58, 0x0E, 0x08, // 244:2648
0x0A, 0x66, 0x0E, 0x08, // 245:2662
0x0A, 0x74, 0x0E, 0x08, // 246:2676
0x0A, 0x82, 0x11, 0x0A, // 247:2690
0x0A, 0x93, 0x0E, 0x08, // 248:2707
0x0A, 0xA1, 0x0C, 0x07, // 249:2721
0x0A, 0xAD, 0x0C, 0x07, // 250:2733
0x0A, 0xB9, 0x0C, 0x07, // 251:2745
0x0A, 0xC5, 0x0C, 0x07, // 252:2757
0x0A, 0xD1, 0x0D, 0x07, // 253:2769
0x0A, 0xDE, 0x0E, 0x08, // 254:2782
0x0A, 0xEC, 0x0B, 0x07, // 255:2796
// Font Data:
0x00,0x00,0x00,0x00,0xF8,0x09, // 33
0x00,0x00,0x38,0x00,0x00,0x00,0x38, // 34
0x00,0x00,0x00,0x01,0x40,0x0D,0xC0,0x03,0x78,0x01,0x40,0x0F,0xE0,0x01,0x58,0x01,0x40, // 35
0x00,0x00,0x70,0x08,0xC8,0x08,0xFC,0x1F,0x88,0x08,0x88,0x0D,0x18,0x07, // 36
0x00,0x00,0x70,0x00,0x88,0x00,0x88,0x08,0x70,0x06,0x80,0x01,0x40,0x00,0x30,0x07,0x88,0x08,0x80,0x08,0x00,0x07, // 37
0x00,0x00,0x80,0x07,0xF0,0x0C,0x48,0x08,0x88,0x09,0x08,0x0B,0x00,0x06,0x80,0x0F,0x80,0x08, // 38
0x00,0x00,0x38, // 39
0x00,0x00,0xF0,0x07,0x0C,0x18, // 40
0x00,0x00,0x00,0x00,0x1C,0x18,0xE0,0x07, // 41
0x00,0x00,0x50,0x00,0x60,0x00,0xF8,0x00,0x60,0x00,0x50, // 42
0x00,0x00,0x00,0x01,0x00,0x01,0x00,0x01,0xF0,0x0F,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01, // 43
0x00,0x10,0x00,0x0C, // 44
0x00,0x00,0x00,0x01,0x00,0x01,0x00,0x01, // 45
0x00,0x00,0x00,0x08, // 46
0x00,0x30,0x00,0x0F,0xE0,0x00,0x18, // 47
0x00,0x00,0xE0,0x03,0x18,0x0C,0x08,0x08,0x08,0x08,0x18,0x0C,0xE0,0x03, // 48
0x00,0x00,0x08,0x08,0x08,0x08,0xF8,0x0F,0x00,0x08,0x00,0x08, // 49
0x00,0x00,0x18,0x0C,0x08,0x0E,0x08,0x0B,0x88,0x08,0x70,0x08, // 50
0x00,0x0C,0x08,0x08,0x48,0x08,0x48,0x08,0xC8,0x0C,0xB0,0x07, // 51
0x00,0x00,0x00,0x03,0xC0,0x02,0x60,0x02,0x18,0x02,0xF8,0x0F,0x00,0x02, // 52
0x00,0x0C,0x78,0x08,0x48,0x08,0x48,0x08,0xC8,0x0C,0x80,0x07, // 53
0x00,0x00,0xE0,0x03,0x90,0x0C,0x48,0x08,0x48,0x08,0xC8,0x0C,0x88,0x07, // 54
0x00,0x00,0x08,0x00,0x08,0x08,0x08,0x0E,0xC8,0x03,0x78,0x00,0x18, // 55
0x00,0x00,0x70,0x07,0x88,0x09,0x88,0x08,0x88,0x08,0x88,0x09,0x70,0x07, // 56
0x00,0x00,0xF0,0x08,0x98,0x09,0x08,0x09,0x08,0x09,0x98,0x04,0xE0,0x03, // 57
0x00,0x00,0x40,0x08, // 58
0x00,0x10,0x20,0x0C, // 59
0x00,0x00,0x80,0x01,0x80,0x01,0x80,0x03,0x40,0x02,0x40,0x02,0x60,0x04,0x20,0x04,0x20,0x04, // 60
0x00,0x00,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02,0x40,0x02, // 61
0x00,0x00,0x20,0x04,0x20,0x04,0x40,0x02,0x40,0x02,0xC0,0x02,0x80,0x01,0x80,0x01,0x00,0x01, // 62
0x00,0x00,0x08,0x00,0x88,0x0B,0xC8,0x00,0x70, // 63
0x00,0x00,0xC0,0x07,0x20,0x08,0x10,0x10,0x88,0x23,0x48,0x24,0x48,0x24,0x48,0x24,0xD0,0x17,0x30,0x04,0xC0,0x03, // 64
0x00,0x08,0x00,0x0F,0xE0,0x03,0x38,0x02,0x18,0x02,0xE0,0x02,0x00,0x07,0x00,0x0C, // 65
0x00,0x00,0xF8,0x0F,0x88,0x08,0x88,0x08,0x88,0x08,0x88,0x08,0x70,0x07, // 66
0x00,0x00,0xE0,0x03,0x10,0x04,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x10,0x04, // 67
0x00,0x00,0xF8,0x0F,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x10,0x04,0xE0,0x03, // 68
0x00,0x00,0xF8,0x0F,0x88,0x08,0x88,0x08,0x88,0x08,0x88,0x08, // 69
0x00,0x00,0xF8,0x0F,0x88,0x00,0x88,0x00,0x88,0x00,0x08, // 70
0x00,0x00,0xE0,0x03,0x10,0x04,0x08,0x08,0x08,0x08,0x08,0x08,0x88,0x08,0x88,0x08,0x90,0x07, // 71
0x00,0x00,0xF8,0x0F,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0xF8,0x0F, // 72
0x00,0x00,0xF8,0x0F, // 73
0x00,0x40,0xF8,0x3F, // 74
0x00,0x00,0xF8,0x0F,0xC0,0x00,0x60,0x01,0x30,0x02,0x18,0x04,0x08,0x08, // 75
0x00,0x00,0xF8,0x0F,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08, // 76
0x00,0x00,0xF8,0x0F,0x18,0x00,0xE0,0x00,0x00,0x03,0x00,0x03,0xE0,0x00,0x18,0x00,0xF8,0x0F, // 77
0x00,0x00,0xF8,0x0F,0x18,0x00,0x60,0x00,0xC0,0x01,0x00,0x03,0x00,0x0C,0xF8,0x0F, // 78
0x00,0x00,0xE0,0x03,0x10,0x04,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x10,0x04,0xE0,0x03, // 79
0x00,0x00,0xF8,0x0F,0x88,0x00,0x88,0x00,0x88,0x00,0x88,0x00,0x70, // 80
0x00,0x00,0xE0,0x03,0x10,0x04,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x18,0x10,0x24,0xE0,0x03, // 81
0x00,0x00,0xF8,0x0F,0x88,0x00,0x88,0x00,0x88,0x00,0x88,0x01,0x70,0x07,0x00,0x0C, // 82
0x00,0x00,0x70,0x0C,0xC8,0x08,0x88,0x08,0x88,0x08,0x88,0x08,0x18,0x07, // 83
0x08,0x00,0x08,0x00,0x08,0x00,0xF8,0x0F,0x08,0x00,0x08,0x00,0x08, // 84
0x00,0x00,0xF8,0x07,0x00,0x0C,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x0C,0xF8,0x07, // 85
0x08,0x00,0x78,0x00,0xC0,0x01,0x00,0x0E,0x00,0x0E,0x80,0x03,0x70,0x00,0x18, // 86
0x00,0x00,0xF8,0x00,0x80,0x0F,0x00,0x0C,0xC0,0x03,0x38,0x00,0x78,0x00,0x80,0x07,0x00,0x0C,0xC0,0x07,0x78, // 87
0x00,0x00,0x08,0x0C,0x30,0x06,0xE0,0x01,0xC0,0x01,0x30,0x03,0x18,0x0C,0x00,0x08, // 88
0x08,0x00,0x10,0x00,0x60,0x00,0x80,0x0F,0x60,0x00,0x18,0x00,0x08, // 89
0x00,0x00,0x08,0x0C,0x08,0x0E,0x08,0x0B,0x88,0x08,0x68,0x08,0x38,0x08,0x18,0x08, // 90
0x00,0x00,0xFC,0x1F,0x04,0x10, // 91
0x18,0x00,0xE0,0x00,0x00,0x0F,0x00,0x30, // 92
0x00,0x00,0x00,0x00,0x04,0x10,0xFC,0x1F, // 93
0x00,0x00,0x40,0x00,0x20,0x00,0x30,0x00,0x18,0x00,0x08,0x00,0x10,0x00,0x20,0x00,0x40, // 94
0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40,0x00,0x40, // 95
0x00,0x00,0x02,0x00,0x0C, // 96
0x00,0x00,0x60,0x06,0x20,0x09,0x20,0x09,0x20,0x09,0x60,0x05,0xC0,0x0F, // 97
0x00,0x00,0xFC,0x0F,0x40,0x04,0x20,0x08,0x20,0x08,0x60,0x0C,0xC0,0x07, // 98
0x00,0x00,0xC0,0x07,0x60,0x0C,0x20,0x08,0x20,0x08,0x20,0x08, // 99
0x00,0x00,0xC0,0x07,0x60,0x0C,0x20,0x08,0x20,0x08,0x40,0x04,0xFC,0x0F, // 100
0x00,0x00,0xC0,0x07,0x60,0x0D,0x20,0x09,0x20,0x09,0x60,0x09,0xC0,0x09, // 101
0x20,0x00,0xF8,0x0F,0x24,0x00,0x24, // 102
0x00,0x00,0xC0,0x07,0x60,0x4C,0x20,0x48,0x20,0x48,0x40,0x64,0xE0,0x3F, // 103
0x00,0x00,0xFC,0x0F,0x40,0x00,0x20,0x00,0x20,0x00,0xC0,0x0F, // 104
0x00,0x00,0xE4,0x0F, // 105
0x00,0x40,0xE4,0x3F, // 106
0x00,0x00,0xFC,0x0F,0x00,0x01,0x80,0x02,0x40,0x04,0x20,0x08, // 107
0x00,0x00,0xFC,0x0F, // 108
0x00,0x00,0xE0,0x0F,0x40,0x00,0x20,0x00,0x20,0x00,0xC0,0x0F,0x40,0x00,0x20,0x00,0x20,0x00,0xC0,0x0F, // 109
0x00,0x00,0xE0,0x0F,0x40,0x00,0x20,0x00,0x20,0x00,0xC0,0x0F, // 110
0x00,0x00,0xC0,0x07,0x60,0x0C,0x20,0x08,0x20,0x08,0x60,0x0C,0xC0,0x07, // 111
0x00,0x00,0xE0,0x7F,0x40,0x04,0x20,0x08,0x20,0x08,0x60,0x0C,0xC0,0x07, // 112
0x00,0x00,0xC0,0x07,0x60,0x0C,0x20,0x08,0x20,0x08,0x40,0x04,0xE0,0x7F, // 113
0x00,0x00,0xE0,0x0F,0x40,0x00,0x20,0x00,0x20, // 114
0x00,0x00,0xC0,0x08,0x20,0x09,0x20,0x09,0x20,0x09,0x20,0x06, // 115
0x20,0x00,0xF8,0x0F,0x20,0x08,0x20,0x08, // 116
0x00,0x00,0xE0,0x07,0x00,0x08,0x00,0x08,0x00,0x04,0xE0,0x0F, // 117
0x00,0x00,0xE0,0x00,0x00,0x07,0x00,0x08,0x00,0x07,0xE0,0x01,0x20, // 118
0x00,0x00,0xE0,0x01,0x00,0x0E,0x00,0x0F,0xE0,0x00,0xE0,0x01,0x00,0x0E,0x00,0x0F,0xE0, // 119
0x00,0x00,0x20,0x0C,0xC0,0x06,0x80,0x01,0xC0,0x06,0x60,0x0C, // 120
0x00,0x00,0xE0,0x40,0x00,0x67,0x00,0x38,0x00,0x07,0xE0,0x00,0x20, // 121
0x00,0x00,0x20,0x0C,0x20,0x0E,0x20,0x0B,0xA0,0x08,0x60,0x08,0x20,0x08, // 122
0x00,0x00,0x80,0x00,0x80,0x00,0x7C,0x3F,0x04,0x20,0x04,0x20, // 123
0x00,0x00,0x00,0x00,0xFC,0x3F, // 124
0x00,0x00,0x04,0x20,0x04,0x20,0x7C,0x3F,0x80,0x00,0x80, // 125
0x00,0x00,0x00,0x01,0x80,0x00,0x80,0x00,0x80,0x00,0x00,0x01,0x00,0x01,0x00,0x01,0x80, // 126
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 127
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 128
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 129
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 130
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 131
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 132
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 133
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 134
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 135
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 136
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 137
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 138
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 139
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 140
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 141
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 142
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 143
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 144
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 145
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 146
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 147
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 148
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 149
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 150
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 151
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 152
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 153
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 154
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 155
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 156
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 157
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 158
0xF8,0x3F,0x08,0x20,0x08,0x20,0x08,0x20,0x08,0x20,0xF8,0x3F, // 159
0x00,0x00,0x00,0x00,0xC8,0x0F, // 161
0x00,0x00,0xC0,0x07,0x60,0x0C,0x20,0x08,0xF0,0x3F,0x20,0x08,0x20,0x08, // 162
0x00,0x00,0x80,0x08,0xF0,0x0F,0x88,0x08,0x88,0x08,0x88,0x08,0x08,0x08, // 163
0x00,0x00,0xC0,0x07,0x40,0x04,0x40,0x04,0x40,0x04,0xC0,0x07, // 164
0x00,0x00,0x58,0x01,0x60,0x01,0x80,0x0F,0x60,0x01,0x58,0x01, // 165
0x00,0x00,0x00,0x00,0x78,0x3C, // 166
0x00,0x00,0xB0,0x21,0x48,0x22,0x48,0x24,0x88,0x1C,0x00,0x03, // 167
0x00,0x00,0x04,0x00,0x00,0x00,0x04, // 168
0x00,0x00,0x00,0x00,0xE0,0x03,0x30,0x06,0xD8,0x0D,0x28,0x0A,0x28,0x0A,0x28,0x0A,0x18,0x0C,0x30,0x06,0xE0,0x03, // 169
0x00,0x00,0xE8,0x02,0xA8,0x02,0xA8,0x02,0xF0,0x02, // 170
0x00,0x00,0x00,0x01,0x80,0x02,0x40,0x05,0x80,0x01,0xC0,0x02,0x40,0x04, // 171
0x00,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x07, // 172
0x00,0x00,0x00,0x01,0x00,0x01,0x00,0x01, // 173
0x00,0x00,0x00,0x00,0xE0,0x03,0x30,0x06,0x18,0x0C,0xE8,0x0B,0xA8,0x08,0x68,0x0B,0x18,0x0C,0x30,0x06,0xE0,0x03, // 174
0x00,0x00,0x04,0x00,0x04,0x00,0x04,0x00,0x04, // 175
0x00,0x00,0x30,0x00,0x48,0x00,0x48,0x00,0x30, // 176
0x00,0x00,0x80,0x08,0x80,0x08,0x80,0x08,0xF0,0x0B,0x80,0x08,0x80,0x08,0x80,0x08,0x80,0x08, // 177
0x08,0x01,0x88,0x01,0x48,0x01,0x38,0x01, // 178
0x08,0x01,0x28,0x01,0x28,0x01,0xD8, // 179
0x00,0x00,0x00,0x00,0x08,0x00,0x04,0x00,0x02, // 180
0x00,0x00,0xE0,0x7F,0x00,0x08,0x00,0x08,0x00,0x08,0xE0,0x0F,0x00,0x08, // 181
0x20,0x00,0xF0,0x00,0xF8,0x00,0xF8,0x3F,0x08,0x00,0xF8,0x3F, // 182
0x00,0x00,0x80, // 183
0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x60, // 184
0x00,0x00,0x88,0x00,0xF8,0x00,0x80, // 185
0x00,0x00,0x70,0x02,0x88,0x02,0x88,0x02,0x88,0x02,0x70,0x02, // 186
0x00,0x00,0x40,0x06,0x80,0x02,0x40,0x05,0xC0,0x02,0x80,0x01,0x00,0x01, // 187
0x00,0x00,0x88,0x00,0xF8,0x00,0x80,0x0C,0x00,0x03,0x80,0x00,0x60,0x00,0x18,0x07,0x00,0x05,0x80,0x0F,0x00,0x04, // 188
0x00,0x00,0x88,0x00,0xF8,0x00,0x80,0x08,0x00,0x06,0x80,0x01,0x40,0x00,0xB0,0x08,0x88,0x0C,0x80,0x0A,0x80,0x09, // 189
0x88,0x00,0xA8,0x00,0xA8,0x00,0xD8,0x0C,0x00,0x03,0xC0,0x00,0x20,0x00,0x18,0x07,0x80,0x04,0x80,0x0F,0x00,0x04, // 190
0x00,0x00,0x00,0x07,0x80,0x09,0xE8,0x08,0x00,0x08, // 191
0x00,0x08,0x00,0x0F,0xE0,0x03,0x39,0x02,0x1A,0x02,0xE0,0x02,0x00,0x07,0x00,0x0C, // 192
0x00,0x08,0x00,0x0F,0xE0,0x03,0x38,0x02,0x1B,0x02,0xE1,0x02,0x00,0x07,0x00,0x0C, // 193
0x00,0x08,0x00,0x0F,0xE0,0x03,0x3A,0x02,0x1B,0x02,0xE0,0x02,0x00,0x07,0x00,0x0C, // 194
0x00,0x08,0x00,0x0F,0xE3,0x03,0x39,0x02,0x1A,0x02,0xE3,0x02,0x00,0x07,0x00,0x0C, // 195
0x00,0x0C,0x80,0x07,0xF2,0x02,0x08,0x02,0xF2,0x02,0x80,0x07,0x00,0x0C, // 196
0x00,0x0C,0x80,0x03,0x77,0x02,0x19,0x02,0x66,0x02,0x80,0x03,0x00,0x0C, // 197
0x00,0x0C,0x00,0x07,0xE0,0x03,0x38,0x02,0x08,0x02,0xF8,0x0F,0x88,0x08,0x88,0x08,0x88,0x08,0x88,0x08, // 198
0x00,0x00,0xE0,0x03,0x10,0x06,0x08,0x0C,0x08,0x4C,0x08,0x7C,0x08,0x0C,0x10,0x04, // 199
0x00,0x00,0xF8,0x0F,0x89,0x08,0x8A,0x08,0x88,0x08,0x88,0x08, // 200
0x00,0x00,0xF8,0x0F,0x88,0x08,0x8A,0x08,0x89,0x08,0x88,0x08, // 201
0x00,0x00,0xF8,0x0F,0x8A,0x08,0x89,0x08,0x8A,0x08,0x88,0x08, // 202
0x00,0x00,0xF8,0x0F,0x8A,0x08,0x88,0x08,0x8A,0x08,0x88,0x08, // 203
0x01,0x00,0xFA,0x0F, // 204
0x00,0x00,0xFA,0x0F,0x01, // 205
0x02,0x00,0xF9,0x0F,0x02, // 206
0x00,0x00,0x02,0x00,0xF8,0x0F,0x02, // 207
0x80,0x00,0xF8,0x0F,0x88,0x08,0x88,0x08,0x08,0x08,0x08,0x08,0x10,0x04,0xE0,0x03, // 208
0x00,0x00,0xF8,0x0F,0x1A,0x00,0x61,0x00,0xC3,0x01,0x02,0x03,0x01,0x0C,0xF8,0x0F, // 209
0x00,0x00,0xE0,0x03,0x10,0x04,0x08,0x08,0x09,0x08,0x0A,0x08,0x08,0x08,0x10,0x04,0xE0,0x03, // 210
0x00,0x00,0xE0,0x03,0x10,0x04,0x08,0x08,0x0A,0x08,0x09,0x08,0x08,0x08,0x10,0x04,0xE0,0x03, // 211
0x00,0x00,0xE0,0x03,0x10,0x04,0x0A,0x08,0x09,0x08,0x09,0x08,0x0A,0x08,0x10,0x04,0xE0,0x03, // 212
0x00,0x00,0xE0,0x03,0x10,0x04,0x0B,0x08,0x09,0x08,0x0A,0x08,0x0B,0x08,0x10,0x04,0xE0,0x03, // 213
0x00,0x00,0xE0,0x03,0x10,0x04,0x0A,0x08,0x08,0x08,0x08,0x08,0x0A,0x08,0x10,0x04,0xE0,0x03, // 214
0x00,0x00,0x00,0x00,0x20,0x04,0x40,0x02,0x80,0x01,0x80,0x01,0x40,0x02,0x20,0x04, // 215
0x00,0x00,0xE0,0x0B,0x10,0x04,0x08,0x0B,0x88,0x09,0xC8,0x08,0x68,0x08,0x10,0x04,0xE8,0x03, // 216
0x00,0x00,0xF8,0x07,0x00,0x0C,0x01,0x08,0x02,0x08,0x00,0x08,0x00,0x0C,0xF8,0x07, // 217
0x00,0x00,0xF8,0x07,0x00,0x0C,0x00,0x08,0x02,0x08,0x01,0x08,0x00,0x0C,0xF8,0x07, // 218
0x00,0x00,0xF8,0x07,0x00,0x0C,0x03,0x08,0x01,0x08,0x03,0x08,0x00,0x0C,0xF8,0x07, // 219
0x00,0x00,0xF8,0x07,0x00,0x0C,0x02,0x08,0x00,0x08,0x02,0x08,0x00,0x0C,0xF8,0x07, // 220
0x08,0x00,0x10,0x00,0x60,0x00,0x82,0x0F,0x60,0x00,0x18,0x00,0x08, // 221
0x00,0x00,0xF8,0x0F,0x20,0x02,0x20,0x02,0x20,0x02,0x20,0x02,0xC0,0x01, // 222
0x00,0x00,0xF8,0x0F,0x04,0x00,0xE4,0x08,0x94,0x08,0x18,0x09,0x00,0x06, // 223
0x00,0x00,0x60,0x06,0x24,0x09,0x28,0x09,0x30,0x09,0x60,0x05,0xC0,0x0F, // 224
0x00,0x00,0x60,0x06,0x20,0x09,0x30,0x09,0x28,0x09,0x64,0x05,0xC0,0x0F, // 225
0x00,0x00,0x60,0x06,0x38,0x09,0x24,0x09,0x2C,0x09,0x70,0x05,0xC0,0x0F, // 226
0x00,0x00,0x60,0x06,0x2C,0x09,0x24,0x09,0x28,0x09,0x6C,0x05,0xC0,0x0F, // 227
0x00,0x00,0x60,0x06,0x24,0x09,0x20,0x09,0x24,0x09,0x60,0x05,0xC0,0x0F, // 228
0x00,0x00,0x60,0x06,0x24,0x09,0x2A,0x09,0x2A,0x09,0x64,0x05,0xC0,0x0F, // 229
0x00,0x00,0x20,0x07,0xA0,0x08,0xA0,0x08,0xA0,0x0C,0xC0,0x07,0x60,0x0D,0x20,0x09,0x20,0x09,0x60,0x09,0xC0,0x09, // 230
0x00,0x00,0xC0,0x07,0x60,0x0C,0x20,0x4C,0x20,0x7C,0x20,0x04, // 231
0x00,0x00,0xC0,0x07,0x64,0x0D,0x2C,0x09,0x20,0x09,0x60,0x09,0xC0,0x09, // 232
0x00,0x00,0xC0,0x07,0x60,0x0D,0x20,0x09,0x2C,0x09,0x64,0x09,0xC0,0x09, // 233
0x00,0x00,0xC0,0x07,0x68,0x0D,0x24,0x09,0x24,0x09,0x68,0x09,0xC0,0x09, // 234
0x00,0x00,0xC0,0x07,0x60,0x0D,0x24,0x09,0x20,0x09,0x64,0x09,0xC0,0x09, // 235
0x04,0x00,0xF8,0x0F, // 236
0x00,0x00,0xF8,0x0F,0x04, // 237
0x08,0x00,0xE4,0x0F,0x08, // 238
0x04,0x00,0xE0,0x0F,0x04, // 239
0x00,0x00,0xC0,0x07,0x74,0x0C,0x2C,0x08,0x38,0x08,0x24,0x0C,0xC0,0x07, // 240
0x00,0x00,0xE0,0x0F,0x4C,0x00,0x2C,0x00,0x2C,0x00,0xC0,0x0F, // 241
0x00,0x00,0xC0,0x07,0x64,0x0C,0x2C,0x08,0x20,0x08,0x60,0x0C,0xC0,0x07, // 242
0x00,0x00,0xC0,0x07,0x60,0x0C,0x20,0x08,0x2C,0x08,0x64,0x0C,0xC0,0x07, // 243
0x00,0x00,0xC0,0x07,0x68,0x0C,0x24,0x08,0x24,0x08,0x68,0x0C,0xC0,0x07, // 244
0x00,0x00,0xC0,0x07,0x6C,0x0C,0x24,0x08,0x28,0x08,0x6C,0x0C,0xC0,0x07, // 245
0x00,0x00,0xC0,0x07,0x64,0x0C,0x20,0x08,0x20,0x08,0x64,0x0C,0xC0,0x07, // 246
0x00,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0xA0,0x02,0x80,0x00,0x80,0x00,0x80,0x00,0x80, // 247
0x00,0x00,0xC0,0x0F,0x60,0x0C,0x20,0x0B,0xA0,0x08,0x60,0x0C,0xE0,0x07, // 248
0x00,0x00,0xE0,0x07,0x04,0x08,0x18,0x08,0x00,0x04,0xE0,0x0F, // 249
0x00,0x00,0xE0,0x07,0x00,0x08,0x18,0x08,0x04,0x04,0xE0,0x0F, // 250
0x00,0x00,0xE0,0x07,0x18,0x08,0x04,0x08,0x18,0x04,0xE0,0x0F, // 251
0x00,0x00,0xE0,0x07,0x04,0x08,0x00,0x08,0x04,0x04,0xE0,0x0F, // 252
0x00,0x00,0xE0,0x40,0x00,0x67,0x10,0x38,0x0C,0x07,0xE4,0x01,0x20, // 253
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
+831
View File
@@ -0,0 +1,831 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#include "OLEDDisplay.h"
OLEDDisplay::~OLEDDisplay() {
end();
}
bool OLEDDisplay::init() {
if (!this->connect()) {
DEBUG_OLEDDISPLAY("[OLEDDISPLAY][init] Can't establish connection to display\n");
return false;
}
if(this->buffer==NULL) {
this->buffer = (uint8_t*) malloc(sizeof(uint8_t) * DISPLAY_BUFFER_SIZE);
if(!this->buffer) {
DEBUG_OLEDDISPLAY("[OLEDDISPLAY][init] Not enough memory to create display\n");
return false;
}
}
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
if(this->buffer_back==NULL) {
this->buffer_back = (uint8_t*) malloc(sizeof(uint8_t) * DISPLAY_BUFFER_SIZE);
if(!this->buffer_back) {
DEBUG_OLEDDISPLAY("[OLEDDISPLAY][init] Not enough memory to create back buffer\n");
free(this->buffer);
return false;
}
}
#endif
sendInitCommands();
resetDisplay();
return true;
}
void OLEDDisplay::end() {
if (this->buffer) { free(this->buffer); this->buffer = NULL; }
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
if (this->buffer_back) { free(this->buffer_back); this->buffer_back = NULL; }
#endif
if (this->logBuffer != NULL) { free(this->logBuffer); this->logBuffer = NULL; }
}
void OLEDDisplay::resetDisplay(void) {
clear();
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
memset(buffer_back, 1, DISPLAY_BUFFER_SIZE);
#endif
display();
}
void OLEDDisplay::setColor(OLEDDISPLAY_COLOR color) {
this->color = color;
}
void OLEDDisplay::setPixel(int16_t x, int16_t y) {
if (x >= 0 && x < this->width() && y >= 0 && y < this->height()) {
switch (color) {
case WHITE: buffer[x + (y / 8) * this->width()] |= (1 << (y & 7)); break;
case BLACK: buffer[x + (y / 8) * this->width()] &= ~(1 << (y & 7)); break;
case INVERSE: buffer[x + (y / 8) * this->width()] ^= (1 << (y & 7)); break;
}
}
}
// Bresenham's algorithm - thx wikipedia and Adafruit_GFX
void OLEDDisplay::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1) {
int16_t steep = abs(y1 - y0) > abs(x1 - x0);
if (steep) {
_swap_int16_t(x0, y0);
_swap_int16_t(x1, y1);
}
if (x0 > x1) {
_swap_int16_t(x0, x1);
_swap_int16_t(y0, y1);
}
int16_t dx, dy;
dx = x1 - x0;
dy = abs(y1 - y0);
int16_t err = dx / 2;
int16_t ystep;
if (y0 < y1) {
ystep = 1;
} else {
ystep = -1;
}
for (; x0<=x1; x0++) {
if (steep) {
setPixel(y0, x0);
} else {
setPixel(x0, y0);
}
err -= dy;
if (err < 0) {
y0 += ystep;
err += dx;
}
}
}
void OLEDDisplay::drawRect(int16_t x, int16_t y, int16_t width, int16_t height) {
drawHorizontalLine(x, y, width);
drawVerticalLine(x, y, height);
drawVerticalLine(x + width - 1, y, height);
drawHorizontalLine(x, y + height - 1, width);
}
void OLEDDisplay::fillRect(int16_t xMove, int16_t yMove, int16_t width, int16_t height) {
for (int16_t x = xMove; x < xMove + width; x++) {
drawVerticalLine(x, yMove, height);
}
}
void OLEDDisplay::drawCircle(int16_t x0, int16_t y0, int16_t radius) {
int16_t x = 0, y = radius;
int16_t dp = 1 - radius;
do {
if (dp < 0)
dp = dp + 2 * (++x) + 3;
else
dp = dp + 2 * (++x) - 2 * (--y) + 5;
setPixel(x0 + x, y0 + y); //For the 8 octants
setPixel(x0 - x, y0 + y);
setPixel(x0 + x, y0 - y);
setPixel(x0 - x, y0 - y);
setPixel(x0 + y, y0 + x);
setPixel(x0 - y, y0 + x);
setPixel(x0 + y, y0 - x);
setPixel(x0 - y, y0 - x);
} while (x < y);
setPixel(x0 + radius, y0);
setPixel(x0, y0 + radius);
setPixel(x0 - radius, y0);
setPixel(x0, y0 - radius);
}
void OLEDDisplay::drawCircleQuads(int16_t x0, int16_t y0, int16_t radius, uint8_t quads) {
int16_t x = 0, y = radius;
int16_t dp = 1 - radius;
while (x < y) {
if (dp < 0)
dp = dp + 2 * (++x) + 3;
else
dp = dp + 2 * (++x) - 2 * (--y) + 5;
if (quads & 0x1) {
setPixel(x0 + x, y0 - y);
setPixel(x0 + y, y0 - x);
}
if (quads & 0x2) {
setPixel(x0 - y, y0 - x);
setPixel(x0 - x, y0 - y);
}
if (quads & 0x4) {
setPixel(x0 - y, y0 + x);
setPixel(x0 - x, y0 + y);
}
if (quads & 0x8) {
setPixel(x0 + x, y0 + y);
setPixel(x0 + y, y0 + x);
}
}
if (quads & 0x1 && quads & 0x8) {
setPixel(x0 + radius, y0);
}
if (quads & 0x4 && quads & 0x8) {
setPixel(x0, y0 + radius);
}
if (quads & 0x2 && quads & 0x4) {
setPixel(x0 - radius, y0);
}
if (quads & 0x1 && quads & 0x2) {
setPixel(x0, y0 - radius);
}
}
void OLEDDisplay::fillCircle(int16_t x0, int16_t y0, int16_t radius) {
int16_t x = 0, y = radius;
int16_t dp = 1 - radius;
do {
if (dp < 0)
dp = dp + 2 * (++x) + 3;
else
dp = dp + 2 * (++x) - 2 * (--y) + 5;
drawHorizontalLine(x0 - x, y0 - y, 2*x);
drawHorizontalLine(x0 - x, y0 + y, 2*x);
drawHorizontalLine(x0 - y, y0 - x, 2*y);
drawHorizontalLine(x0 - y, y0 + x, 2*y);
} while (x < y);
drawHorizontalLine(x0 - radius, y0, 2 * radius);
}
void OLEDDisplay::drawHorizontalLine(int16_t x, int16_t y, int16_t length) {
if (y < 0 || y >= this->height()) { return; }
if (x < 0) {
length += x;
x = 0;
}
if ( (x + length) > this->width()) {
length = (this->width() - x);
}
if (length <= 0) { return; }
uint8_t * bufferPtr = buffer;
bufferPtr += (y >> 3) * this->width();
bufferPtr += x;
uint8_t drawBit = 1 << (y & 7);
switch (color) {
case WHITE: while (length--) {
*bufferPtr++ |= drawBit;
}; break;
case BLACK: drawBit = ~drawBit; while (length--) {
*bufferPtr++ &= drawBit;
}; break;
case INVERSE: while (length--) {
*bufferPtr++ ^= drawBit;
}; break;
}
}
void OLEDDisplay::drawVerticalLine(int16_t x, int16_t y, int16_t length) {
if (x < 0 || x >= this->width()) return;
if (y < 0) {
length += y;
y = 0;
}
if ( (y + length) > this->height()) {
length = (this->height() - y);
}
if (length <= 0) return;
uint8_t yOffset = y & 7;
uint8_t drawBit;
uint8_t *bufferPtr = buffer;
bufferPtr += (y >> 3) * this->width();
bufferPtr += x;
if (yOffset) {
yOffset = 8 - yOffset;
drawBit = ~(0xFF >> (yOffset));
if (length < yOffset) {
drawBit &= (0xFF >> (yOffset - length));
}
switch (color) {
case WHITE: *bufferPtr |= drawBit; break;
case BLACK: *bufferPtr &= ~drawBit; break;
case INVERSE: *bufferPtr ^= drawBit; break;
}
if (length < yOffset) return;
length -= yOffset;
bufferPtr += this->width();
}
if (length >= 8) {
switch (color) {
case WHITE:
case BLACK:
drawBit = (color == WHITE) ? 0xFF : 0x00;
do {
*bufferPtr = drawBit;
bufferPtr += this->width();
length -= 8;
} while (length >= 8);
break;
case INVERSE:
do {
*bufferPtr = ~(*bufferPtr);
bufferPtr += this->width();
length -= 8;
} while (length >= 8);
break;
}
}
if (length > 0) {
drawBit = (1 << (length & 7)) - 1;
switch (color) {
case WHITE: *bufferPtr |= drawBit; break;
case BLACK: *bufferPtr &= ~drawBit; break;
case INVERSE: *bufferPtr ^= drawBit; break;
}
}
}
void OLEDDisplay::drawProgressBar(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint8_t progress) {
uint16_t radius = height / 2;
uint16_t xRadius = x + radius;
uint16_t yRadius = y + radius;
uint16_t doubleRadius = 2 * radius;
uint16_t innerRadius = radius - 2;
setColor(WHITE);
drawCircleQuads(xRadius, yRadius, radius, 0b00000110);
drawHorizontalLine(xRadius, y, width - doubleRadius + 1);
drawHorizontalLine(xRadius, y + height, width - doubleRadius + 1);
drawCircleQuads(x + width - radius, yRadius, radius, 0b00001001);
uint16_t maxProgressWidth = (width - doubleRadius + 1) * progress / 100;
fillCircle(xRadius, yRadius, innerRadius);
fillRect(xRadius + 1, y + 2, maxProgressWidth, height - 3);
fillCircle(xRadius + maxProgressWidth, yRadius, innerRadius);
}
void OLEDDisplay::drawFastImage(int16_t xMove, int16_t yMove, int16_t width, int16_t height, const char *image) {
drawInternal(xMove, yMove, width, height, image, 0, 0);
}
void OLEDDisplay::drawXbm(int16_t xMove, int16_t yMove, int16_t width, int16_t height, const char *xbm) {
int16_t widthInXbm = (width + 7) / 8;
uint8_t data = 0;
for(int16_t y = 0; y < height; y++) {
for(int16_t x = 0; x < width; x++ ) {
if (x & 7) {
data >>= 1; // Move a bit
} else { // Read new data every 8 bit
data = pgm_read_byte(xbm + (x / 8) + y * widthInXbm);
}
// if there is a bit draw it
if (data & 0x01) {
setPixel(xMove + x, yMove + y);
}
}
}
}
void OLEDDisplay::drawStringInternal(int16_t xMove, int16_t yMove, char* text, uint16_t textLength, uint16_t textWidth) {
uint8_t textHeight = pgm_read_byte(fontData + HEIGHT_POS);
uint8_t firstChar = pgm_read_byte(fontData + FIRST_CHAR_POS);
uint16_t sizeOfJumpTable = pgm_read_byte(fontData + CHAR_NUM_POS) * JUMPTABLE_BYTES;
uint8_t cursorX = 0;
uint8_t cursorY = 0;
switch (textAlignment) {
case TEXT_ALIGN_CENTER_BOTH:
yMove -= textHeight >> 1;
// Fallthrough
case TEXT_ALIGN_CENTER:
xMove -= textWidth >> 1; // divide by 2
break;
case TEXT_ALIGN_RIGHT:
xMove -= textWidth;
break;
case TEXT_ALIGN_LEFT:
break;
}
// Don't draw anything if it is not on the screen.
if (xMove + textWidth < 0 || xMove > this->width() ) {return;}
if (yMove + textHeight < 0 || yMove > this->width() ) {return;}
for (uint16_t j = 0; j < textLength; j++) {
int16_t xPos = xMove + cursorX;
int16_t yPos = yMove + cursorY;
byte code = text[j];
if (code >= firstChar) {
byte charCode = code - firstChar;
// 4 Bytes per char code
byte msbJumpToChar = pgm_read_byte( fontData + JUMPTABLE_START + charCode * JUMPTABLE_BYTES ); // MSB \ JumpAddress
byte lsbJumpToChar = pgm_read_byte( fontData + JUMPTABLE_START + charCode * JUMPTABLE_BYTES + JUMPTABLE_LSB); // LSB /
byte charByteSize = pgm_read_byte( fontData + JUMPTABLE_START + charCode * JUMPTABLE_BYTES + JUMPTABLE_SIZE); // Size
byte currentCharWidth = pgm_read_byte( fontData + JUMPTABLE_START + charCode * JUMPTABLE_BYTES + JUMPTABLE_WIDTH); // Width
// Test if the char is drawable
if (!(msbJumpToChar == 255 && lsbJumpToChar == 255)) {
// Get the position of the char data
uint16_t charDataPosition = JUMPTABLE_START + sizeOfJumpTable + ((msbJumpToChar << 8) + lsbJumpToChar);
drawInternal(xPos, yPos, currentCharWidth, textHeight, fontData, charDataPosition, charByteSize);
}
cursorX += currentCharWidth;
}
}
}
void OLEDDisplay::drawString(int16_t xMove, int16_t yMove, String strUser) {
uint16_t lineHeight = pgm_read_byte(fontData + HEIGHT_POS);
// char* text must be freed!
char* text = utf8ascii(strUser);
uint16_t yOffset = 0;
// If the string should be centered vertically too
// we need to now how heigh the string is.
if (textAlignment == TEXT_ALIGN_CENTER_BOTH) {
uint16_t lb = 0;
// Find number of linebreaks in text
for (uint16_t i=0;text[i] != 0; i++) {
lb += (text[i] == 10);
}
// Calculate center
yOffset = (lb * lineHeight) / 2;
}
uint16_t line = 0;
char* textPart = strtok(text,"\n");
while (textPart != NULL) {
uint16_t length = strlen(textPart);
drawStringInternal(xMove, yMove - yOffset + (line++) * lineHeight, textPart, length, getStringWidth(textPart, length));
textPart = strtok(NULL, "\n");
}
free(text);
}
void OLEDDisplay::drawStringMaxWidth(int16_t xMove, int16_t yMove, uint16_t maxLineWidth, String strUser) {
uint16_t firstChar = pgm_read_byte(fontData + FIRST_CHAR_POS);
uint16_t lineHeight = pgm_read_byte(fontData + HEIGHT_POS);
char* text = utf8ascii(strUser);
uint16_t length = strlen(text);
uint16_t lastDrawnPos = 0;
uint16_t lineNumber = 0;
uint16_t strWidth = 0;
uint16_t preferredBreakpoint = 0;
uint16_t widthAtBreakpoint = 0;
for (uint16_t i = 0; i < length; i++) {
strWidth += pgm_read_byte(fontData + JUMPTABLE_START + (text[i] - firstChar) * JUMPTABLE_BYTES + JUMPTABLE_WIDTH);
// Always try to break on a space or dash
if (text[i] == ' ' || text[i]== '-') {
preferredBreakpoint = i;
widthAtBreakpoint = strWidth;
}
if (strWidth >= maxLineWidth) {
if (preferredBreakpoint == 0) {
preferredBreakpoint = i;
widthAtBreakpoint = strWidth;
}
drawStringInternal(xMove, yMove + (lineNumber++) * lineHeight , &text[lastDrawnPos], preferredBreakpoint - lastDrawnPos, widthAtBreakpoint);
lastDrawnPos = preferredBreakpoint + 1;
// It is possible that we did not draw all letters to i so we need
// to account for the width of the chars from `i - preferredBreakpoint`
// by calculating the width we did not draw yet.
strWidth = strWidth - widthAtBreakpoint;
preferredBreakpoint = 0;
}
}
// Draw last part if needed
if (lastDrawnPos < length) {
drawStringInternal(xMove, yMove + lineNumber * lineHeight , &text[lastDrawnPos], length - lastDrawnPos, getStringWidth(&text[lastDrawnPos], length - lastDrawnPos));
}
free(text);
}
uint16_t OLEDDisplay::getStringWidth(const char* text, uint16_t length) {
uint16_t firstChar = pgm_read_byte(fontData + FIRST_CHAR_POS);
uint16_t stringWidth = 0;
uint16_t maxWidth = 0;
while (length--) {
stringWidth += pgm_read_byte(fontData + JUMPTABLE_START + (text[length] - firstChar) * JUMPTABLE_BYTES + JUMPTABLE_WIDTH);
if (text[length] == 10) {
maxWidth = max(maxWidth, stringWidth);
stringWidth = 0;
}
}
return max(maxWidth, stringWidth);
}
uint16_t OLEDDisplay::getStringWidth(String strUser) {
char* text = utf8ascii(strUser);
uint16_t length = strlen(text);
uint16_t width = getStringWidth(text, length);
free(text);
return width;
}
void OLEDDisplay::setTextAlignment(OLEDDISPLAY_TEXT_ALIGNMENT textAlignment) {
this->textAlignment = textAlignment;
}
void OLEDDisplay::setFont(const char *fontData) {
this->fontData = fontData;
}
void OLEDDisplay::displayOn(void) {
sendCommand(DISPLAYON);
}
void OLEDDisplay::displayOff(void) {
sendCommand(DISPLAYOFF);
}
void OLEDDisplay::invertDisplay(void) {
sendCommand(INVERTDISPLAY);
}
void OLEDDisplay::normalDisplay(void) {
sendCommand(NORMALDISPLAY);
}
void OLEDDisplay::setContrast(char contrast, char precharge, char comdetect) {
sendCommand(SETPRECHARGE); //0xD9
sendCommand(precharge); //0xF1 default, to lower the contrast, put 1-1F
sendCommand(SETCONTRAST);
sendCommand(contrast); // 0-255
sendCommand(SETVCOMDETECT); //0xDB, (additionally needed to lower the contrast)
sendCommand(comdetect); //0x40 default, to lower the contrast, put 0
sendCommand(DISPLAYALLON_RESUME);
sendCommand(NORMALDISPLAY);
sendCommand(DISPLAYON);
}
void OLEDDisplay::flipScreenVertically() {
sendCommand(SEGREMAP | 0x01);
sendCommand(COMSCANDEC); //Rotate screen 180 Deg
}
void OLEDDisplay::clear(void) {
memset(buffer, 0, DISPLAY_BUFFER_SIZE);
}
void OLEDDisplay::drawLogBuffer(uint16_t xMove, uint16_t yMove) {
uint16_t lineHeight = pgm_read_byte(fontData + HEIGHT_POS);
// Always align left
setTextAlignment(TEXT_ALIGN_LEFT);
// State values
uint16_t length = 0;
uint16_t line = 0;
uint16_t lastPos = 0;
for (uint16_t i=0;i<this->logBufferFilled;i++){
// Everytime we have a \n print
if (this->logBuffer[i] == 10) {
length++;
// Draw string on line `line` from lastPos to length
// Passing 0 as the lenght because we are in TEXT_ALIGN_LEFT
drawStringInternal(xMove, yMove + (line++) * lineHeight, &this->logBuffer[lastPos], length, 0);
// Remember last pos
lastPos = i;
// Reset length
length = 0;
} else {
// Count chars until next linebreak
length++;
}
}
// Draw the remaining string
if (length > 0) {
drawStringInternal(xMove, yMove + line * lineHeight, &this->logBuffer[lastPos], length, 0);
}
}
bool OLEDDisplay::setLogBuffer(uint16_t lines, uint16_t chars){
if (logBuffer != NULL) free(logBuffer);
uint16_t size = lines * chars;
if (size > 0) {
this->logBufferLine = 0; // Lines printed
this->logBufferFilled = 0; // Nothing stored yet
this->logBufferMaxLines = lines; // Lines max printable
this->logBufferSize = size; // Total number of characters the buffer can hold
this->logBuffer = (char *) malloc(size * sizeof(uint8_t));
if(!this->logBuffer) {
DEBUG_OLEDDISPLAY("[OLEDDISPLAY][setLogBuffer] Not enough memory to create log buffer\n");
return false;
}
}
return true;
}
size_t OLEDDisplay::write(uint8_t c) {
if (this->logBufferSize > 0) {
// Don't waste space on \r\n line endings, dropping \r
if (c == 13) return 1;
bool maxLineNotReached = this->logBufferLine < this->logBufferMaxLines;
bool bufferNotFull = this->logBufferFilled < this->logBufferSize;
// Can we write to the buffer?
if (bufferNotFull && maxLineNotReached) {
this->logBuffer[logBufferFilled] = utf8ascii(c);
this->logBufferFilled++;
// Keep track of lines written
if (c == 10) this->logBufferLine++;
} else {
// Max line number is reached
if (!maxLineNotReached) this->logBufferLine--;
// Find the end of the first line
uint16_t firstLineEnd = 0;
for (uint16_t i=0;i<this->logBufferFilled;i++) {
if (this->logBuffer[i] == 10){
// Include last char too
firstLineEnd = i + 1;
break;
}
}
// If there was a line ending
if (firstLineEnd > 0) {
// Calculate the new logBufferFilled value
this->logBufferFilled = logBufferFilled - firstLineEnd;
// Now we move the lines infront of the buffer
memcpy(this->logBuffer, &this->logBuffer[firstLineEnd], logBufferFilled);
} else {
// Let's reuse the buffer if it was full
if (!bufferNotFull) {
this->logBufferFilled = 0;
}// else {
// Nothing to do here
//}
}
write(c);
}
}
// We are always writing all uint8_t to the buffer
return 1;
}
size_t OLEDDisplay::write(const char* str) {
if (str == NULL) return 0;
size_t length = strlen(str);
for (size_t i = 0; i < length; i++) {
write(str[i]);
}
return length;
}
// Private functions
void OLEDDisplay::sendInitCommands(void) {
sendCommand(DISPLAYOFF);
sendCommand(SETDISPLAYCLOCKDIV);
sendCommand(0xF0); // Increase speed of the display max ~96Hz
sendCommand(SETMULTIPLEX);
sendCommand(this->height() - 1);
sendCommand(SETDISPLAYOFFSET);
sendCommand(0x00);
sendCommand(SETSTARTLINE);
sendCommand(CHARGEPUMP);
sendCommand(0x14);
sendCommand(MEMORYMODE);
sendCommand(0x00);
sendCommand(SEGREMAP);
sendCommand(COMSCANINC);
sendCommand(SETCOMPINS);
sendCommand(0x12); // according to the adafruit lib, sometimes this may need to be 0x02
sendCommand(SETCONTRAST);
sendCommand(0xCF);
sendCommand(SETPRECHARGE);
sendCommand(0xF1);
sendCommand(SETVCOMDETECT); //0xDB, (additionally needed to lower the contrast)
sendCommand(0x40); //0x40 default, to lower the contrast, put 0
sendCommand(DISPLAYALLON_RESUME);
sendCommand(NORMALDISPLAY);
sendCommand(0x2e); // stop scroll
sendCommand(DISPLAYON);
}
void inline OLEDDisplay::drawInternal(int16_t xMove, int16_t yMove, int16_t width, int16_t height, const char *data, uint16_t offset, uint16_t bytesInData) {
if (width < 0 || height < 0) return;
if (yMove + height < 0 || yMove > this->height()) return;
if (xMove + width < 0 || xMove > this->width()) return;
uint8_t rasterHeight = 1 + ((height - 1) >> 3); // fast ceil(height / 8.0)
int8_t yOffset = yMove & 7;
bytesInData = bytesInData == 0 ? width * rasterHeight : bytesInData;
int16_t initYMove = yMove;
int8_t initYOffset = yOffset;
for (uint16_t i = 0; i < bytesInData; i++) {
// Reset if next horizontal drawing phase is started.
if ( i % rasterHeight == 0) {
yMove = initYMove;
yOffset = initYOffset;
}
byte currentByte = pgm_read_byte(data + offset + i);
int16_t xPos = xMove + (i / rasterHeight);
int16_t yPos = ((yMove >> 3) + (i % rasterHeight)) * this->width();
// int16_t yScreenPos = yMove + yOffset;
int16_t dataPos = xPos + yPos;
if (dataPos >= 0 && dataPos < DISPLAY_BUFFER_SIZE &&
xPos >= 0 && xPos < this->width() ) {
if (yOffset >= 0) {
switch (this->color) {
case WHITE: buffer[dataPos] |= currentByte << yOffset; break;
case BLACK: buffer[dataPos] &= ~(currentByte << yOffset); break;
case INVERSE: buffer[dataPos] ^= currentByte << yOffset; break;
}
if (dataPos < (DISPLAY_BUFFER_SIZE - this->width())) {
switch (this->color) {
case WHITE: buffer[dataPos + this->width()] |= currentByte >> (8 - yOffset); break;
case BLACK: buffer[dataPos + this->width()] &= ~(currentByte >> (8 - yOffset)); break;
case INVERSE: buffer[dataPos + this->width()] ^= currentByte >> (8 - yOffset); break;
}
}
} else {
// Make new offset position
yOffset = -yOffset;
switch (this->color) {
case WHITE: buffer[dataPos] |= currentByte >> yOffset; break;
case BLACK: buffer[dataPos] &= ~(currentByte >> yOffset); break;
case INVERSE: buffer[dataPos] ^= currentByte >> yOffset; break;
}
// Prepare for next iteration by moving one block up
yMove -= 8;
// and setting the new yOffset
yOffset = 8 - yOffset;
}
yield();
}
}
}
// Code form http://playground.arduino.cc/Main/Utf8ascii
uint8_t OLEDDisplay::utf8ascii(byte ascii) {
static uint8_t LASTCHAR;
if ( ascii < 128 ) { // Standard ASCII-set 0..0x7F handling
LASTCHAR = 0;
return ascii;
}
uint8_t last = LASTCHAR; // get last char
LASTCHAR = ascii;
switch (last) { // conversion depnding on first UTF8-character
case 0xC2: return (ascii); break;
case 0xC3: return (ascii | 0xC0); break;
case 0x82: if (ascii == 0xAC) return (0x80); // special case Euro-symbol
}
return 0; // otherwise: return zero, if character has to be ignored
}
// You need to free the char!
char* OLEDDisplay::utf8ascii(String str) {
uint16_t k = 0;
uint16_t length = str.length() + 1;
// Copy the string into a char array
char* s = (char*) malloc(length * sizeof(char));
if(!s) {
DEBUG_OLEDDISPLAY("[OLEDDISPLAY][utf8ascii] Can't allocate another char array. Drop support for UTF-8.\n");
return (char*) str.c_str();
}
str.toCharArray(s, length);
length--;
for (uint16_t i=0; i < length; i++) {
char c = utf8ascii(s[i]);
if (c!=0) {
s[k++]=c;
}
}
s[k]=0;
// This will leak 's' be sure to free it in the calling function.
return s;
}
+283
View File
@@ -0,0 +1,283 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#ifndef OLEDDISPLAY_h
#define OLEDDISPLAY_h
#include <Arduino.h>
#include "OLEDDisplayFonts.h"
//#define DEBUG_OLEDDISPLAY(...) Serial.printf( __VA_ARGS__ )
#ifndef DEBUG_OLEDDISPLAY
#define DEBUG_OLEDDISPLAY(...)
#endif
// Use DOUBLE BUFFERING by default
#ifndef OLEDDISPLAY_REDUCE_MEMORY
#define OLEDDISPLAY_DOUBLE_BUFFER
#endif
// Display settings
#ifndef DISPLAY_WIDTH
#define DISPLAY_WIDTH 128
#endif
#ifndef DISPLAY_HEIGHT
#define DISPLAY_HEIGHT 64
#endif
#define DISPLAY_BUFFER_SIZE DISPLAY_WIDTH * DISPLAY_HEIGHT / 8
// Header Values
#define JUMPTABLE_BYTES 4
#define JUMPTABLE_LSB 1
#define JUMPTABLE_SIZE 2
#define JUMPTABLE_WIDTH 3
#define JUMPTABLE_START 4
#define WIDTH_POS 0
#define HEIGHT_POS 1
#define FIRST_CHAR_POS 2
#define CHAR_NUM_POS 3
// Display commands
#define CHARGEPUMP 0x8D
#define COLUMNADDR 0x21
#define COMSCANDEC 0xC8
#define COMSCANINC 0xC0
#define DISPLAYALLON 0xA5
#define DISPLAYALLON_RESUME 0xA4
#define DISPLAYOFF 0xAE
#define DISPLAYON 0xAF
#define EXTERNALVCC 0x1
#define INVERTDISPLAY 0xA7
#define MEMORYMODE 0x20
#define NORMALDISPLAY 0xA6
#define PAGEADDR 0x22
#define SEGREMAP 0xA0
#define SETCOMPINS 0xDA
#define SETCONTRAST 0x81
#define SETDISPLAYCLOCKDIV 0xD5
#define SETDISPLAYOFFSET 0xD3
#define SETHIGHCOLUMN 0x10
#define SETLOWCOLUMN 0x00
#define SETMULTIPLEX 0xA8
#define SETPRECHARGE 0xD9
#define SETSEGMENTREMAP 0xA1
#define SETSTARTLINE 0x40
#define SETVCOMDETECT 0xDB
#define SWITCHCAPVCC 0x2
#ifndef _swap_int16_t
#define _swap_int16_t(a, b) { int16_t t = a; a = b; b = t; }
#endif
enum OLEDDISPLAY_COLOR {
BLACK = 0,
WHITE = 1,
INVERSE = 2
};
enum OLEDDISPLAY_TEXT_ALIGNMENT {
TEXT_ALIGN_LEFT = 0,
TEXT_ALIGN_RIGHT = 1,
TEXT_ALIGN_CENTER = 2,
TEXT_ALIGN_CENTER_BOTH = 3
};
class OLEDDisplay : public Print {
private:
const int _width, _height;
public:
OLEDDisplay(const int width = DISPLAY_WIDTH, const int height = DISPLAY_HEIGHT) : _width(width), _height(height){ };
virtual ~OLEDDisplay();
const int width(void) const { return _width; };
const int height(void) const { return _height; };
// Initialize the display
bool init();
// Free the memory used by the display
void end();
// Cycle through the initialization
void resetDisplay(void);
/* Drawing functions */
// Sets the color of all pixel operations
void setColor(OLEDDISPLAY_COLOR color);
// Draw a pixel at given position
void setPixel(int16_t x, int16_t y);
// Draw a line from position 0 to position 1
void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1);
// Draw the border of a rectangle at the given location
void drawRect(int16_t x, int16_t y, int16_t width, int16_t height);
// Fill the rectangle
void fillRect(int16_t x, int16_t y, int16_t width, int16_t height);
// Draw the border of a circle
void drawCircle(int16_t x, int16_t y, int16_t radius);
// Draw all Quadrants specified in the quads bit mask
void drawCircleQuads(int16_t x0, int16_t y0, int16_t radius, uint8_t quads);
// Fill circle
void fillCircle(int16_t x, int16_t y, int16_t radius);
// Draw a line horizontally
void drawHorizontalLine(int16_t x, int16_t y, int16_t length);
// Draw a lin vertically
void drawVerticalLine(int16_t x, int16_t y, int16_t length);
// Draws a rounded progress bar with the outer dimensions given by width and height. Progress is
// a unsigned byte value between 0 and 100
void drawProgressBar(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint8_t progress);
// Draw a bitmap in the internal image format
void drawFastImage(int16_t x, int16_t y, int16_t width, int16_t height, const char *image);
// Draw a XBM
void drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, const char *xbm);
/* Text functions */
// Draws a string at the given location
void drawString(int16_t x, int16_t y, String text);
// Draws a String with a maximum width at the given location.
// If the given String is wider than the specified width
// The text will be wrapped to the next line at a space or dash
void drawStringMaxWidth(int16_t x, int16_t y, uint16_t maxLineWidth, String text);
// Returns the width of the const char* with the current
// font settings
uint16_t getStringWidth(const char* text, uint16_t length);
// Convencience method for the const char version
uint16_t getStringWidth(String text);
// Specifies relative to which anchor point
// the text is rendered. Available constants:
// TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER_BOTH
void setTextAlignment(OLEDDISPLAY_TEXT_ALIGNMENT textAlignment);
// Sets the current font. Available default fonts
// ArialMT_Plain_10, ArialMT_Plain_16, ArialMT_Plain_24
void setFont(const char *fontData);
/* Display functions */
// Turn the display on
void displayOn(void);
// Turn the display offs
void displayOff(void);
// Inverted display mode
void invertDisplay(void);
// Normal display mode
void normalDisplay(void);
// Set display contrast
// really low brightness & contrast: contrast = 10, precharge = 5, comdetect = 0
// normal brightness & contrast: contrast = 100
void setContrast(char contrast, char precharge = 241, char comdetect = 64);
// Turn the display upside down
void flipScreenVertically();
// Write the buffer to the display memory
virtual void display(void) = 0;
// Clear the local pixel buffer
void clear(void);
// Log buffer implementation
// This will define the lines and characters you can
// print to the screen. When you exeed the buffer size (lines * chars)
// the output may be truncated due to the size constraint.
bool setLogBuffer(uint16_t lines, uint16_t chars);
// Draw the log buffer at position (x, y)
void drawLogBuffer(uint16_t x, uint16_t y);
// Implementent needed function to be compatible with Print class
size_t write(uint8_t c);
size_t write(const char* s);
uint8_t *buffer = NULL;
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
uint8_t *buffer_back = NULL;
#endif
protected:
OLEDDISPLAY_TEXT_ALIGNMENT textAlignment = TEXT_ALIGN_LEFT;
OLEDDISPLAY_COLOR color = WHITE;
const char *fontData = ArialMT_Plain_10;
// State values for logBuffer
uint16_t logBufferSize = 0;
uint16_t logBufferFilled = 0;
uint16_t logBufferLine = 0;
uint16_t logBufferMaxLines = 0;
char *logBuffer = NULL;
// Send a command to the display (low level function)
virtual void sendCommand(uint8_t com) {(void)com;};
// Connect to the display
virtual bool connect() { return false; };
// Send all the init commands
void sendInitCommands();
// converts utf8 characters to extended ascii
static char* utf8ascii(String s);
static byte utf8ascii(byte ascii);
void inline drawInternal(int16_t xMove, int16_t yMove, int16_t width, int16_t height, const char *data, uint16_t offset, uint16_t bytesInData) __attribute__((always_inline));
void drawStringInternal(int16_t xMove, int16_t yMove, char* text, uint16_t textLength, uint16_t textWidth);
};
#endif
File diff suppressed because it is too large Load Diff
+406
View File
@@ -0,0 +1,406 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "OLEDDisplayUi.h"
OLEDDisplayUi::OLEDDisplayUi(OLEDDisplay *display) {
this->display = display;
}
void OLEDDisplayUi::init() {
this->display->init();
}
void OLEDDisplayUi::setTargetFPS(uint8_t fps){
float oldInterval = this->updateInterval;
this->updateInterval = ((float) 1.0 / (float) fps) * 1000;
// Calculate new ticksPerFrame
float changeRatio = oldInterval / (float) this->updateInterval;
this->ticksPerFrame *= changeRatio;
this->ticksPerTransition *= changeRatio;
}
// -/------ Automatic controll ------\-
void OLEDDisplayUi::enableAutoTransition(){
this->autoTransition = true;
}
void OLEDDisplayUi::disableAutoTransition(){
this->autoTransition = false;
}
void OLEDDisplayUi::setAutoTransitionForwards(){
this->state.frameTransitionDirection = 1;
this->lastTransitionDirection = 1;
}
void OLEDDisplayUi::setAutoTransitionBackwards(){
this->state.frameTransitionDirection = -1;
this->lastTransitionDirection = -1;
}
void OLEDDisplayUi::setTimePerFrame(uint16_t time){
this->ticksPerFrame = (int) ( (float) time / (float) updateInterval);
}
void OLEDDisplayUi::setTimePerTransition(uint16_t time){
this->ticksPerTransition = (int) ( (float) time / (float) updateInterval);
}
// -/------ Customize indicator position and style -------\-
void OLEDDisplayUi::enableIndicator(){
this->state.isIndicatorDrawen = true;
}
void OLEDDisplayUi::disableIndicator(){
this->state.isIndicatorDrawen = false;
}
void OLEDDisplayUi::enableAllIndicators(){
this->shouldDrawIndicators = true;
}
void OLEDDisplayUi::disableAllIndicators(){
this->shouldDrawIndicators = false;
}
void OLEDDisplayUi::setIndicatorPosition(IndicatorPosition pos) {
this->indicatorPosition = pos;
}
void OLEDDisplayUi::setIndicatorDirection(IndicatorDirection dir) {
this->indicatorDirection = dir;
}
void OLEDDisplayUi::setActiveSymbol(const char* symbol) {
this->activeSymbol = symbol;
}
void OLEDDisplayUi::setInactiveSymbol(const char* symbol) {
this->inactiveSymbol = symbol;
}
// -/----- Frame settings -----\-
void OLEDDisplayUi::setFrameAnimation(AnimationDirection dir) {
this->frameAnimationDirection = dir;
}
void OLEDDisplayUi::setFrames(FrameCallback* frameFunctions, uint8_t frameCount) {
this->frameFunctions = frameFunctions;
this->frameCount = frameCount;
this->resetState();
}
// -/----- Overlays ------\-
void OLEDDisplayUi::setOverlays(OverlayCallback* overlayFunctions, uint8_t overlayCount){
this->overlayFunctions = overlayFunctions;
this->overlayCount = overlayCount;
}
// -/----- Loading Process -----\-
void OLEDDisplayUi::setLoadingDrawFunction(LoadingDrawFunction loadingDrawFunction) {
this->loadingDrawFunction = loadingDrawFunction;
}
void OLEDDisplayUi::runLoadingProcess(LoadingStage* stages, uint8_t stagesCount) {
uint8_t progress = 0;
uint8_t increment = 100 / stagesCount;
for (uint8_t i = 0; i < stagesCount; i++) {
display->clear();
this->loadingDrawFunction(this->display, &stages[i], progress);
display->display();
stages[i].callback();
progress += increment;
yield();
}
display->clear();
this->loadingDrawFunction(this->display, &stages[stagesCount-1], progress);
display->display();
delay(150);
}
// -/----- Manuel control -----\-
void OLEDDisplayUi::nextFrame() {
if (this->state.frameState != IN_TRANSITION) {
this->state.manuelControll = true;
this->state.frameState = IN_TRANSITION;
this->state.ticksSinceLastStateSwitch = 0;
this->lastTransitionDirection = this->state.frameTransitionDirection;
this->state.frameTransitionDirection = 1;
}
}
void OLEDDisplayUi::previousFrame() {
if (this->state.frameState != IN_TRANSITION) {
this->state.manuelControll = true;
this->state.frameState = IN_TRANSITION;
this->state.ticksSinceLastStateSwitch = 0;
this->lastTransitionDirection = this->state.frameTransitionDirection;
this->state.frameTransitionDirection = -1;
}
}
void OLEDDisplayUi::switchToFrame(uint8_t frame) {
if (frame >= this->frameCount) return;
this->state.ticksSinceLastStateSwitch = 0;
if (frame == this->state.currentFrame) return;
this->state.frameState = FIXED;
this->state.currentFrame = frame;
this->state.isIndicatorDrawen = true;
}
void OLEDDisplayUi::transitionToFrame(uint8_t frame) {
if (frame >= this->frameCount) return;
this->state.ticksSinceLastStateSwitch = 0;
if (frame == this->state.currentFrame) return;
this->nextFrameNumber = frame;
this->lastTransitionDirection = this->state.frameTransitionDirection;
this->state.manuelControll = true;
this->state.frameState = IN_TRANSITION;
this->state.frameTransitionDirection = frame < this->state.currentFrame ? -1 : 1;
}
// -/----- State information -----\-
OLEDDisplayUiState* OLEDDisplayUi::getUiState(){
return &this->state;
}
int8_t OLEDDisplayUi::update(){
long frameStart = millis();
int8_t timeBudget = this->updateInterval - (frameStart - this->state.lastUpdate);
if ( timeBudget <= 0) {
// Implement frame skipping to ensure time budget is keept
if (this->autoTransition && this->state.lastUpdate != 0) this->state.ticksSinceLastStateSwitch += ceil(-timeBudget / this->updateInterval);
this->state.lastUpdate = frameStart;
this->tick();
}
return this->updateInterval - (millis() - frameStart);
}
void OLEDDisplayUi::tick() {
this->state.ticksSinceLastStateSwitch++;
switch (this->state.frameState) {
case IN_TRANSITION:
if (this->state.ticksSinceLastStateSwitch >= this->ticksPerTransition){
this->state.frameState = FIXED;
this->state.currentFrame = getNextFrameNumber();
this->state.ticksSinceLastStateSwitch = 0;
this->nextFrameNumber = -1;
}
break;
case FIXED:
// Revert manuelControll
if (this->state.manuelControll) {
this->state.frameTransitionDirection = this->lastTransitionDirection;
this->state.manuelControll = false;
}
if (this->state.ticksSinceLastStateSwitch >= this->ticksPerFrame){
if (this->autoTransition){
this->state.frameState = IN_TRANSITION;
}
this->state.ticksSinceLastStateSwitch = 0;
}
break;
}
this->display->clear();
this->drawFrame();
if (shouldDrawIndicators) {
this->drawIndicator();
}
this->drawOverlays();
this->display->display();
}
void OLEDDisplayUi::resetState() {
this->state.lastUpdate = 0;
this->state.ticksSinceLastStateSwitch = 0;
this->state.frameState = FIXED;
this->state.currentFrame = 0;
this->state.isIndicatorDrawen = true;
}
void OLEDDisplayUi::drawFrame(){
switch (this->state.frameState){
case IN_TRANSITION: {
float progress = (float) this->state.ticksSinceLastStateSwitch / (float) this->ticksPerTransition;
int16_t x = 0, y = 0, x1 = 0, y1 = 0;
switch(this->frameAnimationDirection){
case SLIDE_LEFT:
x = -this->display->width() * progress;
y = 0;
x1 = x + this->display->width();
y1 = 0;
break;
case SLIDE_RIGHT:
x = this->display->width() * progress;
y = 0;
x1 = x - this->display->width();
y1 = 0;
break;
case SLIDE_UP:
x = 0;
y = -this->display->height() * progress;
x1 = 0;
y1 = y + this->display->height();
break;
case SLIDE_DOWN:
x = 0;
y = this->display->height() * progress;
x1 = 0;
y1 = y - this->display->height();
break;
}
// Invert animation if direction is reversed.
int8_t dir = this->state.frameTransitionDirection >= 0 ? 1 : -1;
x *= dir; y *= dir; x1 *= dir; y1 *= dir;
bool drawenCurrentFrame;
// Prope each frameFunction for the indicator Drawen state
this->enableIndicator();
(this->frameFunctions[this->state.currentFrame])(this->display, &this->state, x, y);
drawenCurrentFrame = this->state.isIndicatorDrawen;
this->enableIndicator();
(this->frameFunctions[this->getNextFrameNumber()])(this->display, &this->state, x1, y1);
// Build up the indicatorDrawState
if (drawenCurrentFrame && !this->state.isIndicatorDrawen) {
// Drawen now but not next
this->indicatorDrawState = 2;
} else if (!drawenCurrentFrame && this->state.isIndicatorDrawen) {
// Not drawen now but next
this->indicatorDrawState = 1;
} else if (!drawenCurrentFrame && !this->state.isIndicatorDrawen) {
// Not drawen in both frames
this->indicatorDrawState = 3;
}
// If the indicator isn't draw in the current frame
// reflect it in state.isIndicatorDrawen
if (!drawenCurrentFrame) this->state.isIndicatorDrawen = false;
break;
}
case FIXED:
// Always assume that the indicator is drawn!
// And set indicatorDrawState to "not known yet"
this->indicatorDrawState = 0;
this->enableIndicator();
(this->frameFunctions[this->state.currentFrame])(this->display, &this->state, 0, 0);
break;
}
}
void OLEDDisplayUi::drawIndicator() {
// Only draw if the indicator is invisible
// for both frames or
// the indiactor is shown and we are IN_TRANSITION
if (this->indicatorDrawState == 3 || (!this->state.isIndicatorDrawen && this->state.frameState != IN_TRANSITION)) {
return;
}
uint8_t posOfHighlightFrame = 0;
float indicatorFadeProgress = 0;
// if the indicator needs to be slided in we want to
// highlight the next frame in the transition
uint8_t frameToHighlight = this->indicatorDrawState == 1 ? this->getNextFrameNumber() : this->state.currentFrame;
// Calculate the frame that needs to be highlighted
// based on the Direction the indiactor is drawn
switch (this->indicatorDirection){
case LEFT_RIGHT:
posOfHighlightFrame = frameToHighlight;
break;
case RIGHT_LEFT:
posOfHighlightFrame = this->frameCount - frameToHighlight;
break;
}
switch (this->indicatorDrawState) {
case 1: // Indicator was not drawn in this frame but will be in next
// Slide IN
indicatorFadeProgress = 1 - ((float) this->state.ticksSinceLastStateSwitch / (float) this->ticksPerTransition);
break;
case 2: // Indicator was drawn in this frame but not in next
// Slide OUT
indicatorFadeProgress = ((float) this->state.ticksSinceLastStateSwitch / (float) this->ticksPerTransition);
break;
}
uint16_t frameStartPos = (12 * frameCount / 2);
const char *image;
uint16_t x = 0, y = 0;
for (byte i = 0; i < this->frameCount; i++) {
switch (this->indicatorPosition){
case TOP:
y = 0 - (8 * indicatorFadeProgress);
x = (this->display->width() / 2) - frameStartPos + 12 * i;
break;
case BOTTOM:
y = (this->display->height() - 8) + (8 * indicatorFadeProgress);
x = (this->display->width() / 2) - frameStartPos + 12 * i;
break;
case RIGHT:
x = (this->display->width() - 8) + (8 * indicatorFadeProgress);
y = (this->display->height() / 2) - frameStartPos + 2 + 12 * i;
break;
case LEFT:
x = 0 - (8 * indicatorFadeProgress);
y = (this->display->height() / 2) - frameStartPos + 2 + 12 * i;
break;
}
if (posOfHighlightFrame == i) {
image = this->activeSymbol;
} else {
image = this->inactiveSymbol;
}
this->display->drawFastImage(x, y, 8, 8, image);
}
}
void OLEDDisplayUi::drawOverlays() {
for (uint8_t i=0;i<this->overlayCount;i++){
(this->overlayFunctions[i])(this->display, &this->state);
}
}
uint8_t OLEDDisplayUi::getNextFrameNumber(){
if (this->nextFrameNumber != -1) return this->nextFrameNumber;
return (this->state.currentFrame + this->frameCount + this->state.frameTransitionDirection) % this->frameCount;
}
+305
View File
@@ -0,0 +1,305 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef OLEDDISPLAYUI_h
#define OLEDDISPLAYUI_h
#include <Arduino.h>
#include "OLEDDisplay.h"
//#define DEBUG_OLEDDISPLAYUI(...) Serial.printf( __VA_ARGS__ )
#ifndef DEBUG_OLEDDISPLAYUI
#define DEBUG_OLEDDISPLAYUI(...)
#endif
enum AnimationDirection {
SLIDE_UP,
SLIDE_DOWN,
SLIDE_LEFT,
SLIDE_RIGHT
};
enum IndicatorPosition {
TOP,
RIGHT,
BOTTOM,
LEFT
};
enum IndicatorDirection {
LEFT_RIGHT,
RIGHT_LEFT
};
enum FrameState {
IN_TRANSITION,
FIXED
};
const char ANIMATION_activeSymbol[] PROGMEM = {
0x00, 0x18, 0x3c, 0x7e, 0x7e, 0x3c, 0x18, 0x00
};
const char ANIMATION_inactiveSymbol[] PROGMEM = {
0x00, 0x0, 0x0, 0x18, 0x18, 0x0, 0x0, 0x00
};
// Structure of the UiState
struct OLEDDisplayUiState {
uint64_t lastUpdate = 0;
uint16_t ticksSinceLastStateSwitch = 0;
FrameState frameState = FIXED;
uint8_t currentFrame = 0;
bool isIndicatorDrawen = true;
// Normal = 1, Inverse = -1;
int8_t frameTransitionDirection = 1;
bool manuelControll = false;
// Custom data that can be used by the user
void* userData = NULL;
};
struct LoadingStage {
const char* process;
void (*callback)();
};
typedef void (*FrameCallback)(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y);
typedef void (*OverlayCallback)(OLEDDisplay *display, OLEDDisplayUiState* state);
typedef void (*LoadingDrawFunction)(OLEDDisplay *display, LoadingStage* stage, uint8_t progress);
class OLEDDisplayUi {
private:
OLEDDisplay *display;
// Symbols for the Indicator
IndicatorPosition indicatorPosition = BOTTOM;
IndicatorDirection indicatorDirection = LEFT_RIGHT;
const char* activeSymbol = ANIMATION_activeSymbol;
const char* inactiveSymbol = ANIMATION_inactiveSymbol;
bool shouldDrawIndicators = true;
// Values for the Frames
AnimationDirection frameAnimationDirection = SLIDE_RIGHT;
int8_t lastTransitionDirection = 1;
uint16_t ticksPerFrame = 151; // ~ 5000ms at 30 FPS
uint16_t ticksPerTransition = 15; // ~ 500ms at 30 FPS
bool autoTransition = true;
FrameCallback* frameFunctions;
uint8_t frameCount = 0;
// Internally used to transition to a specific frame
int8_t nextFrameNumber = -1;
// Values for Overlays
OverlayCallback* overlayFunctions;
uint8_t overlayCount = 0;
// Will the Indicator be drawen
// 3 Not drawn in both frames
// 2 Drawn this frame but not next
// 1 Not drown this frame but next
// 0 Not known yet
uint8_t indicatorDrawState = 1;
// Loading screen
LoadingDrawFunction loadingDrawFunction = [](OLEDDisplay *display, LoadingStage* stage, uint8_t progress) {
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->setFont(ArialMT_Plain_10);
display->drawString(64, 18, stage->process);
display->drawProgressBar(4, 32, 120, 8, progress);
};
// UI State
OLEDDisplayUiState state;
// Bookeeping for update
uint8_t updateInterval = 33;
uint8_t getNextFrameNumber();
void drawIndicator();
void drawFrame();
void drawOverlays();
void tick();
void resetState();
public:
OLEDDisplayUi(OLEDDisplay *display);
/**
* Initialise the display
*/
void init();
/**
* Configure the internal used target FPS
*/
void setTargetFPS(uint8_t fps);
// Automatic Controll
/**
* Enable automatic transition to next frame after the some time can be configured with `setTimePerFrame` and `setTimePerTransition`.
*/
void enableAutoTransition();
/**
* Disable automatic transition to next frame.
*/
void disableAutoTransition();
/**
* Set the direction if the automatic transitioning
*/
void setAutoTransitionForwards();
void setAutoTransitionBackwards();
/**
* Set the approx. time a frame is displayed
*/
void setTimePerFrame(uint16_t time);
/**
* Set the approx. time a transition will take
*/
void setTimePerTransition(uint16_t time);
// Customize indicator position and style
/**
* Draw the indicator.
* This is the defaut state for all frames if
* the indicator was hidden on the previous frame
* it will be slided in.
*/
void enableIndicator();
/**
* Don't draw the indicator.
* This will slide out the indicator
* when transitioning to the next frame.
*/
void disableIndicator();
/**
* Enable drawing of indicators
*/
void enableAllIndicators();
/**
* Disable draw of indicators.
*/
void disableAllIndicators();
/**
* Set the position of the indicator bar.
*/
void setIndicatorPosition(IndicatorPosition pos);
/**
* Set the direction of the indicator bar. Defining the order of frames ASCENDING / DESCENDING
*/
void setIndicatorDirection(IndicatorDirection dir);
/**
* Set the symbol to indicate an active frame in the indicator bar.
*/
void setActiveSymbol(const char* symbol);
/**
* Set the symbol to indicate an inactive frame in the indicator bar.
*/
void setInactiveSymbol(const char* symbol);
// Frame settings
/**
* Configure what animation is used to transition from one frame to another
*/
void setFrameAnimation(AnimationDirection dir);
/**
* Add frame drawing functions
*/
void setFrames(FrameCallback* frameFunctions, uint8_t frameCount);
// Overlay
/**
* Add overlays drawing functions that are draw independent of the Frames
*/
void setOverlays(OverlayCallback* overlayFunctions, uint8_t overlayCount);
// Loading animation
/**
* Set the function that will draw each step
* in the loading animation
*/
void setLoadingDrawFunction(LoadingDrawFunction loadingFunction);
/**
* Run the loading process
*/
void runLoadingProcess(LoadingStage* stages, uint8_t stagesCount);
// Manual Control
void nextFrame();
void previousFrame();
/**
* Switch without transition to frame `frame`.
*/
void switchToFrame(uint8_t frame);
/**
* Transition to frame `frame`, when the `frame` number is bigger than the current
* frame the forward animation will be used, otherwise the backwards animation is used.
*/
void transitionToFrame(uint8_t frame);
// State Info
OLEDDisplayUiState* getUiState();
int8_t update();
};
#endif
@@ -0,0 +1,45 @@
#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= {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x60, 0x40, 0xc0, 0x00, 0x00, 0x70, 0xf0, 0xe0,
0x01, 0x00, 0x78, 0xf8, 0xf0, 0x01, 0x00, 0x3c, 0x7c, 0xf8, 0x00, 0x00,
0x1e, 0x3e, 0x7c, 0x00, 0x00, 0x0f, 0x1f, 0x3e, 0x00, 0x80, 0x87, 0x0f,
0x1f, 0x00, 0xc0, 0xc3, 0x87, 0x0f, 0x00, 0xe0, 0xe1, 0xc3, 0x07, 0x00,
0xf0, 0xf0, 0xe1, 0xc3, 0x00, 0x78, 0xf8, 0xf0, 0xe1, 0x01, 0x30, 0x7c,
0xf8, 0xf0, 0x00, 0x00, 0x3e, 0x7c, 0x78, 0x00, 0x00, 0x1f, 0x3e, 0x3c,
0x00, 0x80, 0x0f, 0x1f, 0x1e, 0x00, 0xc0, 0x87, 0x0f, 0x0f, 0x00, 0xe0,
0xc3, 0x87, 0x07, 0x00, 0xf0, 0xe1, 0xc3, 0x03, 0x00, 0xf0, 0xf0, 0xe1,
0x01, 0x00, 0x78, 0xf8, 0xf0, 0x00, 0x00, 0x30, 0x7c, 0x78, 0x00, 0x00,
0x00, 0x3e, 0x3c, 0x00, 0x00, 0x00, 0x1f, 0x1e, 0x00, 0x00, 0x80, 0x0f,
0x0f, 0x78, 0x00, 0xc0, 0x87, 0x07, 0xfc, 0x00, 0xe0, 0xc3, 0x03, 0xfc,
0x01, 0xf0, 0xe1, 0x01, 0xfc, 0x01, 0xf8, 0xf0, 0x00, 0xfc, 0x00, 0x78,
0x70, 0x00, 0x78, 0x00, 0x10, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
const char activeSymbole[] PROGMEM = {
B00000000,
B00000000,
B00011000,
B00100100,
B01000010,
B01000010,
B00100100,
B00011000
};
const char inactiveSymbole[] PROGMEM = {
B00000000,
B00000000,
B00000000,
B00000000,
B00011000,
B00011000,
B00000000,
B00000000
};
#endif
+260 -56
View File
@@ -1,20 +1,34 @@
# esp8266-oled-ssd1306
esp8266-oled-ssd1306 [![Build Status](https://travis-ci.org/squix78/esp8266-oled-ssd1306.svg?branch=dev-branch-3.0.0)](https://travis-ci.org/squix78/esp8266-oled-ssd1306)
============
> We just released version 3.0.0. Please have a look at our [upgrade guide](UPGRADE-3.0.md)
This is a driver for the SSD1306 based 128x64 pixel OLED display running on the Arduino/ESP8266 platform.
Can be used with either the I2C or SPI version of the display
You can either download this library as a zip file and unpack it to your Arduino/libraries folder or (once it has been added) choose it from the Arduino library manager.
It is also available as a platformio library. Just execute the following command:
```
platformio lib install 562
```
## Credits
Many thanks go to Fabrice Weinberg (@FWeinb) for optimizing and refactoring the UI library.
The init sequence for the SSD1306 was inspired by Adafruits library for the same display.
This library has initially been written by Daniel Eichhorn (@squix78). Many thanks go to Fabrice Weinberg (@FWeinb) for optimizing and refactoring many aspects of the library. Also many thanks to the many committers who helped to add new features and who fixed many bugs.
The init sequence for the SSD1306 was inspired by Adafruit's library for the same display.
## Usage
The SSD1306Demo is a very comprehensive example demonstrating the most important features of the library.
Check out the examples folder for a few comprehensive demonstrations how to use the library. Also check out the ESP8266 Weather Station library (https://github.com/squix78/esp8266-weather-station) which uses the OLED library to display beautiful weather information.
## Upgrade
The API changed a lot with the 3.0 release. If you were using this library with older versions please have a look at the [Upgrade Guide](UPGRADE-3.0.md).
## Features
* Draw pixels at given coordinates
* Draw lines from given coordinates to given coordinates
* Draw or fill a rectangle with given dimensions
* Draw Text at given coordinates:
* Define Alignment: Left, Right and Center
@@ -32,20 +46,72 @@ Fonts are defined in a proprietary but open format. You can create new font file
of open sourced Fonts from this web app: http://oleddisplay.squix.ch
Choose the font family, style and size, check the preview image and if you like what you see click the "Create" button. This will create the font array in a text area form where you can copy and paste it into a new or existing header file.
![FontTool](https://github.com/squix78/esp8266-oled-ssd1306/raw/master/resources/FontTool.png)
## Hardware Abstraction
The library supports different protocols to access the OLED display. Currently there is support for I2C using the built in Wire.h library, I2C by using the much faster BRZO I2C library [https://github.com/pasko-zh/brzo_i2c] written in assembler and it also supports displays which come with the SPI interface.
### I2C with Wire.h
```C++
#include <Wire.h>
#include "SSD1306.h"
SSD1306 display(ADDRESS, SDA, SDC);
```
or for a SH1106:
```C++
#include <Wire.h>
#include "SH1106.h"
SH1106 display(ADDRESS, SDA, SDC);
```
### I2C with brzo_i2c
```C++
#include <brzo_i2c.h>
#include "SSD1306Brzo.h"
SSD1306Brzo display(ADDRESS, SDA, SDC);
```
or for the SH1106:
```C++
#include <brzo_i2c.h>
#include "SH1106Brzo.h"
SH1106Brzo display(ADDRESS, SDA, SDC);
```
### SPI
```C++
#include <SPI.h>
#include "SSD1306Spi.h"
SSD1306Spi display(RES, DC, CS);
```
or for the SH1106:
```C++
#include <SPI.h>
#include "SH1106Spi.h"
SH1106Spi display(RES, DC, CS);
```
## API
### Display Control
```C++
// Create the display object connected to pin sda and sdc
SSD1306(int i2cAddress, int sda, int sdc);
// Initialize the display
void init();
// Free the memory used by the display
void end();
// Cycle through the initialization
void resetDisplay(void);
@@ -64,101 +130,227 @@ void clear(void);
// Write the buffer to the display memory
void display(void);
// Inverted display mode
void invertDisplay(void);
// Normal display mode
void normalDisplay(void);
// Set display contrast
void setContrast(char contrast);
// Turn the display upside down
void flipScreenVertically();
// Send a command to the display (low level function)
void sendCommand(unsigned char com);
// Send all the init commands
void sendInitCommands(void);
```
## Pixel drawing
```C++
// Draw a pixel at given position
void setPixel(int x, int y);
// Draw 8 bits at the given position
void setChar(int x, int y, unsigned char data);
/* Drawing functions */
// Sets the color of all pixel operations
void setColor(OLEDDISPLAY_COLOR color);
// Draw a pixel at given position
void setPixel(int16_t x, int16_t y);
// Draw a line from position 0 to position 1
void drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1);
// Draw the border of a rectangle at the given location
void drawRect(int x, int y, int width, int height);
void drawRect(int16_t x, int16_t y, int16_t width, int16_t height);
// Fill the rectangle
void fillRect(int x, int y, int width, int height);
void fillRect(int16_t x, int16_t y, int16_t width, int16_t height);
// Draw a bitmap with the given dimensions
void drawBitmap(int x, int y, int width, int height, const char *bitmap);
// Draw the border of a circle
void drawCircle(int16_t x, int16_t y, int16_t radius);
// Draw an XBM image with the given dimensions
void drawXbm(int x, int y, int width, int height, const char *xbm);
// Fill circle
void fillCircle(int16_t x, int16_t y, int16_t radius);
// Sets the color of all pixel operations
void setColor(int color);
// Draw a line horizontally
void drawHorizontalLine(int16_t x, int16_t y, int16_t length);
// Draw a lin vertically
void drawVerticalLine(int16_t x, int16_t y, int16_t length);
// Draws a rounded progress bar with the outer dimensions given by width and height. Progress is
// a unsigned byte value between 0 and 100
void drawProgressBar(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint8_t progress);
// Draw a bitmap in the internal image format
void drawFastImage(int16_t x, int16_t y, int16_t width, int16_t height, const char *image);
// Draw a XBM
void drawXbm(int16_t x, int16_t y, int16_t width, int16_t height, const char* xbm);
```
## Text operations
``` C++
// Draws a string at the given location
void drawString(int x, int y, String text);
void drawString(int16_t x, int16_t y, String text);
// Draws a String with a maximum width at the given location.
// If the given String is wider than the specified width
// The text will be wrapped to the next line at a space or dash
void drawStringMaxWidth(int x, int y, int maxLineWidth, String text);
void drawStringMaxWidth(int16_t x, int16_t y, int16_t maxLineWidth, String text);
// Returns the width of the String with the current
// Returns the width of the const char* with the current
// font settings
int getStringWidth(String text);
uint16_t getStringWidth(const char* text, uint16_t length);
// Convencience method for the const char version
uint16_t getStringWidth(String text);
// Specifies relative to which anchor point
// the text is rendered. Available constants:
// TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT
void setTextAlignment(int textAlignment);
// TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER_BOTH
void setTextAlignment(OLEDDISPLAY_TEXT_ALIGNMENT textAlignment);
// Sets the current font. Available default fonts
// defined in SSD1306Fonts.h:
// ArialMT_Plain_10, ArialMT_Plain_16, ArialMT_Plain_24
// Or create one with the font tool at http://oleddisplay.squix.ch
void setFont(const char *fontData);
void setFont(const char* fontData);
```
## Frame Transition Functions
## Ui Library (OLEDDisplayUi)
The Ui Library is used to provide a basic set of Ui elements called, `Frames` and `Overlays`. A `Frame` is used to provide
information the default behaviour is to display a `Frame` for a defined time and than move to the next. The library also provides an `Indicator` that will be updated accordingly. An `Overlay` on the other hand is a pieces of information (e.g. a clock) that is displayed always at the same position.
The Frame Transition functions are a set of functions on top of the basic library. They allow you to easily write frames which will be shifted in regular intervals. The frame animation (including the frame indicators) will only be activated if you define callback functions with setFrameCallacks(..). If no callback methods are defined no indicators will be displayed.
```C++
// Sets the callback methods of the format void method(x,y). As soon as you define the callbacks
// the library is in "frame mode" and indicators will be drawn.
void setFrameCallbacks(int frameCount, void (*frameCallbacks[])(SSD1306 *display, SSD1306UiState* state,int x, int y));
/**
* Initialise the display
*/
void init();
// Tells the framework to move to the next tick. The
// current visible frame callback will be called once
// per tick
void nextFrameTick(void);
/**
* Configure the internal used target FPS
*/
void setTargetFPS(uint8_t fps);
// Draws the frame indicators. In a normal setup
// the framework does this for you
void drawIndicators(int frameCount, int activeFrame);
/**
* Enable automatic transition to next frame after the some time can be configured with
* `setTimePerFrame` and `setTimePerTransition`.
*/
void enableAutoTransition();
// defines how many ticks a frame should remain visible
// This does not include the transition
void setFrameWaitTicks(int frameWaitTicks);
/**
* Disable automatic transition to next frame.
*/
void disableAutoTransition();
// Defines how many ticks should be used for a transition
void setFrameTransitionTicks(int frameTransitionTicks);
/**
* Set the direction if the automatic transitioning
*/
void setAutoTransitionForwards();
void setAutoTransitionBackwards();
// Returns the current state of the internal state machine
// Possible values: FRAME_STATE_FIX, FRAME_STATE_TRANSITION
// You can use this to detect when there is no transition
// on the way to execute operations that would
int getFrameState();
/**
* Set the approx. time a frame is displayed
*/
void setTimePerFrame(uint16_t time);
/**
* Set the approx. time a transition will take
*/
void setTimePerTransition(uint16_t time);
/**
* Draw the indicator.
* This is the default state for all frames if
* the indicator was hidden on the previous frame
* it will be slided in.
*/
void enableIndicator();
/**
* Don't draw the indicator.
* This will slide out the indicator
* when transitioning to the next frame.
*/
void disableIndicator();
/**
* Enable drawing of all indicators.
*/
void enableAllIndicators();
/**
* Disable drawing of all indicators.
*/
void disableAllIndicators();
/**
* Set the position of the indicator bar.
*/
void setIndicatorPosition(IndicatorPosition pos);
/**
* Set the direction of the indicator bar. Defining the order of frames ASCENDING / DESCENDING
*/
void setIndicatorDirection(IndicatorDirection dir);
/**
* Set the symbol to indicate an active frame in the indicator bar.
*/
void setActiveSymbol(const char* symbol);
/**
* Set the symbol to indicate an inactive frame in the indicator bar.
*/
void setInactiveSymbol(const char* symbol);
/**
* Configure what animation is used to transition from one frame to another
*/
void setFrameAnimation(AnimationDirection dir);
/**
* Add frame drawing functions
*/
void setFrames(FrameCallback* frameFunctions, uint8_t frameCount);
/**
* Add overlays drawing functions that are draw independent of the Frames
*/
void setOverlays(OverlayCallback* overlayFunctions, uint8_t overlayCount);
/**
* Set the function that will draw each step
* in the loading animation
*/
void setLoadingDrawFunction(LoadingDrawFunction loadingDrawFunction);
/**
* Run the loading process
*/
void runLoadingProcess(LoadingStage* stages, uint8_t stagesCount);
// Manuell Controll
void nextFrame();
void previousFrame();
/**
* Switch without transition to frame `frame`.
*/
void switchToFrame(uint8_t frame);
/**
* Transition to frame `frame`, when the `frame` number is bigger than the current
* frame the forward animation will be used, otherwise the backwards animation is used.
*/
void transitionToFrame(uint8_t frame);
// State Info
OLEDDisplayUiState* getUiState();
// This needs to be called in the main loop
// the returned value is the remaining time (in ms)
// you have to draw after drawing to keep the frame budget.
int8_t update();
```
## Example: SSD1306Demo
@@ -187,3 +379,15 @@ This frame demonstrates the text alignment. The coordinates in the frame show re
![DemoFrame4](https://github.com/squix78/esp8266-oled-ssd1306/raw/master/resources/DemoFrame4.jpg)
This shows how to use define a maximum width after which the driver automatically wraps a word to the next line. This comes in very handy if you have longer texts to display.
### SPI version
![SPIVersion](https://github.com/neptune2/esp8266-oled-ssd1306/raw/master/resources/SPI_version.jpg)
This shows the code working on the SPI version of the display. See demo code for ESP8266 pins used.
## Project using this library
* [QRCode ESP8266](https://github.com/anunpanya/ESP8266_QRcode) (by @anunpanya)
* [Scan I2C](https://github.com/hallard/Scan-I2C-WiFi) (by @hallard)
* [Weather Station](https://github.com/squix78/esp8266-weather-station) (by @squix)
+36
View File
@@ -0,0 +1,36 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#ifndef SH1106_h
#define SH1106_h
#include "SH1106Wire.h"
// For make SH1106 an alias for SH1106Wire
typedef SH1106Wire SH1106;
#endif
+133
View File
@@ -0,0 +1,133 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#ifndef SH1106Brzo_h
#define SH1106Brzo_h
#include "OLEDDisplay.h"
#include <brzo_i2c.h>
#if F_CPU == 160000000L
#define BRZO_I2C_SPEED 1000
#else
#define BRZO_I2C_SPEED 800
#endif
class SH1106Brzo : public OLEDDisplay {
private:
uint8_t _address;
uint8_t _sda;
uint8_t _scl;
public:
SH1106Brzo(uint8_t _address, uint8_t _sda, uint8_t _scl) {
this->_address = _address;
this->_sda = _sda;
this->_scl = _scl;
}
bool connect(){
brzo_i2c_setup(_sda, _scl, 0);
return true;
}
void display(void) {
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
uint8_t minBoundY = ~0;
uint8_t maxBoundY = 0;
uint8_t minBoundX = ~0;
uint8_t maxBoundX = 0;
uint8_t x, y;
// Calculate the Y bounding box of changes
// and copy buffer[pos] to buffer_back[pos];
for (y = 0; y < (DISPLAY_HEIGHT / 8); y++) {
for (x = 0; x < DISPLAY_WIDTH; x++) {
uint16_t pos = x + y * DISPLAY_WIDTH;
if (buffer[pos] != buffer_back[pos]) {
minBoundY = _min(minBoundY, y);
maxBoundY = _max(maxBoundY, y);
minBoundX = _min(minBoundX, x);
maxBoundX = _max(maxBoundX, x);
}
buffer_back[pos] = buffer[pos];
}
yield();
}
// If the minBoundY wasn't updated
// we can savely assume that buffer_back[pos] == buffer[pos]
// holdes true for all values of pos
if (minBoundY == ~0) return;
byte k = 0;
uint8_t sendBuffer[17];
sendBuffer[0] = 0x40;
// Calculate the colum offset
uint8_t minBoundXp2H = (minBoundX + 2) & 0x0F;
uint8_t minBoundXp2L = 0x10 | ((minBoundX + 2) >> 4 );
brzo_i2c_start_transaction(this->_address, BRZO_I2C_SPEED);
for (y = minBoundY; y <= maxBoundY; y++) {
sendCommand(0xB0 + y);
sendCommand(minBoundXp2H);
sendCommand(minBoundXp2L);
for (x = minBoundX; x <= maxBoundX; x++) {
k++;
sendBuffer[k] = buffer[x + y * DISPLAY_WIDTH];
if (k == 16) {
brzo_i2c_write(sendBuffer, 17, true);
k = 0;
}
}
if (k != 0) {
brzo_i2c_write(sendBuffer, k + 1, true);
k = 0;
}
yield();
}
if (k != 0) {
brzo_i2c_write(sendBuffer, k + 1, true);
}
brzo_i2c_end_transaction();
#else
#endif
}
private:
inline void sendCommand(uint8_t com) __attribute__((always_inline)){
uint8_t command[2] = {0x80 /* command mode */, com};
brzo_i2c_start_transaction(_address, BRZO_I2C_SPEED);
brzo_i2c_write(command, 2, true);
brzo_i2c_end_transaction();
}
};
#endif
+128
View File
@@ -0,0 +1,128 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#ifndef SH1106Spi_h
#define SH1106Spi_h
#include "OLEDDisplay.h"
#include <SPI.h>
class SH1106Spi : public OLEDDisplay {
private:
uint8_t _rst;
uint8_t _dc;
public:
SH1106Spi(uint8_t _rst, uint8_t _dc) {
this->_rst = _rst;
this->_dc = _dc;
}
bool connect(){
pinMode(_dc, OUTPUT);
pinMode(_rst, OUTPUT);
SPI.begin ();
SPI.setClockDivider (SPI_CLOCK_DIV2);
// Pulse Reset low for 10ms
digitalWrite(_rst, HIGH);
delay(1);
digitalWrite(_rst, LOW);
delay(10);
digitalWrite(_rst, HIGH);
return true;
}
void display(void) {
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
uint8_t minBoundY = ~0;
uint8_t maxBoundY = 0;
uint8_t minBoundX = ~0;
uint8_t maxBoundX = 0;
uint8_t x, y;
// Calculate the Y bounding box of changes
// and copy buffer[pos] to buffer_back[pos];
for (y = 0; y < (DISPLAY_HEIGHT / 8); y++) {
for (x = 0; x < DISPLAY_WIDTH; x++) {
uint16_t pos = x + y * DISPLAY_WIDTH;
if (buffer[pos] != buffer_back[pos]) {
minBoundY = _min(minBoundY, y);
maxBoundY = _max(maxBoundY, y);
minBoundX = _min(minBoundX, x);
maxBoundX = _max(maxBoundX, x);
}
buffer_back[pos] = buffer[pos];
}
yield();
}
// If the minBoundY wasn't updated
// we can savely assume that buffer_back[pos] == buffer[pos]
// holdes true for all values of pos
if (minBoundY == ~0) return;
// Calculate the colum offset
uint8_t minBoundXp2H = (minBoundX + 2) & 0x0F;
uint8_t minBoundXp2L = 0x10 | ((minBoundX + 2) >> 4 );
for (y = minBoundY; y <= maxBoundY; y++) {
sendCommand(0xB0 + y);
sendCommand(minBoundXp2H);
sendCommand(minBoundXp2L);
digitalWrite(_dc, HIGH); // data mode
for (x = minBoundX; x <= maxBoundX; x++) {
SPI.transfer(buffer[x + y * DISPLAY_WIDTH]);
}
yield();
}
#else
for (uint8_t y=0; y<DISPLAY_HEIGHT/8; y++) {
sendCommand(0xB0 + y);
sendCommand(0x02);
sendCommand(0x10);
digitalWrite(_dc, HIGH); // data mode
for( uint8_t x=0; x < DISPLAY_WIDTH; x++) {
SPI.transfer(buffer[x + y * DISPLAY_WIDTH]);
}
yield();
}
#endif
}
private:
inline void sendCommand(uint8_t com) __attribute__((always_inline)){
digitalWrite(_dc, LOW);
SPI.transfer(com);
}
};
#endif
+152
View File
@@ -0,0 +1,152 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#ifndef SH1106Wire_h
#define SH1106Wire_h
#include "OLEDDisplay.h"
#include <Wire.h>
#define SH1106_SET_PUMP_VOLTAGE 0X30
#define SH1106_SET_PUMP_MODE 0XAD
#define SH1106_PUMP_ON 0X8B
#define SH1106_PUMP_OFF 0X8A
//--------------------------------------
class SH1106Wire : public OLEDDisplay {
private:
uint8_t _address;
uint8_t _sda;
uint8_t _scl;
public:
SH1106Wire(uint8_t _address, uint8_t _sda, uint8_t _scl) {
this->_address = _address;
this->_sda = _sda;
this->_scl = _scl;
}
bool connect() {
Wire.begin(this->_sda, this->_scl);
// Let's use ~700khz if ESP8266 is in 160Mhz mode
// this will be limited to ~400khz if the ESP8266 in 80Mhz mode.
Wire.setClock(700000);
return true;
}
void display(void) {
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
uint8_t minBoundY = ~0;
uint8_t maxBoundY = 0;
uint8_t minBoundX = ~0;
uint8_t maxBoundX = 0;
uint8_t x, y;
// Calculate the Y bounding box of changes
// and copy buffer[pos] to buffer_back[pos];
for (y = 0; y < (DISPLAY_HEIGHT / 8); y++) {
for (x = 0; x < DISPLAY_WIDTH; x++) {
uint16_t pos = x + y * DISPLAY_WIDTH;
if (buffer[pos] != buffer_back[pos]) {
minBoundY = _min(minBoundY, y);
maxBoundY = _max(maxBoundY, y);
minBoundX = _min(minBoundX, x);
maxBoundX = _max(maxBoundX, x);
}
buffer_back[pos] = buffer[pos];
}
yield();
}
// If the minBoundY wasn't updated
// we can savely assume that buffer_back[pos] == buffer[pos]
// holdes true for all values of pos
if (minBoundY == ~0) return;
// Calculate the colum offset
uint8_t minBoundXp2H = (minBoundX + 2) & 0x0F;
uint8_t minBoundXp2L = 0x10 | ((minBoundX + 2) >> 4 );
byte k = 0;
for (y = minBoundY; y <= maxBoundY; y++) {
sendCommand(0xB0 + y);
sendCommand(minBoundXp2H);
sendCommand(minBoundXp2L);
for (x = minBoundX; x <= maxBoundX; x++) {
if (k == 0) {
Wire.beginTransmission(_address);
Wire.write(0x40);
}
Wire.write(buffer[x + y * DISPLAY_WIDTH]);
k++;
if (k == 16) {
Wire.endTransmission();
k = 0;
}
}
if (k != 0) {
Wire.endTransmission();
k = 0;
}
yield();
}
if (k != 0) {
Wire.endTransmission();
}
#else
uint8_t * p = &buffer[0];
for (uint8_t y=0; y<8; y++) {
sendCommand(0xB0+y);
sendCommand(0x02);
sendCommand(0x10);
for( uint8_t x=0; x<8; x++) {
Wire.beginTransmission(_address);
Wire.write(0x40);
for (uint8_t k = 0; k < 16; k++) {
Wire.write(*p++);
}
Wire.endTransmission();
}
}
#endif
}
private:
inline void sendCommand(uint8_t command) __attribute__((always_inline)){
Wire.beginTransmission(_address);
Wire.write(0x80);
Wire.write(command);
Wire.endTransmission();
}
};
#endif
-363
View File
@@ -1,363 +0,0 @@
/**The MIT License (MIT)
Copyright (c) 2015 by Daniel Eichhorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
See more at http://blog.squix.ch
Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#include "../esp8266-oled-ssd1306/SSD1306.h"
#include <Wire.h>
SSD1306::SSD1306(int i2cAddress, int sda, int sdc) {
myI2cAddress = i2cAddress;
mySda = sda;
mySdc = sdc;
}
void SSD1306::init() {
Wire.begin(mySda, mySdc);
Wire.setClock(400000);
sendInitCommands();
resetDisplay();
}
// Local override of init to avoid having to pass the sda and sdc in global section.
void SSD1306::init(int i2cAddress) {
myI2cAddress = i2cAddress;
Wire.setClock(400000);
sendInitCommands();
resetDisplay();
}
void SSD1306::resetDisplay(void) {
displayOff();
clear();
display();
displayOn();
}
void SSD1306::reconnect() {
Wire.begin(mySda, mySdc);
}
void SSD1306::displayOn(void) {
sendCommand(0xaf); //display on
}
void SSD1306::displayOff(void) {
sendCommand(0xae); //display off
}
void SSD1306::setContrast(char contrast) {
sendCommand(0x81);
sendCommand(contrast);
}
void SSD1306::flipScreenVertically() {
sendCommand(0xA0 | 0x1); //SEGREMAP //Rotate screen 180 deg
sendCommand(0xC8); //COMSCANDEC Rotate screen 180 Deg
}
void SSD1306::clear(void) {
memset(buffer, 0, (128 * 64 / 8));
}
void SSD1306::display(void) {
sendCommand(COLUMNADDR);
sendCommand(0x0);
sendCommand(0x7F);
sendCommand(PAGEADDR);
sendCommand(0x0);
sendCommand(0x7);
for (uint16_t i=0; i<(128*64/8); i++) {
// send a bunch of data in one xmission
Wire.beginTransmission(myI2cAddress);
Wire.write(0x40);
for (uint8_t x=0; x<16; x++) {
Wire.write(buffer[i]);
i++;
}
i--;
yield();
Wire.endTransmission();
}
}
void SSD1306::setPixel(int x, int y) {
if (x >= 0 && x < 128 && y >= 0 && y < 64) {
switch (myColor) {
case WHITE: buffer[x + (y/8)*128] |= (1 << (y&7)); break;
case BLACK: buffer[x + (y/8)*128] &= ~(1 << (y&7)); break;
case INVERSE: buffer[x + (y/8)*128] ^= (1 << (y&7)); break;
}
}
}
void SSD1306::setChar(int x, int y, unsigned char data) {
for (int i = 0; i < 8; i++) {
if (bitRead(data, i)) {
setPixel(x,y + i);
}
}
}
// Code form http://playground.arduino.cc/Main/Utf8ascii
byte SSD1306::utf8ascii(byte ascii) {
if ( ascii<128 ) { // Standard ASCII-set 0..0x7F handling
lastChar=0;
return( ascii );
}
// get previous input
byte last = lastChar; // get last char
lastChar=ascii; // remember actual character
switch (last) // conversion depnding on first UTF8-character
{ case 0xC2: return (ascii); break;
case 0xC3: return (ascii | 0xC0); break;
case 0x82: if(ascii==0xAC) return(0x80); // special case Euro-symbol
}
return (0); // otherwise: return zero, if character has to be ignored
}
// Code form http://playground.arduino.cc/Main/Utf8ascii
String SSD1306::utf8ascii(String s) {
String r= "";
char c;
for (int i=0; i<s.length(); i++)
{
c = utf8ascii(s.charAt(i));
if (c!=0) r+=c;
}
return r;
}
void SSD1306::drawString(int x, int y, String text) {
text = utf8ascii(text);
unsigned char currentByte;
int charX, charY;
int currentBitCount;
int charCode;
int currentCharWidth;
int currentCharStartPos;
int cursorX = 0;
int numberOfChars = pgm_read_byte(myFontData + CHAR_NUM_POS);
// iterate over string
int firstChar = pgm_read_byte(myFontData + FIRST_CHAR_POS);
int charHeight = pgm_read_byte(myFontData + HEIGHT_POS);
int currentCharByteNum = 0;
int startX = 0;
int startY = y;
if (myTextAlignment == TEXT_ALIGN_LEFT) {
startX = x;
} else if (myTextAlignment == TEXT_ALIGN_CENTER) {
int width = getStringWidth(text);
startX = x - width / 2;
} else if (myTextAlignment == TEXT_ALIGN_RIGHT) {
int width = getStringWidth(text);
startX = x - width;
}
for (int j=0; j < text.length(); j++) {
charCode = text.charAt(j)-0x20;
currentCharWidth = pgm_read_byte(myFontData + CHAR_WIDTH_START_POS + charCode);
// Jump to font data beginning
currentCharStartPos = CHAR_WIDTH_START_POS + numberOfChars;
for (int m = 0; m < charCode; m++) {
currentCharStartPos += pgm_read_byte(myFontData + CHAR_WIDTH_START_POS + m) * charHeight / 8 + 1;
}
currentCharByteNum = ((charHeight * currentCharWidth) / 8) + 1;
// iterate over all bytes of character
for (int i = 0; i < currentCharByteNum; i++) {
currentByte = pgm_read_byte(myFontData + currentCharStartPos + i);
//Serial.println(String(charCode) + ", " + String(currentCharWidth) + ", " + String(currentByte));
// iterate over all bytes of character
for(int bit = 0; bit < 8; bit++) {
//int currentBit = bitRead(currentByte, bit);
currentBitCount = i * 8 + bit;
charX = currentBitCount % currentCharWidth;
charY = currentBitCount / currentCharWidth;
if (bitRead(currentByte, bit)) {
setPixel(startX + cursorX + charX, startY + charY);
}
}
yield();
}
cursorX += currentCharWidth;
}
}
void SSD1306::drawStringMaxWidth(int x, int y, int maxLineWidth, String text) {
int currentLineWidth = 0;
int startsAt = 0;
int endsAt = 0;
int lineNumber = 0;
char currentChar = ' ';
int lineHeight = pgm_read_byte(myFontData + HEIGHT_POS);
String currentLine = "";
for (int i = 0; i < text.length(); i++) {
currentChar = text.charAt(i);
if (currentChar == ' ' || currentChar == '-') {
String lineCandidate = text.substring(startsAt, i);
if (getStringWidth(lineCandidate) <= maxLineWidth) {
endsAt = i;
} else {
drawString(x, y + lineNumber * lineHeight, text.substring(startsAt, endsAt));
lineNumber++;
startsAt = endsAt + 1;
}
}
}
drawString(x, y + lineNumber * lineHeight, text.substring(startsAt));
}
int SSD1306::getStringWidth(String text) {
text = utf8ascii(text);
int stringWidth = 0;
char charCode;
for (int j=0; j < text.length(); j++) {
charCode = text.charAt(j)-0x20;
stringWidth += pgm_read_byte(myFontData + CHAR_WIDTH_START_POS + charCode);
}
return stringWidth;
}
void SSD1306::setTextAlignment(int textAlignment) {
myTextAlignment = textAlignment;
}
void SSD1306::setFont(const char *fontData) {
myFontData = fontData;
}
void SSD1306::drawBitmap(int x, int y, int width, int height, const char *bitmap) {
for (int i = 0; i < width * height / 8; i++ ){
unsigned char charColumn = 255 - pgm_read_byte(bitmap + i);
for (int j = 0; j < 8; j++) {
int targetX = i % width + x;
int targetY = (i / (width)) * 8 + j + y;
if (bitRead(charColumn, j)) {
setPixel(targetX, targetY);
}
}
}
}
void SSD1306::setColor(int color) {
myColor = color;
}
void SSD1306::drawRect(int x, int y, int width, int height) {
for (int i = x; i < x + width; i++) {
setPixel(i, y);
setPixel(i, y + height);
}
for (int i = y; i < y + height; i++) {
setPixel(x, i);
setPixel(x + width, i);
}
}
void SSD1306::fillRect(int x, int y, int width, int height) {
for (int i = x; i < x + width; i++) {
for (int j = y; j < y + height; j++) {
setPixel(i, j);
}
}
}
void SSD1306::drawXbm(int x, int y, int width, int height, const char *xbm) {
if (width % 8 != 0) {
width = ((width / 8) + 1) * 8;
}
for (int i = 0; i < width * height / 8; i++ ){
unsigned char charColumn = pgm_read_byte(xbm + i);
for (int j = 0; j < 8; j++) {
int targetX = (i * 8 + j) % width + x;
int targetY = (8 * i / (width)) + y;
if (bitRead(charColumn, j)) {
setPixel(targetX, targetY);
}
}
}
}
void SSD1306::sendCommand(unsigned char com) {
Wire.beginTransmission(myI2cAddress); //begin transmitting
Wire.write(0x80); //command mode
Wire.write(com);
Wire.endTransmission(); // stop transmitting
}
void SSD1306::sendInitCommands(void) {
sendCommand(DISPLAYOFF);
sendCommand(NORMALDISPLAY);
sendCommand(SETDISPLAYCLOCKDIV);
sendCommand(0x80);
sendCommand(SETMULTIPLEX);
sendCommand(0x3F);
sendCommand(SETDISPLAYOFFSET);
sendCommand(0x00);
sendCommand(SETSTARTLINE | 0x00);
sendCommand(CHARGEPUMP);
sendCommand(0x14);
sendCommand(MEMORYMODE);
sendCommand(0x00);
sendCommand(SEGREMAP);
sendCommand(COMSCANINC);
sendCommand(SETCOMPINS);
sendCommand(0x12);
sendCommand(SETCONTRAST);
sendCommand(0xCF);
sendCommand(SETPRECHARGE);
sendCommand(0xF1);
sendCommand(SETVCOMDETECT);
sendCommand(0x40);
sendCommand(DISPLAYALLON_RESUME);
sendCommand(NORMALDISPLAY);
sendCommand(0x2e); // stop scroll
sendCommand(DISPLAYON);
}
+32 -172
View File
@@ -1,176 +1,36 @@
/**The MIT License (MIT)
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
Copyright (c) 2015 by Daniel Eichhorn
#ifndef SSD1306_h
#define SSD1306_h
#include "SSD1306Wire.h"
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
// For legacy support make SSD1306 an alias for SSD1306
typedef SSD1306Wire SSD1306;
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
See more at http://blog.squix.ch
Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#pragma once
#include <Arduino.h>
#include "SSD1306Fonts.h"
#define BLACK 0
#define WHITE 1
#define INVERSE 2
#define WIDTH_POS 0
#define HEIGHT_POS 1
#define FIRST_CHAR_POS 2
#define CHAR_NUM_POS 3
#define CHAR_WIDTH_START_POS 4
#define TEXT_ALIGN_LEFT 0
#define TEXT_ALIGN_CENTER 1
#define TEXT_ALIGN_RIGHT 2
#define CHARGEPUMP 0x8D
#define COLUMNADDR 0x21
#define COMSCANDEC 0xC8
#define COMSCANINC 0xC0
#define DISPLAYALLON 0xA5
#define DISPLAYALLON_RESUME 0xA4
#define DISPLAYOFF 0xAE
#define DISPLAYON 0xAF
#define EXTERNALVCC 0x1
#define INVERTDISPLAY 0xA7
#define MEMORYMODE 0x20
#define NORMALDISPLAY 0xA6
#define PAGEADDR 0x22
#define SEGREMAP 0xA0
#define SETCOMPINS 0xDA
#define SETCONTRAST 0x81
#define SETDISPLAYCLOCKDIV 0xD5
#define SETDISPLAYOFFSET 0xD3
#define SETHIGHCOLUMN 0x10
#define SETLOWCOLUMN 0x00
#define SETMULTIPLEX 0xA8
#define SETPRECHARGE 0xD9
#define SETSEGMENTREMAP 0xA1
#define SETSTARTLINE 0x40
#define SETVCOMDETECT 0xDB
#define SWITCHCAPVCC 0x2
class SSD1306 {
private:
int myI2cAddress;
int mySda;
int mySdc;
uint8_t buffer[128 * 64 / 8];
int myTextAlignment = TEXT_ALIGN_LEFT;
int myColor = WHITE;
byte lastChar;
const char *myFontData = ArialMT_Plain_10;
public:
// Create the display object connected to pin sda and sdc
SSD1306(int i2cAddress, int sda, int sdc);
// Initialize the display
void init();
// Initialize the display - Neil's version to setting of address
void init(int i2cAddress); //local override to allow init to set the address
// Cycle through the initialization
void resetDisplay(void);
// Connect again to the display through I2C
void reconnect(void);
// Turn the display on
void displayOn(void);
// Turn the display offs
void displayOff(void);
// Clear the local pixel buffer
void clear(void);
// Write the buffer to the display memory
void display(void);
// Set display contrast
void setContrast(char contrast);
// Turn the display upside down
void flipScreenVertically();
// Send a command to the display (low level function)
void sendCommand(unsigned char com);
// Send all the init commands
void sendInitCommands(void);
// Draw a pixel at given position
void setPixel(int x, int y);
// Draw 8 bits at the given position
void setChar(int x, int y, unsigned char data);
// Draw the border of a rectangle at the given location
void drawRect(int x, int y, int width, int height);
// Fill the rectangle
void fillRect(int x, int y, int width, int height);
// Draw a bitmap with the given dimensions
void drawBitmap(int x, int y, int width, int height, const char *bitmap);
// Draw an XBM image with the given dimensions
void drawXbm(int x, int y, int width, int height, const char *xbm);
// Sets the color of all pixel operations
void setColor(int color);
// converts utf8 characters to extended ascii
// taken from http://playground.arduino.cc/Main/Utf8ascii
byte utf8ascii(byte ascii);
// converts utf8 string to extended ascii
// taken from http://playground.arduino.cc/Main/Utf8ascii
String utf8ascii(String s);
// Draws a string at the given location
void drawString(int x, int y, String text);
// Draws a String with a maximum width at the given location.
// If the given String is wider than the specified width
// The text will be wrapped to the next line at a space or dash
void drawStringMaxWidth(int x, int y, int maxLineWidth, String text);
// Returns the width of the String with the current
// font settings
int getStringWidth(String text);
// Specifies relative to which anchor point
// the text is rendered. Available constants:
// TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT
void setTextAlignment(int textAlignment);
// Sets the current font. Available default fonts
// defined in SSD1306Fonts.h:
// ArialMT_Plain_10, ArialMT_Plain_16, ArialMT_Plain_24
void setFont(const char *fontData);
};
#endif
+149
View File
@@ -0,0 +1,149 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#ifndef SSD1306Brzo_h
#define SSD1306Brzo_h
#include "OLEDDisplay.h"
#include <brzo_i2c.h>
#if F_CPU == 160000000L
#define BRZO_I2C_SPEED 1000
#else
#define BRZO_I2C_SPEED 800
#endif
class SSD1306Brzo : public OLEDDisplay {
private:
uint8_t _address;
uint8_t _sda;
uint8_t _scl;
public:
SSD1306Brzo(uint8_t _address, uint8_t _sda, uint8_t _scl) {
this->_address = _address;
this->_sda = _sda;
this->_scl = _scl;
}
bool connect(){
brzo_i2c_setup(_sda, _scl, 0);
return true;
}
void display(void) {
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
uint8_t minBoundY = ~0;
uint8_t maxBoundY = 0;
uint8_t minBoundX = ~0;
uint8_t maxBoundX = 0;
uint8_t x, y;
// Calculate the Y bounding box of changes
// and copy buffer[pos] to buffer_back[pos];
for (y = 0; y < (DISPLAY_HEIGHT / 8); y++) {
for (x = 0; x < DISPLAY_WIDTH; x++) {
uint16_t pos = x + y * DISPLAY_WIDTH;
if (buffer[pos] != buffer_back[pos]) {
minBoundY = _min(minBoundY, y);
maxBoundY = _max(maxBoundY, y);
minBoundX = _min(minBoundX, x);
maxBoundX = _max(maxBoundX, x);
}
buffer_back[pos] = buffer[pos];
}
yield();
}
// If the minBoundY wasn't updated
// we can savely assume that buffer_back[pos] == buffer[pos]
// holdes true for all values of pos
if (minBoundY == ~0) return;
sendCommand(COLUMNADDR);
sendCommand(minBoundX);
sendCommand(maxBoundX);
sendCommand(PAGEADDR);
sendCommand(minBoundY);
sendCommand(maxBoundY);
byte k = 0;
uint8_t sendBuffer[17];
sendBuffer[0] = 0x40;
brzo_i2c_start_transaction(this->_address, BRZO_I2C_SPEED);
for (y = minBoundY; y <= maxBoundY; y++) {
for (x = minBoundX; x <= maxBoundX; x++) {
k++;
sendBuffer[k] = buffer[x + y * DISPLAY_WIDTH];
if (k == 16) {
brzo_i2c_write(sendBuffer, 17, true);
k = 0;
}
}
yield();
}
brzo_i2c_write(sendBuffer, k + 1, true);
brzo_i2c_end_transaction();
#else
// No double buffering
sendCommand(COLUMNADDR);
sendCommand(0x0);
sendCommand(0x7F);
sendCommand(PAGEADDR);
sendCommand(0x0);
sendCommand(0x7);
uint8_t sendBuffer[17];
sendBuffer[0] = 0x40;
brzo_i2c_start_transaction(this->_address, BRZO_I2C_SPEED);
for (uint16_t i=0; i<DISPLAY_BUFFER_SIZE; i++) {
for (uint8_t x=1; x<17; x++) {
sendBuffer[x] = buffer[i];
i++;
}
i--;
brzo_i2c_write(sendBuffer, 17, true);
yield();
}
brzo_i2c_end_transaction();
#endif
}
private:
inline void sendCommand(uint8_t com) __attribute__((always_inline)){
uint8_t command[2] = {0x80 /* command mode */, com};
brzo_i2c_start_transaction(_address, BRZO_I2C_SPEED);
brzo_i2c_write(command, 2, true);
brzo_i2c_end_transaction();
}
};
#endif
File diff suppressed because it is too large Load Diff
+150
View File
@@ -0,0 +1,150 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#ifndef SSD1306Spi_h
#define SSD1306Spi_h
#include "OLEDDisplay.h"
#include <SPI.h>
#if F_CPU == 160000000L
#define BRZO_I2C_SPEED 1000
#else
#define BRZO_I2C_SPEED 800
#endif
class SSD1306Spi : public OLEDDisplay {
private:
uint8_t _rst;
uint8_t _dc;
uint8_t _cs;
public:
SSD1306Spi(uint8_t _rst, uint8_t _dc, uint8_t _cs) {
this->_rst = _rst;
this->_dc = _dc;
this->_cs = _cs;
}
bool connect(){
pinMode(_dc, OUTPUT);
pinMode(_cs, OUTPUT);
pinMode(_rst, OUTPUT);
SPI.begin ();
SPI.setClockDivider (SPI_CLOCK_DIV2);
// Pulse Reset low for 10ms
digitalWrite(_rst, HIGH);
delay(1);
digitalWrite(_rst, LOW);
delay(10);
digitalWrite(_rst, HIGH);
return true;
}
void display(void) {
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
uint8_t minBoundY = ~0;
uint8_t maxBoundY = 0;
uint8_t minBoundX = ~0;
uint8_t maxBoundX = 0;
uint8_t x, y;
// Calculate the Y bounding box of changes
// and copy buffer[pos] to buffer_back[pos];
for (y = 0; y < (DISPLAY_HEIGHT / 8); y++) {
for (x = 0; x < DISPLAY_WIDTH; x++) {
uint16_t pos = x + y * DISPLAY_WIDTH;
if (buffer[pos] != buffer_back[pos]) {
minBoundY = _min(minBoundY, y);
maxBoundY = _max(maxBoundY, y);
minBoundX = _min(minBoundX, x);
maxBoundX = _max(maxBoundX, x);
}
buffer_back[pos] = buffer[pos];
}
yield();
}
// If the minBoundY wasn't updated
// we can savely assume that buffer_back[pos] == buffer[pos]
// holdes true for all values of pos
if (minBoundY == ~0) return;
sendCommand(COLUMNADDR);
sendCommand(minBoundX);
sendCommand(maxBoundX);
sendCommand(PAGEADDR);
sendCommand(minBoundY);
sendCommand(maxBoundY);
digitalWrite(_cs, HIGH);
digitalWrite(_dc, HIGH); // data mode
digitalWrite(_cs, LOW);
for (y = minBoundY; y <= maxBoundY; y++) {
for (x = minBoundX; x <= maxBoundX; x++) {
SPI.transfer(buffer[x + y * DISPLAY_WIDTH]);
}
yield();
}
digitalWrite(_cs, HIGH);
#else
// No double buffering
sendCommand(COLUMNADDR);
sendCommand(0x0);
sendCommand(0x7F);
sendCommand(PAGEADDR);
sendCommand(0x0);
sendCommand(0x7);
digitalWrite(_cs, HIGH);
digitalWrite(_dc, HIGH); // data mode
digitalWrite(_cs, LOW);
for (uint16_t i=0; i<DISPLAY_BUFFER_SIZE; i++) {
SPI.transfer(buffer[i]);
yield();
}
digitalWrite(_cs, HIGH);
#endif
}
private:
inline void sendCommand(uint8_t com) __attribute__((always_inline)){
digitalWrite(_cs, HIGH);
digitalWrite(_dc, LOW);
digitalWrite(_cs, LOW);
SPI.transfer(com);
digitalWrite(_cs, HIGH);
}
};
#endif
-247
View File
@@ -1,247 +0,0 @@
#include "SSD1306Ui.h"
SSD1306Ui::SSD1306Ui(SSD1306 *display) {
this->display = display;
}
void SSD1306Ui::init() {
this->display->init();
}
void SSD1306Ui::setTargetFPS(byte fps){
int oldInterval = this->updateInterval;
this->updateInterval = ((float) 1.0 / (float) fps) * 1000;
// Calculate new ticksPerFrame
float changeRatio = oldInterval / this->updateInterval;
this->ticksPerFrame *= changeRatio;
this->ticksPerTransition *= changeRatio;
}
// -/------ Automatic controll ------\-
void SSD1306Ui::enableAutoTransition(){
this->autoTransition = true;
}
void SSD1306Ui::disableAutoTransition(){
this->autoTransition = false;
}
void SSD1306Ui::setAutoTransitionForwards(){
this->frameTransitionDirection = 1;
}
void SSD1306Ui::setAutoTransitionBackwards(){
this->frameTransitionDirection = 1;
}
void SSD1306Ui::setTimePerFrame(int time){
this->ticksPerFrame = (int) ( (float) time / (float) updateInterval);
}
void SSD1306Ui::setTimePerTransition(int time){
this->ticksPerTransition = (int) ( (float) time / (float) updateInterval);
}
// -/------ Customize indicator position and style -------\-
void SSD1306Ui::setIndicatorPosition(IndicatorPosition pos) {
this->indicatorPosition = pos;
this->dirty = true;
}
void SSD1306Ui::setIndicatorDirection(IndicatorDirection dir) {
this->indicatorDirection = dir;
}
void SSD1306Ui::setActiveSymbole(const char* symbole) {
this->activeSymbole = symbole;
this->dirty = true;
}
void SSD1306Ui::setInactiveSymbole(const char* symbole) {
this->inactiveSymbole = symbole;
this->dirty = true;
}
// -/----- Frame settings -----\-
void SSD1306Ui::setFrameAnimation(AnimationDirection dir) {
this->frameAnimationDirection = dir;
}
void SSD1306Ui::setFrames(FrameCallback* frameFunctions, int frameCount) {
this->frameCount = frameCount;
this->frameFunctions = frameFunctions;
}
// -/----- Overlays ------\-
void SSD1306Ui::setOverlays(OverlayCallback* overlayFunctions, int overlayCount){
this->overlayCount = overlayCount;
this->overlayFunctions = overlayFunctions;
}
// -/----- Manuel control -----\-
void SSD1306Ui::nextFrame() {
this->state.frameState = IN_TRANSITION;
this->state.ticksSinceLastStateSwitch = 0;
this->frameTransitionDirection = 1;
}
void SSD1306Ui::previousFrame() {
this->state.frameState = IN_TRANSITION;
this->state.ticksSinceLastStateSwitch = 0;
this->frameTransitionDirection = -1;
}
// -/----- State information -----\-
SSD1306UiState SSD1306Ui::getUiState(){
return this->state;
}
int SSD1306Ui::update(){
int timeBudget = this->updateInterval - (millis() - this->state.lastUpdate);
if ( timeBudget <= 0) {
// Implement frame skipping to ensure time budget is keept
if (this->autoTransition && this->state.lastUpdate != 0) this->state.ticksSinceLastStateSwitch += ceil(-timeBudget / this->updateInterval);
this->state.lastUpdate = millis();
this->tick();
}
return timeBudget;
}
void SSD1306Ui::tick() {
this->state.ticksSinceLastStateSwitch++;
switch (this->state.frameState) {
case IN_TRANSITION:
this->dirty = true;
if (this->state.ticksSinceLastStateSwitch >= this->ticksPerTransition){
this->state.frameState = FIXED;
this->state.currentFrame = getNextFrameNumber();
this->state.ticksSinceLastStateSwitch = 0;
}
break;
case FIXED:
if (this->state.ticksSinceLastStateSwitch >= this->ticksPerFrame){
if (this->autoTransition){
this->state.frameState = IN_TRANSITION;
this->dirty = true;
}
this->state.ticksSinceLastStateSwitch = 0;
}
break;
}
if (this->dirty) {
this->dirty = false;
this->display->clear();
this->drawIndicator();
this->drawFrame();
this->drawOverlays();
this->display->display();
}
}
void SSD1306Ui::drawFrame(){
switch (this->state.frameState){
case IN_TRANSITION: {
float progress = (float) this->state.ticksSinceLastStateSwitch / (float) this->ticksPerTransition;
int x, y, x1, y1;
switch(this->frameAnimationDirection){
case SLIDE_LEFT:
x = -128 * progress;
y = 0;
x1 = x + 128;
y1 = 0;
break;
case SLIDE_RIGHT:
x = 128 * progress;
y = 0;
x1 = x - 128;
y1 = 0;
break;
case SLIDE_UP:
x = 0;
y = -64 * progress;
x1 = 0;
y1 = y + 64;
break;
case SLIDE_DOWN:
x = 0;
y = 64 * progress;
x1 = 0;
y1 = y - 64;
break;
}
// Invert animation if direction is reversed.
int dir = frameTransitionDirection >= 0 ? 1 : -1;
x *= dir; y *= dir; x1 *= dir; y1 *= dir;
this->dirty |= (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, x, y);
this->dirty |= (this->frameFunctions[this->getNextFrameNumber()])(this->display, &this->state, x1, y1);
break;
}
case FIXED:
this->dirty |= (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, 0, 0);
break;
}
}
void SSD1306Ui::drawIndicator() {
byte posOfCurrentFrame;
switch (this->indicatorDirection){
case LEFT_RIGHT:
posOfCurrentFrame = this->state.currentFrame;
break;
case RIGHT_LEFT:
posOfCurrentFrame = (this->frameCount - 1) - this->state.currentFrame;
break;
}
for (byte i = 0; i < this->frameCount; i++) {
const char *image;
if (posOfCurrentFrame == i) {
image = this->activeSymbole;
} else {
image = this->inactiveSymbole;
}
int x,y;
switch (this->indicatorPosition){
case TOP:
y = 0;
x = 64 - (12 * frameCount / 2) + 12 * i;
break;
case BOTTOM:
y = 56;
x = 64 - (12 * frameCount / 2) + 12 * i;
break;
case RIGHT:
x = 120;
y = 32 - (12 * frameCount / 2) + 12 * i;
break;
case LEFT:
x = 0;
y = 32 - (12 * frameCount / 2) + 12 * i;
break;
}
this->display->drawXbm(x, y, 8, 8, image);
}
}
void SSD1306Ui::drawOverlays() {
for (int i=0;i<this->overlayCount;i++){
this->dirty |= (this->overlayFunctions[i])(this->display, &this->state);
}
}
int SSD1306Ui::getNextFrameNumber(){
int nextFrame = (this->state.currentFrame + this->frameTransitionDirection) % this->frameCount;
if (nextFrame < 0){
nextFrame = this->frameCount + nextFrame;
}
return nextFrame;
}
-209
View File
@@ -1,209 +0,0 @@
/**The MIT License (MIT)
Copyright (c) 2015 by Fabrice Weinberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Credits for parts of this code go to Daniel Eichhorn
*/
#pragma once
#include <Arduino.h>
#include "../esp8266-oled-ssd1306/SSD1306.h"
enum AnimationDirection {
SLIDE_UP,
SLIDE_DOWN,
SLIDE_LEFT,
SLIDE_RIGHT
};
enum IndicatorPosition {
TOP,
RIGHT,
BOTTOM,
LEFT
};
enum IndicatorDirection {
LEFT_RIGHT,
RIGHT_LEFT
};
enum FrameState {
IN_TRANSITION,
FIXED
};
const char ANIMATION_activeSymbole[] PROGMEM = {
0x00, 0x18, 0x3c, 0x7e, 0x7e, 0x3c, 0x18, 0x00
};
const char ANIMATION_inactiveSymbole[] PROGMEM = {
0x00, 0x0, 0x0, 0x18, 0x18, 0x0, 0x0, 0x00
};
// Structure of the UiState
struct SSD1306UiState {
int lastUpdate = 0;
int ticksSinceLastStateSwitch = 0;
FrameState frameState = FIXED;
int currentFrame = 0;
};
typedef bool (*FrameCallback)(SSD1306 *display, SSD1306UiState* state, int x, int y);
typedef bool (*OverlayCallback)(SSD1306 *display, SSD1306UiState* state);
class SSD1306Ui {
private:
SSD1306 *display;
// Global dirty flag to indicate that the display needs to be redraw.
bool dirty = true;
// Symboles for the Indicator
IndicatorPosition indicatorPosition = BOTTOM;
IndicatorDirection indicatorDirection = LEFT_RIGHT;
const char* activeSymbole = ANIMATION_activeSymbole;
const char* inactiveSymbole = ANIMATION_inactiveSymbole;
// Values for the Frames
AnimationDirection frameAnimationDirection = SLIDE_RIGHT;
int frameTransitionDirection = 1;
int ticksPerFrame = 151; // ~ 5000ms at 30 FPS
int ticksPerTransition = 15; // ~ 500ms at 30 FPS
bool autoTransition = true;
FrameCallback* frameFunctions;
int frameCount = 0;
// Values for Overlays
OverlayCallback* overlayFunctions;
int overlayCount = 0;
// UI State
SSD1306UiState state;
// Bookeeping for update
int updateInterval = 33;
int getNextFrameNumber();
void drawIndicator();
void drawFrame();
void drawOverlays();
void tick();
public:
SSD1306Ui(SSD1306 *display);
/**
* Initialise the display
*/
void init();
/**
* Configure the internal used target FPS
*/
void setTargetFPS(byte fps);
// Automatic Controll
/**
* Enable automatic transition to next frame after the some time can be configured with `setTimePerFrame` and `setTimePerTransition`.
*/
void enableAutoTransition();
/**
* Disable automatic transition to next frame.
*/
void disableAutoTransition();
/**
* Set the direction if the automatic transitioning
*/
void setAutoTransitionForwards();
void setAutoTransitionBackwards();
/**
* Set the approx. time a frame is displayed
*/
void setTimePerFrame(int time);
/**
* Set the approx. time a transition will take
*/
void setTimePerTransition(int time);
// Customize indicator position and style
/**
* Set the position of the indicator bar.
*/
void setIndicatorPosition(IndicatorPosition pos);
/**
* Set the direction of the indicator bar. Defining the order of frames ASCENDING / DESCENDING
*/
void setIndicatorDirection(IndicatorDirection dir);
/**
* Set the symbole to indicate an active frame in the indicator bar.
*/
void setActiveSymbole(const char* symbole);
/**
* Set the symbole to indicate an inactive frame in the indicator bar.
*/
void setInactiveSymbole(const char* symbole);
// Frame settings
/**
* Configure what animation is used to transition from one frame to another
*/
void setFrameAnimation(AnimationDirection dir);
/**
* Add frame drawing functions
*/
void setFrames(FrameCallback* frameFunctions, int frameCount);
// Overlay
/**
* Add overlays drawing functions that are draw independent of the Frames
*/
void setOverlays(OverlayCallback* overlayFunctions, int overlayCount);
// Manuell Controll
void nextFrame();
void previousFrame();
// State Info
SSD1306UiState getUiState();
int update();
};
+149
View File
@@ -0,0 +1,149 @@
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Credits for parts of this code go to Mike Rankin. Thank you so much for sharing!
*/
#ifndef SSD1306Wire_h
#define SSD1306Wire_h
#include "OLEDDisplay.h"
#include <Wire.h>
class SSD1306Wire : public OLEDDisplay {
private:
uint8_t _address;
uint8_t _sda;
uint8_t _scl;
public:
SSD1306Wire(uint8_t _address, uint8_t _sda, uint8_t _scl, int width = DISPLAY_WIDTH, int height = DISPLAY_HEIGHT)
: OLEDDisplay(width, height) {
this->_address = _address;
this->_sda = _sda;
this->_scl = _scl;
}
bool connect() {
Wire.begin(this->_sda, this->_scl);
// Let's use ~700khz if ESP8266 is in 160Mhz mode
// this will be limited to ~400khz if the ESP8266 in 80Mhz mode.
Wire.setClock(700000);
return true;
}
void display(void) {
const int x_offset = (128 - this->width()) / 2;
#ifdef OLEDDISPLAY_DOUBLE_BUFFER
uint8_t minBoundY = ~0;
uint8_t maxBoundY = 0;
uint8_t minBoundX = ~0;
uint8_t maxBoundX = 0;
uint8_t x, y;
// Calculate the Y bounding box of changes
// and copy buffer[pos] to buffer_back[pos];
for (y = 0; y < (this->height() / 8); y++) {
for (x = 0; x < this->width(); x++) {
uint16_t pos = x + y * this->width();
if (buffer[pos] != buffer_back[pos]) {
minBoundY = _min(minBoundY, y);
maxBoundY = _max(maxBoundY, y);
minBoundX = _min(minBoundX, x);
maxBoundX = _max(maxBoundX, x);
}
buffer_back[pos] = buffer[pos];
}
yield();
}
// If the minBoundY wasn't updated
// we can savely assume that buffer_back[pos] == buffer[pos]
// holdes true for all values of pos
if (minBoundY == (uint8_t)(~0)) return;
sendCommand(COLUMNADDR);
sendCommand(x_offset + minBoundX);
sendCommand(x_offset + maxBoundX);
sendCommand(PAGEADDR);
sendCommand(minBoundY);
sendCommand(maxBoundY);
byte k = 0;
for (y = minBoundY; y <= maxBoundY; y++) {
for (x = minBoundX; x <= maxBoundX; x++) {
if (k == 0) {
Wire.beginTransmission(_address);
Wire.write(0x40);
}
Wire.write(buffer[x + y * this->width()]);
k++;
if (k == 16) {
Wire.endTransmission();
k = 0;
}
}
yield();
}
if (k != 0) {
Wire.endTransmission();
}
#else
sendCommand(COLUMNADDR);
sendCommand(x_offset);
sendCommand(x_offset + (this->width() - 1));
sendCommand(PAGEADDR);
sendCommand(0x0);
sendCommand((this->height() / 8) - 1);
for (uint16_t i=0; i < DISPLAY_BUFFER_SIZE; i++) {
Wire.beginTransmission(this->_address);
Wire.write(0x40);
for (uint8_t x = 0; x < 16; x++) {
Wire.write(buffer[i]);
i++;
}
i--;
Wire.endTransmission();
}
#endif
}
private:
inline void sendCommand(uint8_t command) __attribute__((always_inline)){
Wire.beginTransmission(_address);
Wire.write(0x80);
Wire.write(command);
Wire.endTransmission();
}
};
#endif
+125
View File
@@ -0,0 +1,125 @@
# Upgrade from 2.0 to 3.0
While developing version 3.0 we made some breaking changes to the public
API of this library. This document will help you update your code to work with
version 3.0
## Font Definitions
To get better performance and a smaller font definition format, we change the memory
layout of the font definition format. If you are using custom fonts not included in
this library we updated the font generator [here](http://oleddisplay.squix.ch/#/home).
Please update your fonts to be working with 3.0 by selecting the respective version in the dropdown.
## Architectural Changes
To become a more versatile library for the SSD1306 chipset we abstracted the
hardware connection into subclasses of the base display class now called `OLEDDisplay`.
This library is currently shipping with three implementations:
* `SSD1306Wire` implementing the I2C protocol using the Wire Library.
* `SSD1306Brzo` implementing the I2C protocol using the faster [`brzo_i2c`](https://github.com/pasko-zh/brzo_i2c) library.
* `SSD1306Spi` implementing the SPI protocol.
To keep backwards compatiblity with the old API `SSD1306` is an alias of `SSD1306Wire`.
If you are not using the UI components you don't have to change anything to keep your code working.
## Name Changes
[Naming things is hard](http://martinfowler.com/bliki/TwoHardThings.html), to better reflect our intention with this library
we changed the name of the base class to `OLEDDisplay` and the UI library accordingly to `OLEDDisplayUi`.
As a consequence the type definitions of all frame and overlay related functions changed.
This means that you have to update all your frame drawing callbacks from:
```c
bool frame1(SSD1306 *display, SSD1306UiState* state, int x, int y);
```
too
```c
void frame1(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y);
```
And your overlay drawing functions from:
```c
bool overlay1(SSD1306 *display, SSD1306UiState* state);
```
too
```c
void overlay1(OLEDDisplay *display, OLEDDisplayUiState* state);
```
## New Features
### Loading Animation
While using this library ourself we noticed a pattern emerging. We want to drawing
a loading progress while connecting to WiFi and updating weather data etc.
The simplest thing was to add the function `drawProgressBar(x, y, width, height, progress)`
,where `progress` is between `0` and `100`, right to the `OLEDDisplay` class.
But we didn't stop there. We added a new feature to the `OLEDDisplayUi` called `LoadingStages`.
You can define your loading process like this:
```c++
LoadingStage loadingStages[] = {
{
.process = "Connect to WiFi",
.callback = []() {
// Connect to WiFi
}
},
{
.process = "Get time from NTP",
.callback = []() {
// Get current time via NTP
}
}
// more steps
};
int LOADING_STAGES_COUNT = sizeof(loadingStages) / sizeof(LoadingStage);
```
After defining your array of `LoadingStages` you can then run the loading process by using
`ui.runLoadingProcess(loadingStages, LOADING_STAGES_COUNT)`. This will give you a
nice little loading animation you can see in the beginning of [this](https://vimeo.com/168362918)
video.
To further customize this you are free to define your own `LoadingDrawFunction` like this:
```c
void myLoadingDraw(OLEDDisplay *display, LoadingStage* stage, uint8_t progress) {
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->setFont(ArialMT_Plain_10);
// stage->process contains the text of the current progress e.q. "Connect to WiFi"
display->drawString(64, 18, stage->process);
// you could just print the current process without the progress bar
display->drawString(64, 28, progress);
}
```
After defining a function like that, you can pass it to the Ui library by use
`ui.setLoadingDrawFunction(myLoadingDraw)`.
### Text Logging
It is always useful to display some text on the display without worrying to much
where it goes and managing it. In 3.0 we made the `OLEDDisplay` class implement
[`Print`](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Print.h)
so you can use it like you would use `Serial`. We calls this feature `LogBuffer`
and the only thing you have to do is to define how many lines you want to display
and how many characters there are on average on each. This is done by calling
`setLogBuffer(lines, chars);`. If there is not enough memory the function will
return false.
After that you can draw the `LogBuffer` anywhere you want by calling `drawLogBuffer(x, y)`.
(Note: You have to call `display()` to update the screen)
We made a [video](https://www.youtube.com/watch?v=8Fiss77A3TE) showing this feature in action.
@@ -1,151 +0,0 @@
/**The MIT License (MIT)
Copyright (c) 2015 by Daniel Eichhorn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
See more at http://blog.squix.ch
*/
#include <Wire.h>
#include "SSD1306.h"
#include "SSD1306Ui.h"
#include "images.h"
// Initialize the oled display for address 0x3c
// sda-pin=14 and sdc-pin=12
SSD1306 display(0x3c, D3, D4);
SSD1306Ui ui ( &display );
// this array keeps function pointers to all frames
// frames are the single views that slide from right to left
bool (*frames[])(SSD1306 *display, SSD1306UiState* state, int x, int y) = { drawFrame1, drawFrame2, drawFrame3, drawFrame4 };
// how many frames are there?
int frameCount = 4;
bool (*overlays[])(SSD1306 *display, SSD1306UiState* state) = { msOverlay };
int overlaysCount = 1;
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
ui.setTargetFPS(30);
ui.setActiveSymbole(activeSymbole);
ui.setInactiveSymbole(inactiveSymbole);
// You can change this to
// TOP, LEFT, BOTTOM, RIGHT
ui.setIndicatorPosition(BOTTOM);
// Defines where the first frame is located in the bar.
ui.setIndicatorDirection(LEFT_RIGHT);
// You can change the transition that is used
// SLIDE_LEFT, SLIDE_RIGHT, SLIDE_TOP, SLIDE_DOWN
ui.setFrameAnimation(SLIDE_LEFT);
// Add frames
ui.setFrames(frames, frameCount);
// Add overlays
ui.setOverlays(overlays, overlaysCount);
// Inital UI takes care of initalising the display too.
ui.init();
display.flipScreenVertically();
}
void loop() {
int remainingTimeBudget = ui.update();
if (remainingTimeBudget > 0) {
// You can do some work here
// Don't do stuff if you are below your
// time budget.
delay(remainingTimeBudget);
}
}
bool msOverlay(SSD1306 *display, SSD1306UiState* state) {
display->setTextAlignment(TEXT_ALIGN_RIGHT);
display->setFont(ArialMT_Plain_10);
display->drawString(128, 0, String(millis()));
return true;
}
bool drawFrame1(SSD1306 *display, SSD1306UiState* state, int x, int y) {
// draw an xbm image.
// Please note that everything that should be transitioned
// needs to be drawn relative to x and y
// if this frame need to be refreshed at the targetFPS you need to
// return true
display->drawXbm(x + 34, y + 14, WiFi_Logo_width, WiFi_Logo_height, WiFi_Logo_bits);
return false;
}
bool drawFrame2(SSD1306 *display, SSD1306UiState* state, int x, int y) {
// Demonstrates the 3 included default sizes. The fonts come from SSD1306Fonts.h file
// Besides the default fonts there will be a program to convert TrueType fonts into this format
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->setFont(ArialMT_Plain_10);
display->drawString(0 + x, 10 + y, "Arial 10");
display->setFont(ArialMT_Plain_16);
display->drawString(0 + x, 20 + y, "Arial 16");
display->setFont(ArialMT_Plain_24);
display->drawString(0 + x, 34 + y, "Arial 24");
return false;
}
bool drawFrame3(SSD1306 *display, SSD1306UiState* state, int x, int y) {
// Text alignment demo
display->setFont(ArialMT_Plain_10);
// The coordinates define the left starting point of the text
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->drawString(0 + x, 11 + y, "Left aligned (0,10)");
// The coordinates define the center of the text
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->drawString(64 + x, 22, "Center aligned (64,22)");
// The coordinates define the right end of the text
display->setTextAlignment(TEXT_ALIGN_RIGHT);
display->drawString(128 + x, 33, "Right aligned (128,33)");
return false;
}
bool drawFrame4(SSD1306 *display, SSD1306UiState* state, int x, int y) {
// Demo for drawStringMaxWidth:
// with the third parameter you can define the width after which words will be wrapped.
// Currently only spaces and "-" are allowed for wrapping
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->setFont(ArialMT_Plain_10);
display->drawStringMaxWidth(0 + x, 10 + y, 128, "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore.");
return false;
}
@@ -1,50 +0,0 @@
#define WiFi_Logo_width 60
#define WiFi_Logo_height 36
const char WiFi_Logo_bits[] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x07, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE0, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF,
0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
0xFF, 0x03, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x07, 0xC0, 0x83, 0x01, 0x80, 0xFF, 0xFF, 0xFF,
0x01, 0x00, 0x07, 0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x0C, 0x00,
0xC0, 0xFF, 0xFF, 0x7C, 0x00, 0x60, 0x0C, 0x00, 0xC0, 0x31, 0x46, 0x7C,
0xFC, 0x77, 0x08, 0x00, 0xE0, 0x23, 0xC6, 0x3C, 0xFC, 0x67, 0x18, 0x00,
0xE0, 0x23, 0xE4, 0x3F, 0x1C, 0x00, 0x18, 0x00, 0xE0, 0x23, 0x60, 0x3C,
0x1C, 0x70, 0x18, 0x00, 0xE0, 0x03, 0x60, 0x3C, 0x1C, 0x70, 0x18, 0x00,
0xE0, 0x07, 0x60, 0x3C, 0xFC, 0x73, 0x18, 0x00, 0xE0, 0x87, 0x70, 0x3C,
0xFC, 0x73, 0x18, 0x00, 0xE0, 0x87, 0x70, 0x3C, 0x1C, 0x70, 0x18, 0x00,
0xE0, 0x87, 0x70, 0x3C, 0x1C, 0x70, 0x18, 0x00, 0xE0, 0x8F, 0x71, 0x3C,
0x1C, 0x70, 0x18, 0x00, 0xC0, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x08, 0x00,
0xC0, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x0C, 0x00, 0x80, 0xFF, 0xFF, 0x1F,
0x00, 0x00, 0x06, 0x00, 0x80, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x07, 0x00,
0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0xF8, 0xFF, 0xFF,
0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x01, 0x00, 0x00,
0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF,
0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x1F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const char activeSymbole[] PROGMEM = {
B00000000,
B00000000,
B00011000,
B00100100,
B01000010,
B01000010,
B00100100,
B00011000
};
const char inactiveSymbole[] PROGMEM = {
B00000000,
B00000000,
B00000000,
B00000000,
B00011000,
B00011000,
B00000000,
B00000000
};
-51
View File
@@ -1,51 +0,0 @@
#define WiFi_Logo_width 60
#define WiFi_Logo_height 36
const char WiFi_Logo_bits[] PROGMEM = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFF, 0x07, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE0, 0xFF, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF,
0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
0xFF, 0x03, 0x00, 0x00, 0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0xFF, 0x07, 0xC0, 0x83, 0x01, 0x80, 0xFF, 0xFF, 0xFF,
0x01, 0x00, 0x07, 0x00, 0xC0, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x0C, 0x00,
0xC0, 0xFF, 0xFF, 0x7C, 0x00, 0x60, 0x0C, 0x00, 0xC0, 0x31, 0x46, 0x7C,
0xFC, 0x77, 0x08, 0x00, 0xE0, 0x23, 0xC6, 0x3C, 0xFC, 0x67, 0x18, 0x00,
0xE0, 0x23, 0xE4, 0x3F, 0x1C, 0x00, 0x18, 0x00, 0xE0, 0x23, 0x60, 0x3C,
0x1C, 0x70, 0x18, 0x00, 0xE0, 0x03, 0x60, 0x3C, 0x1C, 0x70, 0x18, 0x00,
0xE0, 0x07, 0x60, 0x3C, 0xFC, 0x73, 0x18, 0x00, 0xE0, 0x87, 0x70, 0x3C,
0xFC, 0x73, 0x18, 0x00, 0xE0, 0x87, 0x70, 0x3C, 0x1C, 0x70, 0x18, 0x00,
0xE0, 0x87, 0x70, 0x3C, 0x1C, 0x70, 0x18, 0x00, 0xE0, 0x8F, 0x71, 0x3C,
0x1C, 0x70, 0x18, 0x00, 0xC0, 0xFF, 0xFF, 0x3F, 0x00, 0x00, 0x08, 0x00,
0xC0, 0xFF, 0xFF, 0x1F, 0x00, 0x00, 0x0C, 0x00, 0x80, 0xFF, 0xFF, 0x1F,
0x00, 0x00, 0x06, 0x00, 0x80, 0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x07, 0x00,
0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0xF8, 0xFF, 0xFF,
0xFF, 0x7F, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0x01, 0x00, 0x00,
0x00, 0x00, 0xFC, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xFF,
0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xFF, 0x1F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0xFF, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const char activeSymbole[] PROGMEM = {
B00000000,
B00000000,
B00011000,
B00100100,
B01000010,
B01000010,
B00100100,
B00011000
};
const char inactiveSymbole[] PROGMEM = {
B00000000,
B00000000,
B00000000,
B00000000,
B00011000,
B00011000,
B00000000,
B00000000
};
+21 -15
View File
@@ -1,22 +1,28 @@
{
"name": "ESP8266 Oled Driver for SSD1306 display",
"keywords": "Display, ssd1306, arduino, esp8266",
"description": "SSD1306 Oled driver which offers scrolling frames, custom fonts, etc",
"repository": {
"name": "ESP8266_SSD1306",
"version": "3.2.7",
"keywords": "ssd1306, oled, display, i2c",
"description": "A I2C display driver for SSD1306 oled displays connected to an ESP8266 or ESP32",
"repository":
{
"type": "git",
"url": "https://github.com/squix78/esp8266-oled-ssd1306.git"
},
"authors": [{
"name": "Daniel Eichhorn",
"url": "http://blog.squix.ch",
"email": "squix78@gmail.com",
"maintainer": true
},
{
"name": "Fabrice Weinberg"
}
"authors":
[
{
"name": "Daniel Eichhorn",
"email": "squix78@gmail.com",
"url": "http://blog.squix.ch"
},
{
"name": "Fabrice Weinberg",
"email": "fabrice@weinberg.me"
}
],
"frameworks": "arduino",
"platforms": "espressif",
"version": "2.0.1"
"platforms": [
"espressif8266",
"espressif32"
]
}
+5 -5
View File
@@ -1,9 +1,9 @@
name=ESP8266 Oled Driver for SSD1306 display
version=2.0.0
name=ESP8266 and ESP32 Oled Driver for SSD1306 display
version=3.2.7
author=Daniel Eichhorn, Fabrice Weinberg
maintainer=Daniel Eichhorn <squix78@gmail.com>
sentence=A display driver for SSD1306 oled displays connected to an ESP8266
paragraph=A display driver for SSD1306 oled displays connected to an ESP8266
sentence=A I2C display driver for SSD1306 oled displays connected to an ESP8266 or ESP32
paragraph=A I2C display driver for SSD1306 oled displays connected to an ESP8266 or ESP32
category=Display
url=https://github.com/squix78/esp8266-oled-ssd1306
architectures=esp8266
architectures=esp8266,esp32
+2 -1
View File
@@ -1,6 +1,7 @@
The MIT License (MIT)
Copyright (c) 2015 by Daniel Eichhorn
Copyright (c) 2016 by Daniel Eichhorn
Copyright (c) 2016 by Fabrice Weinberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

+3 -3
View File
@@ -244,7 +244,7 @@ uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
buffer[len++] = digit;
length += (digit & 127) * multiplier;
multiplier *= 128;
} while ((digit & 128) != 0);
} while ((digit & 128) != 0 && len < (MQTT_MAX_PACKET_SIZE -2));
*lengthLength = len-1;
if (isPublish) {
@@ -420,7 +420,7 @@ boolean PubSubClient::publish_P(const char* topic, const uint8_t* payload, unsig
lastOutActivity = millis();
return rc == tlen + 4 + plength;
return rc == tlen + 3 + llen + plength;
}
boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
@@ -525,7 +525,7 @@ uint16_t PubSubClient::writeString(const char* string, uint8_t* buf, uint16_t po
const char* idp = string;
uint16_t i = 0;
pos += 2;
while (*idp) {
while (*idp && pos < (MQTT_MAX_PACKET_SIZE - 2)) {
buf[pos++] = *idp++;
i++;
}
+1 -1
View File
@@ -73,7 +73,7 @@
#define MQTTQOS1 (1 << 1)
#define MQTTQOS2 (2 << 1)
#ifdef ESP8266
#if defined(ESP8266) || defined(ESP32)
#include <functional>
#define MQTT_CALLBACK_SIGNATURE std::function<void(char*, uint8_t*, unsigned int)> callback
#else
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
PATCH=puya.patch
for DIR in ~/.platformio/packages/framework-arduinoespressif8266*/; do
#not applied yet? (in upstream or otherwise)
if ! grep FLASH_QUIRK_WRITE_0_TO_1 $DIR/cores/esp8266/Esp.cpp >/dev/null; then
echo "Patching $DIR"
patch -p1 -d $DIR < $PATCH
fi
done
+32
View File
@@ -0,0 +1,32 @@
---
cores/esp8266/Esp.cpp | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
diff --git a/cores/esp8266/Esp.cpp b/cores/esp8266/Esp.cpp
index f4c0b220..c5c32f74 100644
--- a/cores/esp8266/Esp.cpp
+++ b/cores/esp8266/Esp.cpp
@@ -501,7 +501,21 @@ bool EspClass::flashEraseSector(uint32_t sector) {
bool EspClass::flashWrite(uint32_t offset, uint32_t *data, size_t size) {
ets_isr_mask(FLASH_INT_MASK);
- int rc = spi_flash_write(offset, (uint32_t*) data, size);
+ int rc;
+ uint32_t* ptr = data;
+#ifdef FLASH_QUIRK_WRITE_0_TO_1
+ static uint32_t read_buf[SPI_FLASH_SEC_SIZE / 4];
+ rc = spi_flash_read(offset, read_buf, size);
+ if (rc != 0) {
+ ets_isr_unmask(FLASH_INT_MASK);
+ return false;
+ }
+ for (size_t i = 0; i < size / 4; ++i) {
+ read_buf[i] &= data[i];
+ }
+ ptr = read_buf;
+#endif // FLASH_QUIRK_WRITE_0_TO_1
+ rc = spi_flash_write(offset, ptr, size);
ets_isr_unmask(FLASH_INT_MASK);
return rc == 0;
}
--
+66 -10
View File
@@ -7,7 +7,7 @@
#minimal version for esps with 512K or less flash (only has minimal plugin set)
; [env:mini_512]
; platform = espressif8266
; platform = espressif8266@1.5.0
; framework = arduino
; board = esp01
; upload_speed=460800
@@ -22,11 +22,24 @@
[common]
build_flags = -D BUILD_GIT='"${env.TRAVIS_TAG}"'
lib_deps = ""
#normal version with stable plugins, 1024k version
[env:normal_ESP8266_1024]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp12e
upload_speed=460800
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld
# upload_port = /dev/ttyUSB0
[env:normal_ESP8266_1024_DOUT]
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp12e
upload_speed=460800
@@ -35,7 +48,8 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld
#normal version with stable plugins, 4096k version
[env:normal_ESP8266_4096]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
framework = arduino
board = esp12e
upload_speed=460800
@@ -44,7 +58,9 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld
#normal version with stable plugins, 4096k version for esp8285
[env:normal_ESP8285_1024]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp8285
upload_speed=460800
@@ -54,7 +70,9 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld -DESP8285
#version with additional plugins (and dependend code) that are in test-stadium 1024k
[env:test_ESP8266_1024]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp12e
upload_speed=460800
@@ -62,15 +80,26 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld -D PLUGIN_BUILD
#version with additional plugins (and dependend code) that are in test-stadium 4096k
[env:test_ESP8266_4096]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
framework = arduino
board = esp12e
upload_speed=460800
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D PLUGIN_BUILD_TESTING
[env:test_ESP8266_4096_VCC]
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
framework = arduino
board = esp12e
upload_speed=460800
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D PLUGIN_BUILD_TESTING -D FEATURE_ADC_VCC=true
#version with additional plugins (and dependend code) that are in test-stadium 4096k for esp8285
[env:test_ESP8285_1024]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp8285
upload_speed=460800
@@ -79,7 +108,9 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld -D PLUGIN_BUILD
#version with additional plugins (and dependend code) that is in development (probably broken or incomplete) 1024k
[env:dev_ESP8266_1024]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp12e
upload_speed=460800
@@ -87,7 +118,8 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld -D PLUGIN_BUILD
#version with additional plugins (and dependend code) that is in development (probably broken or incomplete) 4096k
[env:dev_ESP8266_4096]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
framework = arduino
board = esp12e
upload_speed=460800
@@ -95,8 +127,32 @@ build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.4m1m.ld -D PLUGIN_BUILD_
#version with additional plugins (and dependend code) that is in development (probably broken or incomplete) 4096k for esp8285
[env:dev_ESP8285_1024]
platform = espressif8266
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp8285
upload_speed=460800
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld -D PLUGIN_BUILD_TESTING -D PLUGIN_BUILD_DEV -DESP8285
#special patched version for PUYA flash chips, see https://github.com/letscontrolit/ESPEasy/issues/650
[env:dev_ESP8266PUYA_1024]
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp12e
upload_speed=460800
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld -D PLUGIN_BUILD_TESTING -D PLUGIN_BUILD_DEV -D FLASH_QUIRK_WRITE_0_TO_1
#special patched version for PUYA flash chips, see https://github.com/letscontrolit/ESPEasy/issues/650
[env:dev_ESP8266PUYA_1024_VCC]
platform = espressif8266@1.5.0
lib_deps = ${common.lib_deps}
board_flash_mode = dout
framework = arduino
board = esp12e
upload_speed=460800
build_flags = ${common.build_flags} -Wl,-Tesp8266.flash.1m128.ld -D PLUGIN_BUILD_TESTING -D PLUGIN_BUILD_DEV -D FLASH_QUIRK_WRITE_0_TO_1 -D FEATURE_ADC_VCC=true
+11 -2
View File
@@ -4,7 +4,16 @@ NEW="$1"
[ "$NEW" != "" ] || exit 1
PREV=`git tag --sort=creatordate|tail -1`
echo "Creating release $NEW"
if git describe "$NEW" &>/dev/null; then
echo "Release already exists"
exit 1
fi
NEWBASE=`echo "$NEW"|cut -f1 -d'-'`
PREV=`git tag --sort=creatordate|grep "^$NEWBASE"|tail -1`
############## update Release_notes.txt
NOTES="dist/Release_notes.txt"
@@ -34,5 +43,5 @@ git tag -a "$NEW" -m "`cat /tmp/tagmessage`"
################ push everything
git push
git push origin HEAD
git push --tags
Executable
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
# Call this from a cronjob every day to trigger a nightly build via travis.
git pull
#new commits since last tag?
BRANCH=`git rev-parse --abbrev-ref HEAD`
if ! git describe --exact-match 2>/dev/null | grep "^$BRANCH"; then
TAG="$BRANCH-`date +%Y%m%d`"
./release "$TAG"
fi
+77 -16
View File
@@ -197,6 +197,14 @@ void ExecuteCommand(byte source, const char *Line)
taskClear(Par1 - 1, true);
}
//quickly clear all tasks, without saving (used by test suite)
if (strcasecmp_P(Command, PSTR("TaskClearAll")) == 0)
{
success = true;
for (byte t=0; t<TASKS_MAX; t++)
taskClear(t, false);
}
if (strcasecmp_P(Command, PSTR("wdconfig")) == 0)
{
success = true;
@@ -350,15 +358,19 @@ void ExecuteCommand(byte source, const char *Line)
}
if (strcasecmp_P(Command, PSTR("Publish")) == 0 && WiFi.status() == WL_CONNECTED)
{
success = true;
String event = Line;
event = event.substring(8);
int index = event.indexOf(',');
if (index > 0)
{
String topic = event.substring(0, index);
String value = event.substring(index + 1);
MQTTclient.publish(topic.c_str(), value.c_str(), Settings.MQTTRetainFlag);
// ToDo TD-er: Not sure about this function, but at least it sends to an existing MQTTclient
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
success = true;
String event = Line;
event = event.substring(8);
int index = event.indexOf(',');
if (index > 0)
{
String topic = event.substring(0, index);
String value = event.substring(index + 1);
MQTTpublish(enabledMqttController, topic.c_str(), value.c_str(), Settings.MQTTRetainFlag);
}
}
}
@@ -370,12 +382,17 @@ void ExecuteCommand(byte source, const char *Line)
String port = parseString(strLine, 3);
int msgpos = getParamStartPos(strLine, 4);
String message = strLine.substring(msgpos);
byte ipaddress[4];
str2ip((char*)ip.c_str(), ipaddress);
IPAddress UDP_IP(ipaddress[0], ipaddress[1], ipaddress[2], ipaddress[3]);
portUDP.beginPacket(UDP_IP, port.toInt());
portUDP.write(message.c_str(), message.length());
portUDP.endPacket();
IPAddress UDP_IP;
if(UDP_IP.fromString(ip)) {
portUDP.beginPacket(UDP_IP, port.toInt());
#if defined(ESP8266)
portUDP.write(message.c_str(), message.length());
#endif
#if defined(ESP32)
portUDP.write((uint8_t*)message.c_str(), message.length());
#endif
portUDP.endPacket();
}
}
if (strcasecmp_P(Command, PSTR("SendToHTTP")) == 0 && WiFi.status() == WL_CONNECTED)
@@ -412,6 +429,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");
}
}
}
}
#endif
// ****************************************
// configure settings commands
@@ -509,6 +562,13 @@ void ExecuteCommand(byte source, const char *Line)
{
success = true;
ResetFactory();
#if defined(ESP8266)
ESP.reset();
#endif
#if defined(ESP32)
ESP.restart();
#endif
}
if (strcasecmp_P(Command, PSTR("Save")) == 0)
@@ -532,9 +592,10 @@ void ExecuteCommand(byte source, const char *Line)
if (strcasecmp_P(Command, PSTR("IP")) == 0)
{
success = true;
if (GetArgv(Line, TmpStr1, 2))
if (GetArgv(Line, TmpStr1, 2)) {
if (!str2ip(TmpStr1, Settings.IP))
Serial.println("?");
}
}
if (strcasecmp_P(Command, PSTR("Settings")) == 0)
+101 -67
View File
@@ -7,9 +7,6 @@ void sendData(struct EventStruct *event)
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);
@@ -24,7 +21,8 @@ void sendData(struct EventStruct *event)
uint16_t delayms = Settings.MessageDelay - dif;
//this is logged nowhere else, so might as well disable it here also:
// addLog(LOG_LEVEL_DEBUG_MORE, String(F("CTRL : Message delay (ms): "))+delayms);
delayBackground(delayms);
delayBackground(delayms);
// unsigned long timer = millis() + delayms;
// while (!timeOutReached(timer))
@@ -38,11 +36,19 @@ void sendData(struct EventStruct *event)
{
event->ControllerIndex = x;
event->idx = Settings.TaskDeviceID[x][event->TaskIndex];
if (Settings.TaskDeviceSendData[event->ControllerIndex][event->TaskIndex] && Settings.ControllerEnabled[event->ControllerIndex] && Settings.Protocol[event->ControllerIndex])
if (Settings.TaskDeviceSendData[event->ControllerIndex][event->TaskIndex] &&
Settings.ControllerEnabled[event->ControllerIndex] && Settings.Protocol[event->ControllerIndex])
{
event->ProtocolIndex = getProtocolIndex(Settings.Protocol[event->ControllerIndex]);
CPlugin_ptr[event->ProtocolIndex](CPLUGIN_PROTOCOL_SEND, event, dummyString);
if (validUserVar(event)) {
CPlugin_ptr[event->ProtocolIndex](CPLUGIN_PROTOCOL_SEND, event, dummyString);
} else {
String log = F("Invalid value detected for controller ");
String controllerName;
CPlugin_ptr[event->ProtocolIndex](CPLUGIN_GET_DEVICENAME, event, controllerName);
log += controllerName;
addLog(LOG_LEVEL_DEBUG, log);
}
}
}
@@ -50,6 +56,13 @@ void sendData(struct EventStruct *event)
lastSend = millis();
}
boolean validUserVar(struct EventStruct *event) {
for (int i = 0; i < VARS_PER_TASK; ++i) {
const float f(UserVar[event->BaseVarIndex + i]);
if (!isValidFloat(f)) return false;
}
return true;
}
/*********************************************************************************************\
* Handle incoming MQTT messages
@@ -60,10 +73,15 @@ void callback(char* c_topic, byte* b_payload, unsigned int length) {
char c_payload[384];
statusLED(true);
if (length>sizeof(c_payload)-1)
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController < 0) {
addLog(LOG_LEVEL_ERROR, F("MQTT : No enabled MQTT controller"));
return;
}
if ((length + 1) > sizeof(c_payload))
{
addLog(LOG_LEVEL_ERROR, F("MQTT : Ignored too big message"));
return;
}
//convert payload to string, and 0 terminate
@@ -87,7 +105,7 @@ void callback(char* c_topic, byte* b_payload, unsigned int length) {
struct EventStruct TempEvent;
TempEvent.String1 = c_topic;
TempEvent.String2 = c_payload;
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[0]);
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[enabledMqttController]);
CPlugin_ptr[ProtocolIndex](CPLUGIN_PROTOCOL_RECV, &TempEvent, dummyString);
}
@@ -95,12 +113,14 @@ void callback(char* c_topic, byte* b_payload, unsigned int length) {
/*********************************************************************************************\
* Connect to MQTT message broker
\*********************************************************************************************/
void MQTTConnect()
bool MQTTConnect(int controller_idx)
{
if (WiFi.status() != WL_CONNECTED) return;
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(0, (byte*)&ControllerSettings, sizeof(ControllerSettings)); // todo index is now fixed to 0
LoadControllerSettings(controller_idx, (byte*)&ControllerSettings, sizeof(ControllerSettings));
if (!ControllerSettings.checkHostReachable(true))
return false;
if (MQTTclient.connected())
MQTTclient.disconnect();
if (ControllerSettings.UseDNS) {
MQTTclient.setServer(ControllerSettings.getHost().c_str(), ControllerSettings.Port);
} else {
@@ -109,72 +129,77 @@ void MQTTConnect()
MQTTclient.setCallback(callback);
// MQTT needs a unique clientname to subscribe to broker
String clientid = "ESPClient";
clientid += Settings.Unit;
String subscribeTo = "";
String clientid = F("ESPClient_");
clientid += WiFi.macAddress();
String LWTTopic = ControllerSettings.Subscribe;
LWTTopic.replace(F("/#"), F("/status"));
LWTTopic.replace(F("%sysname%"), Settings.Name);
parseSystemVariables(LWTTopic, false);
LWTTopic += F("/LWT"); // Extend the topic for status updates of connected/disconnected status.
for (byte x = 1; x < 3; x++)
{
String log = "";
boolean MQTTresult = false;
boolean MQTTresult = false;
uint8_t willQos = 0;
boolean willRetain = true;
if ((SecuritySettings.ControllerUser[0] != 0) && (SecuritySettings.ControllerPassword[0] != 0))
MQTTresult = MQTTclient.connect(clientid.c_str(), SecuritySettings.ControllerUser[0], SecuritySettings.ControllerPassword[0], LWTTopic.c_str(), 0, 0, "Connection Lost");
else
MQTTresult = MQTTclient.connect(clientid.c_str(), LWTTopic.c_str(), 0, 0, "Connection Lost");
if (MQTTresult)
{
log = F("MQTT : Connected to broker");
addLog(LOG_LEVEL_INFO, log);
subscribeTo = ControllerSettings.Subscribe;
subscribeTo.replace(F("%sysname%"), Settings.Name);
MQTTclient.subscribe(subscribeTo.c_str());
log = F("Subscribed to: ");
log += subscribeTo;
addLog(LOG_LEVEL_INFO, log);
MQTTclient.publish(LWTTopic.c_str(), "Connected");
statusLED(true);
break; // end loop if succesfull
}
else
{
log = F("MQTT : Failed to connect to broker");
addLog(LOG_LEVEL_ERROR, log);
}
delay(500);
if ((SecuritySettings.ControllerUser[controller_idx] != 0) && (SecuritySettings.ControllerPassword[controller_idx] != 0)) {
MQTTresult = MQTTclient.connect(clientid.c_str(), SecuritySettings.ControllerUser[controller_idx], SecuritySettings.ControllerPassword[controller_idx],
LWTTopic.c_str(), willQos, willRetain, "Connection Lost");
} else {
MQTTresult = MQTTclient.connect(clientid.c_str(), LWTTopic.c_str(), willQos, willRetain, "Connection Lost");
}
yield();
if (!MQTTresult) {
addLog(LOG_LEVEL_ERROR, F("MQTT : Failed to connect to broker"));
return false;
}
MQTTclient_should_reconnect = false;
String log = F("MQTT : Connected to broker with client ID: ");
log += clientid;
addLog(LOG_LEVEL_INFO, log);
String subscribeTo = ControllerSettings.Subscribe;
parseSystemVariables(subscribeTo, false);
MQTTclient.subscribe(subscribeTo.c_str());
log = F("Subscribed to: ");
log += subscribeTo;
addLog(LOG_LEVEL_INFO, log);
if (MQTTclient.publish(LWTTopic.c_str(), "Connected", 1)) {
if (Settings.UseRules)
{
String event = F("MQTT#Connected");
rulesProcessing(event);
}
statusLED(true);
return true; // end loop if succesfull
}
return false;
}
/*********************************************************************************************\
* Check connection MQTT message broker
\*********************************************************************************************/
void MQTTCheck()
bool MQTTCheck(int controller_idx)
{
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[0]);
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[controller_idx]);
if (Protocol[ProtocolIndex].usesMQTT)
{
if (!MQTTclient.connected() || WiFi.status() != WL_CONNECTED)
if (MQTTclient_should_reconnect || !WiFiConnected(10) || !MQTTclient.connected())
{
addLog(LOG_LEVEL_ERROR, F("MQTT : Connection lost"));
connectionFailures += 2;
MQTTclient.disconnect();
if (WiFi.status() == WL_CONNECTED) {
delay(1000);
MQTTConnect();
if (MQTTclient_should_reconnect) {
addLog(LOG_LEVEL_ERROR, F("MQTT : Intentional reconnect"));
} else {
addLog(LOG_LEVEL_ERROR, F("MQTT : Connection lost"));
connectionFailures += 2;
}
}
else if (connectionFailures)
return MQTTConnect(controller_idx);
} else if (connectionFailures) {
connectionFailures--;
}
}
// When no MQTT protocol is enabled, all is fine.
return true;
}
@@ -199,6 +224,13 @@ void SendStatus(byte source, String status)
}
}
boolean MQTTpublish(int controller_idx, const char* topic, const char* payload, boolean retained)
{
if (MQTTclient.publish(topic, payload, retained))
return true;
addLog(LOG_LEVEL_DEBUG, F("MQTT : publish failed"));
return false;
}
/*********************************************************************************************\
* Send status info back to channel where request came from
@@ -206,10 +238,12 @@ void SendStatus(byte source, String status)
void MQTTStatus(String& status)
{
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(0, (byte*)&ControllerSettings, sizeof(ControllerSettings)); // todo index is now fixed to 0
String pubname = ControllerSettings.Subscribe;
pubname.replace(F("/#"), F("/status"));
pubname.replace(F("%sysname%"), Settings.Name);
MQTTclient.publish(pubname.c_str(), status.c_str(),Settings.MQTTRetainFlag);
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
LoadControllerSettings(enabledMqttController, (byte*)&ControllerSettings, sizeof(ControllerSettings));
String pubname = ControllerSettings.Subscribe;
pubname.replace(F("/#"), F("/status"));
parseSystemVariables(pubname, false);
MQTTpublish(enabledMqttController, pubname.c_str(), status.c_str(),Settings.MQTTRetainFlag);
}
}
+129
View File
@@ -0,0 +1,129 @@
/*********************************************************************************************\
Convert bearing in degree to bearing string
\*********************************************************************************************/
String getBearing(int degrees)
{
const __FlashStringHelper* bearing[] = {
F("N"),
F("NNE"),
F("NE"),
F("ENE"),
F("E"),
F("ESE"),
F("SE"),
F("SSE"),
F("S"),
F("SSW"),
F("SW"),
F("WSW"),
F("W"),
F("WNW"),
F("NW"),
F("NNW")
};
int nr_directions = (int) (sizeof(bearing)/sizeof(bearing[0]));
float stepsize = (360.0 / nr_directions);
if (degrees < 0) { degrees += 360; } // Allow for bearing -360 .. 359
int bearing_idx=int((degrees + (stepsize / 2.0)) / stepsize) % nr_directions;
if (bearing_idx < 0)
return("");
else
return(bearing[bearing_idx]);
}
float CelsiusToFahrenheit(float celsius) {
return celsius * (9.0 / 5.0) + 32;
}
int m_secToBeaufort(float m_per_sec) {
if (m_per_sec < 0.3) return 0;
if (m_per_sec < 1.6) return 1;
if (m_per_sec < 3.4) return 2;
if (m_per_sec < 5.5) return 3;
if (m_per_sec < 8.0) return 4;
if (m_per_sec < 10.8) return 5;
if (m_per_sec < 13.9) return 6;
if (m_per_sec < 17.2) return 7;
if (m_per_sec < 20.8) return 8;
if (m_per_sec < 24.5) return 9;
if (m_per_sec < 28.5) return 10;
if (m_per_sec < 32.6) return 11;
return 12;
}
String centimeterToImperialLength(float cm) {
return millimeterToImperialLength(cm * 10.0);
}
String millimeterToImperialLength(float mm) {
float inches = mm / 25.4;
int feet = inches /12;
inches = inches - (feet * 12);
String result;
result.reserve(10);
if (feet != 0) {
result += feet;
result += '\'';
}
result += toString(inches,1);
result += '"';
return result;
}
float minutesToDay(int minutes) {
return minutes / 1440.0;
}
String minutesToDayHour(int minutes) {
int days = minutes / 1440;
int hours = (minutes % 1440) / 60;
char TimeString[6]; //5 digits plus the null char
sprintf_P(TimeString, PSTR("%d%c%02d%c"), days, 'd', hours, 'h');
return TimeString;
}
String minutesToDayHourMinute(int minutes) {
int days = minutes / 1440;
int hours = (minutes % 1440) / 60;
int mins = (minutes % 1440) % 60;
char TimeString[20];
sprintf_P(TimeString, PSTR("%d%c%02d%c%02d%c"), days, 'd', hours, 'h', mins, 'm');
return TimeString;
}
String secondsToDayHourMinuteSecond(int seconds) {
int sec = seconds % 60;
int minutes = seconds / 60;
int days = minutes / 1440;
int hours = (minutes % 1440) / 60;
int mins = (minutes % 1440) % 60;
char TimeString[20];
sprintf_P(TimeString, PSTR("%d%c%02d%c%02d%c%02d"), days, 'd', hours, ':', mins, ':', sec);
return TimeString;
}
/********************************************************************************************\
In memory convert float to long
\*********************************************************************************************/
unsigned long float2ul(float f)
{
unsigned long ul;
memcpy(&ul, &f, 4);
return ul;
}
/********************************************************************************************\
In memory convert long to float
\*********************************************************************************************/
float ul2float(unsigned long ul)
{
float f;
memcpy(&f, &ul, 4);
return f;
}
+42
View File
@@ -0,0 +1,42 @@
/*
To modify the stock configuration without changing the EspEasy.ino file :
1) rename this file to "Custom.h" (It is ignored by Git)
2) define your own settings below
3) define USE_CUSTOM_H as a build flags. ie : export PLATFORMIO_BUILD_FLAGS="'-DUSE_CUSTOM_H'"
*/
// make the compiler show a warning to confirm that this file is inlcuded
#warning "**** Using Settings from Custom.h File ***"
/*
#######################################################################################################
Your Own Default Settings
#######################################################################################################
You can basically ovveride ALL macro defined in ESPEasy.ino.
Don't forget to first #undef each existing #define that you add below.
Here are some examples:
*/
#undef DEFAULT_NAME
#define DEFAULT_NAME "MyEspEasyDevice" // Enter your device friendly name
#undef DEFAULT_SSID
#define DEFAULT_SSID "MyHomeSSID" // Enter your network SSID
#undef DEFAULT_KEY
#define DEFAULT_KEY "MySuperSecretPassword" // Enter your network WPA key
#undef DEFAULT_AP_KEY
#define DEFAULT_AP_KEY "MyOwnConfigPassword" // Enter network WPA key for AP (config) mode
#ifdef BUILD_GIT
#undef BUILD_GIT
#endif
#define BUILD_GIT "MyBuildNum"
+985
View File
@@ -0,0 +1,985 @@
#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_ */
+100 -663
View File
@@ -71,642 +71,22 @@
// SHT1X temperature/humidity sensors
// Ser2Net server
// ********************************************************************************
// User specific configuration
// ********************************************************************************
#include "ESPEasy-Globals.h"
// 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.
// Blynk_get prototype
boolean Blynk_get(const String& command, byte controllerIndex,float *data = NULL );
#define DEFAULT_NAME "ESP_Easy" // Enter your device friendly name
#define DEFAULT_SSID "ssid" // Enter your network SSID
#define DEFAULT_KEY "wpakey" // Enter your network WPA key
#define DEFAULT_DELAY 60 // Enter your Send delay in seconds
#define DEFAULT_AP_KEY "configesp" // Enter network WPA key for AP (config) mode
#define DEFAULT_USE_STATIC_IP false // true or false enabled or disabled set 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_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
#define UNIT 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
#define FEATURE_ADC_VCC false
//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
// ********************************************************************************
#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 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
#define TASKS_MAX 12 // max 12!
#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 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.
#include "lwip/tcp_impl.h"
#include <ESP8266WiFi.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"
int firstEnabledBlynkController() {
for (byte i = 0; i < CONTROLLER_MAX; ++i) {
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[i]);
if (Protocol[ProtocolIndex].Number == 12 && Settings.ControllerEnabled[i]) {
return i;
}
}
return -1;
}
#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(192, 168, 4, 1);
DNSServer dnsServer;
#ifdef FEATURE_MDNS
MDNSResponder mdns;
#endif
// MQTT client
WiFiClient mqtt;
PubSubClient MQTTclient(mqtt);
// WebServer
ESP8266WebServer WebServer(80);
// udp protocol stuff (syslog, global sync, node info list, ntp time)
WiFiUDP portUDP;
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
{
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
{
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;
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;
//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
{
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();
}
boolean connectToHost(WiFiClient &client) {
if (WiFi.status() != WL_CONNECTED) {
return false; // Not connected, so no use in wasting time to connect to a host.
}
if (UseDNS) {
return client.connect(HostName, Port);
}
return client.connect(getIP(), Port);
}
int beginPacket(WiFiUDP &client) {
if (WiFi.status() != WL_CONNECTED) {
return 0; // Not connected, so no use in wasting time to connect to a host.
}
if (UseDNS) {
return client.beginPacket(HostName, Port);
}
return client.beginPacket(getIP(), Port);
}
String getHostPortString() const {
String result = getHost();
result += ":";
result += Port;
return result;
}
};
struct NotificationSettingsStruct
{
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;
//its safe to extend this struct, up to 4096 bytes, default values in config are 0
};
struct ExtraTaskSettingsStruct
{
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
{
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;
};
struct LogStruct
{
unsigned long timeStamp;
char* Message;
} Logging[10];
int logcount = -1;
struct DeviceStruct
{
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
{
byte Number;
boolean usesMQTT;
boolean usesAccount;
boolean usesPassword;
int defaultPort;
boolean usesTemplate;
boolean usesID;
} Protocol[CPLUGIN_MAX];
struct NotificationStruct
{
byte Number;
boolean usesMessaging;
byte usesGPIO;
} Notification[NPLUGIN_MAX];
struct NodeStruct
{
byte ip[4];
byte age;
uint16_t build;
char* nodeName;
byte nodeType;
} Nodes[UNIT_MAX];
struct systemTimerStruct
{
unsigned long timer;
byte plugin;
byte Par1;
byte Par2;
byte Par3;
} systemTimers[SYSTEM_TIMER_MAX];
struct systemCMDTimerStruct
{
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 lastSend;
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;
#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;
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 = "";
/*********************************************************************************************\
* SETUP
\*********************************************************************************************/
@@ -774,6 +154,7 @@ void setup()
fileSystemCheck();
LoadSettings();
checkRuleSets();
if (strcasecmp(SecuritySettings.WifiSSID, "ssid") == 0)
wifiSetup = true;
@@ -813,6 +194,29 @@ void setup()
hardwareInit();
//After booting, we want all the tasks to run without delaying more than neccesary.
//Plugins that need an initial startup delay need to overwrite their initial timerSensor value in PLUGIN_INIT
//They should also check if we returned from deep sleep so that they can skip the delay in that case.
for (byte x = 0; x < TASKS_MAX; x++)
if (Settings.TaskDeviceTimer[x] !=0)
timerSensor[x] = millis() + (x * Settings.MessageDelay);
timer100ms = 0; // timer for periodic actions 10 x per/sec
timer1s = 0; // timer for periodic actions once per/sec
timerwd = 0; // timer for watchdog once per 30 sec
timermqtt = 0; // Timer for the MQTT keep alive loop.
timermqtt_interval = 250; // Interval for checking MQTT
timerAwakeFromDeepSleep = millis();
PluginInit();
CPluginInit();
NPluginInit();
if (Settings.UseRules)
{
String event = F("System#Wake");
rulesProcessing(event);
}
WiFi.persistent(false); // Do not use SDK storage of SSID/WPA parameters
WifiAPconfig();
@@ -829,28 +233,12 @@ void setup()
}
}
else
// 3 connect attempts
WifiConnect(3);
WiFiConnectRelaxed();
#ifdef FEATURE_REPORTING
ReportStatus();
#endif
//After booting, we want all the tasks to run without delaying more than neccesary.
//Plugins that need an initial startup delay need to overwrite their initial timerSensor value in PLUGIN_INIT
//They should also check if we returned from deep sleep so that they can skip the delay in that case.
for (byte x = 0; x < TASKS_MAX; x++)
if (Settings.TaskDeviceTimer[x] !=0)
timerSensor[x] = millis() + (x * Settings.MessageDelay);
timer100ms = 0; // timer for periodic actions 10 x per/sec
timer1s = 0; // timer for periodic actions once per/sec
timerwd = 0; // timer for watchdog once per 30 sec
PluginInit();
CPluginInit();
NPluginInit();
WebServerInit();
#ifdef FEATURE_ARDUINO_OTA
@@ -861,11 +249,6 @@ void setup()
if (Settings.UDPPort != 0)
portUDP.begin(Settings.UDPPort);
// Setup MQTT Client
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[0]);
if (Protocol[ProtocolIndex].usesMQTT && Settings.ControllerEnabled[0])
MQTTConnect();
sendSysInfoUDP(3);
if (Settings.UseNTP)
@@ -891,6 +274,21 @@ void setup()
}
int firstEnabledMQTTController() {
for (byte i = 0; i < CONTROLLER_MAX; ++i) {
byte ProtocolIndex = getProtocolIndex(Settings.Protocol[i]);
if (Protocol[ProtocolIndex].usesMQTT && Settings.ControllerEnabled[i]) {
return i;
}
}
return -1;
}
bool getControllerProtocolDisplayName(byte ProtocolIndex, byte parameterIdx, String& protoDisplayName) {
EventStruct tmpEvent;
tmpEvent.idx=parameterIdx;
return CPlugin_ptr[ProtocolIndex](CPLUGIN_GET_PROTOCOL_DISPLAY_NAME, &tmpEvent, protoDisplayName);
}
/*********************************************************************************************\
* MAIN LOOP
@@ -907,14 +305,20 @@ void loop()
}
// Deep sleep mode, just run all tasks one time and go back to sleep as fast as possible
if (isDeepSleepEnabled())
if (firstLoop && isDeepSleepEnabled())
{
// Setup MQTT Client
// Controller index is forced to the first enabled MQTT controller.
// This is normally done via frequent checks, but there's no time for in deepsleep.
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
MQTTConnect(enabledMqttController);
}
// Now run all frequent tasks
run50TimesPerSecond();
run10TimesPerSecond();
runEach30Seconds();
runOncePerSecond();
deepSleep(Settings.Delay);
//deepsleep will never return, its a special kind of reboot
}
//normal mode, run each task when its time
else
@@ -931,9 +335,39 @@ void loop()
if (timeOutReached(timer1s))
runOncePerSecond();
if (timeOutReached(timermqtt)) {
// MQTT_KEEPALIVE = 15 seconds.
timermqtt = millis() + timermqtt_interval;
//dont do this in backgroundtasks(), otherwise causes crashes. (https://github.com/letscontrolit/ESPEasy/issues/683)
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
if (!MQTTclient.loop()) {
if (!MQTTCheck(enabledMqttController)) {
// Check failed, no need to retry it immediately.
if (timermqtt_interval < 2000)
timermqtt_interval += 250;
} else {
timermqtt_interval = 250;
}
}
}
}
}
backgroundtasks();
if (readyForSleep()){
if (Settings.UseRules)
{
String event = F("System#Sleep");
rulesProcessing(event);
}
deepSleep(Settings.Delay);
//deepsleep will never return, its a special kind of reboot
}
firstLoop = false;
}
@@ -963,6 +397,7 @@ void run10TimesPerSecond()
eventBuffer = "";
}
elapsed = micros() - start;
WebServer.handleClient();
}
@@ -1006,6 +441,7 @@ void runOncePerSecond()
}
cmd_within_mainloop = 0;
}
WifiCheck();
// clock events
if (Settings.UseNTP)
@@ -1067,8 +503,10 @@ void runEach30Seconds()
addLog(LOG_LEVEL_INFO, log);
sendSysInfoUDP(1);
refreshNodeList();
if(Settings.ControllerEnabled[0])
MQTTCheck();
int enabledMqttController = firstEnabledMQTTController();
if (enabledMqttController >= 0) {
MQTTCheck(enabledMqttController);
}
if (Settings.UseSSDP)
SSDP_update();
#if FEATURE_ADC_VCC
@@ -1079,8 +517,6 @@ void runEach30Seconds()
if (loopCounterLast > loopCounterMax)
loopCounterMax = loopCounterLast;
WifiCheck();
#ifdef FEATURE_REPORTING
ReportStatus();
#endif
@@ -1269,10 +705,12 @@ void checkSystemTimers()
bool runningBackgroundTasks=false;
void backgroundtasks()
{
//always start with a yield
yield();
//prevent recursion!
if (runningBackgroundTasks)
{
yield();
return;
}
runningBackgroundTasks=true;
@@ -1289,8 +727,7 @@ void backgroundtasks()
dnsServer.processNextRequest();
WebServer.handleClient();
if(Settings.ControllerEnabled[0])
MQTTclient.loop();
checkUDP();
#ifdef FEATURE_ARDUINO_OTA
+69
View File
@@ -0,0 +1,69 @@
#ifndef ESPEASY_TIMETYPES_H_
#define ESPEASY_TIMETYPES_H_
#include <stdint.h>
struct timeStruct {
timeStruct() : Second(0), Minute(0), Hour(0), Wday(0), Day(0), Month(0), Year(0) {}
uint8_t Second;
uint8_t Minute;
uint8_t Hour;
uint8_t Wday; // day of week, sunday is day 1
uint8_t Day;
uint8_t Month;
uint8_t Year; // offset from 1970;
};
// convenient constants for TimeChangeRules
enum week_t {Last=0, First, Second, Third, Fourth};
enum dow_t {Sun=1, Mon, Tue, Wed, Thu, Fri, Sat};
enum month_t {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
// structure to describe rules for when daylight/summer time begins,
// or when standard time begins.
// For Daylight Saving Time Around the World, see:
// - https://www.timeanddate.com/time/dst/2018.html
// - https://en.wikipedia.org/wiki/Daylight_saving_time_by_country
struct TimeChangeRule {
TimeChangeRule() : week(0), dow(1), month(1), hour(0), offset(0) {}
TimeChangeRule(uint8_t weeknr, uint8_t downr, uint8_t m, uint8_t h, uint16_t minutesoffset) :
week(weeknr), dow(downr), month(m), hour(h), offset(minutesoffset) {}
// Construct time change rule from stored values optimized for minimum space.
TimeChangeRule(uint16_t flash_stored_value, int16_t minutesoffset) : offset(minutesoffset) {
hour = flash_stored_value & 0x001f;
month = (flash_stored_value >> 5) & 0x000f;
dow = (flash_stored_value >> 9) & 0x0007;
week = (flash_stored_value >> 12) & 0x0007;
}
uint16_t toFlashStoredValue() const {
uint16_t value = hour;
value = value | (month << 5);
value = value | (dow << 9);
value = value | (week << 12);
return value;
}
bool isValid() const {
return (week <= 4) && (dow != 0) && (dow <= 7) &&
(month != 0) && (month <= 12) && (hour <= 23) &&
(offset > -720) && (offset < 900); // UTC-12h ... UTC+14h + 1h DSToffset
}
uint8_t week; // First, Second, Third, Fourth, or Last week of the month
uint8_t dow; // day of week, 1=Sun, 2=Mon, ... 7=Sat
uint8_t month; // 1=Jan, 2=Feb, ... 12=Dec
uint8_t hour; // 0-23
int16_t offset; // offset from UTC in minutes
};
// Forward declartions
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_ */
+605 -992
View File
File diff suppressed because it is too large Load Diff
+63 -172
View File
@@ -14,42 +14,24 @@ void syslog(const char *message)
portUDP.beginPacket(broadcastIP, 514);
char str[256];
str[0] = 0;
snprintf_P(str, sizeof(str), PSTR("<7>ESP Unit: %u : %s"), Settings.Unit, message);
portUDP.write(str);
// An RFC3164 compliant message must be formated like : "<PRIO>[TimeStamp ]Hostname TaskName: Message"
// Using Settings.Name as the Hostname (Hostname must NOT content space)
snprintf_P(str, sizeof(str), PSTR("<7>%s EspEasy: %s"), Settings.Name, message);
// Using Setting.Unit to build a Hostname
//snprintf_P(str, sizeof(str), PSTR("<7>EspEasy_%u ESP: %s"), Settings.Unit, message);
#if defined(ESP8266)
portUDP.write(str);
#endif
#if defined(ESP32)
portUDP.write((uint8_t*)str,strlen(str));
#endif
portUDP.endPacket();
}
}
/*********************************************************************************************\
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)
\*********************************************************************************************/
@@ -86,22 +68,10 @@ 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];
@@ -138,70 +108,13 @@ void checkUDP()
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;
}
}
@@ -210,79 +123,12 @@ void checkUDP()
}
/*********************************************************************************************\
Send task info using UDP message
\*********************************************************************************************/
void SendUDPTaskInfo(byte destUnit, byte sourceTaskIndex, byte destTaskIndex)
{
if (WiFi.status() != WL_CONNECTED) {
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 (WiFi.status() != WL_CONNECTED) {
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);
}
/*********************************************************************************************\
Send event using UDP message
\*********************************************************************************************/
void SendUDPCommand(byte destUnit, char* data, byte dataLength)
{
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
return;
}
byte firstUnit = 1;
@@ -306,7 +152,7 @@ void SendUDPCommand(byte destUnit, char* data, byte dataLength)
\*********************************************************************************************/
void sendUDP(byte unit, byte* data, byte size)
{
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
return;
}
if (unit != 255)
@@ -352,7 +198,7 @@ void refreshNodeList()
void sendSysInfoUDP(byte repeats)
{
char log[80];
if (Settings.UDPPort == 0 || WiFi.status() != WL_CONNECTED)
if (Settings.UDPPort == 0 || !WiFiConnected(100))
return;
// TODO: make a nice struct of it and clean up
@@ -412,7 +258,7 @@ void sendSysInfoUDP(byte repeats)
Respond to HTTP XML requests for SSDP information
\*********************************************************************************************/
void SSDP_schema(WiFiClient &client) {
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
return;
}
@@ -726,5 +572,50 @@ void SSDP_update() {
while (_server->next())
_server->flush();
}
}
// Check WiFi connection. Maximum timeout 500 msec.
bool WiFiConnected(uint32_t timeout_ms) {
uint32_t timer = millis() + (timeout_ms > 500 ? 500 : timeout_ms);
uint32_t min_delay = timeout_ms / 20;
if (min_delay < 10) {
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;
}
delay(min_delay); // Allow the backgroundtasks to continue procesing.
}
return true;
}
bool hostReachable(const IPAddress& ip) {
// Only do 1 ping at a time to return early
byte retry = 3;
while (retry > 0) {
if (Ping.ping(ip, 1)) return true;
delay(50);
--retry;
}
String log = F("Host unreachable: ");
log += ip;
addLog(LOG_LEVEL_ERROR, log);
return false;
}
bool hostReachable(const String& hostname) {
IPAddress remote_addr;
if (WiFi.hostByName(hostname.c_str(), remote_addr))
return hostReachable(remote_addr);
String log = F("Hostname cannot be resolved: ");
log += hostname;
addLog(LOG_LEVEL_ERROR, log);
return false;
}
+383
View File
@@ -0,0 +1,383 @@
/********************************************************************************************\
Convert a char string to integer
\*********************************************************************************************/
//FIXME: change original code so it uses String and String.toInt()
unsigned long str2int(char *string)
{
unsigned long temp = atof(string);
return temp;
}
/********************************************************************************************\
Check if valid float and convert string to float.
\*********************************************************************************************/
bool string2float(const String& string, float& floatvalue) {
if (!isFloat(string)) return false;
floatvalue = atof(string.c_str());
return true;
}
/********************************************************************************************\
Convert a char string to IP byte array
\*********************************************************************************************/
boolean str2ip(const String& string, byte* IP) {
return str2ip(string.c_str(), IP);
}
boolean str2ip(const char *string, byte* IP)
{
IPAddress tmpip; // Default constructor => set to 0.0.0.0
if (*string == 0 || tmpip.fromString(string)) {
// Eiher empty string or a valid IP addres, so copy value.
for (byte i = 0; i < 4; ++i)
IP[i] = tmpip[i];
return true;
}
return false;
}
// Call this by first declaring a char array of size 20, like:
// char strIP[20];
// formatIP(ip, strIP);
void formatIP(const IPAddress& ip, char (&strIP)[20]) {
sprintf_P(strIP, PSTR("%u.%u.%u.%u"), ip[0], ip[1], ip[2], ip[3]);
}
String formatIP(const IPAddress& ip) {
char strIP[20];
formatIP(ip, strIP);
return String(strIP);
}
void formatMAC(const uint8_t* mac, char (&strMAC)[20]) {
sprintf_P(strMAC, PSTR("%02X:%02X:%02X:%02X:%02X:%02X"), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}
/*********************************************************************************************\
Workaround for removing trailing white space when String() converts a float with 0 decimals
\*********************************************************************************************/
String toString(float value, byte decimals)
{
String sValue = String(value, decimals);
sValue.trim();
return sValue;
}
/*********************************************************************************************\
Format a value to the set number of decimals
\*********************************************************************************************/
String formatUserVar(struct EventStruct *event, byte rel_index)
{
float f(UserVar[event->BaseVarIndex + rel_index]);
if (!isValidFloat(f)) {
String log = F("Invalid float value for TaskIndex: ");
log += event->TaskIndex;
log += F(" varnumber: ");
log += rel_index;
addLog(LOG_LEVEL_DEBUG, log);
f = 0;
}
return toString(f, ExtraTaskSettings.TaskDeviceValueDecimals[rel_index]);
}
/*********************************************************************************************\
Wrap a string with given pre- and postfix string.
\*********************************************************************************************/
String wrap_String(const String& string, const String& wrap) {
String result;
result.reserve(string.length() + 2* wrap.length());
result = wrap;
result += string;
result += wrap;
return result;
}
/*********************************************************************************************\
Format an object value pair for use in JSON.
\*********************************************************************************************/
String to_json_object_value(const String& object, const String& value) {
String result;
result.reserve(object.length() + value.length() + 6);
result = wrap_String(object, F("\""));
result += F(":");
if (value.length() == 0 || !isFloat(value)) {
result += wrap_String(value, F("\""));
} else {
result += value;
}
return result;
}
/*********************************************************************************************\
Parse a string and get the xth command or parameter
\*********************************************************************************************/
String parseString(String& string, byte indexFind)
{
String tmpString = string;
tmpString += ",";
tmpString.replace(" ", ",");
String locateString = "";
byte count = 0;
int index = tmpString.indexOf(',');
while (index > 0)
{
count++;
locateString = tmpString.substring(0, index);
tmpString = tmpString.substring(index + 1);
index = tmpString.indexOf(',');
if (count == indexFind)
{
locateString.toLowerCase();
return locateString;
}
}
return "";
}
/*********************************************************************************************\
Parse a string and get the xth command or parameter
\*********************************************************************************************/
int getParamStartPos(String& string, byte indexFind)
{
String tmpString = string;
byte count = 0;
tmpString.replace(" ", ",");
for (unsigned int x = 0; x < tmpString.length(); x++)
{
if (tmpString.charAt(x) == ',')
{
count++;
if (count == (indexFind - 1))
return x + 1;
}
}
return -1;
}
//escapes special characters in strings for use in html-forms
void htmlEscape(String & html)
{
html.replace("&", "&amp;");
html.replace("\"", "&quot;");
html.replace("'", "&#039;");
html.replace("<", "&lt;");
html.replace(">", "&gt;");
}
/********************************************************************************************\
replace other system variables like %sysname%, %systime%, %ip%
\*********************************************************************************************/
void parseControllerVariables(String& s, struct EventStruct *event, boolean useURLencode) {
parseSystemVariables(s, useURLencode);
parseEventVariables(s, event, useURLencode);
parseStandardConversions(s, useURLencode);
}
void repl(const String& key, const String& val, String& s, boolean useURLencode)
{
if (useURLencode) {
s.replace(key, URLEncode(val.c_str()));
} else {
s.replace(key, val);
}
}
void parseSpecialCharacters(String& s, boolean useURLencode)
{
bool no_accolades = s.indexOf('{') == -1 || s.indexOf('}') == -1;
bool no_html_entity = s.indexOf('&') == -1 || s.indexOf(';') == -1;
if (no_accolades && no_html_entity)
return; // Nothing to replace
{
// Degree
const char degree[3] = {0xc2, 0xb0, 0}; // Unicode degree symbol
const char degreeC[4] = {0xe2, 0x84, 0x83, 0}; // Unicode degreeC symbol
const char degree_C[4] = {0xc2, 0xb0, 'C', 0}; // Unicode degree symbol + captial C
repl(F("{D}"), degree, s, useURLencode);
repl(F("&deg;"), degree, s, useURLencode);
repl(degreeC, degree_C, s, useURLencode);
}
{
// Angle quotes
const char laquo[3] = {0xc2, 0xab, 0}; // Unicode left angle quotes symbol
const char raquo[3] = {0xc2, 0xbb, 0}; // Unicode right angle quotes symbol
repl(F("{<<}"), laquo, s, useURLencode);
repl(F("&laquo;"), laquo, s, useURLencode);
repl(F("{>>}"), raquo, s, useURLencode);
repl(F("&raquo;"), raquo, s, useURLencode);
}
{
// Greek letter Mu
const char mu[3] = {0xc2, 0xb5, 0}; // Unicode greek letter mu
repl(F("{u}"), mu, s, useURLencode);
repl(F("&micro;"), mu, s, useURLencode);
}
{
// Currency
const char euro[4] = {0xe2, 0x82, 0xac, 0}; // Unicode euro symbol
const char yen[3] = {0xc2, 0xa5, 0}; // Unicode yen symbol
const char pound[3] = {0xc2, 0xa3, 0}; // Unicode pound symbol
const char cent[3] = {0xc2, 0xa2, 0}; // Unicode cent symbol
repl(F("{E}"), euro, s, useURLencode);
repl(F("&euro;"), euro, s, useURLencode);
repl(F("{Y}"), yen, s, useURLencode);
repl(F("&yen;"), yen, s, useURLencode);
repl(F("{P}"), pound, s, useURLencode);
repl(F("&pound;"), pound, s, useURLencode);
repl(F("{c}"), cent, s, useURLencode);
repl(F("&cent;"), cent, s, useURLencode);
}
{
// Math symbols
const char sup1[3] = {0xc2, 0xb9, 0}; // Unicode sup1 symbol
const char sup2[3] = {0xc2, 0xb2, 0}; // Unicode sup2 symbol
const char sup3[3] = {0xc2, 0xb3, 0}; // Unicode sup3 symbol
const char frac14[3] = {0xc2, 0xbc, 0}; // Unicode frac14 symbol
const char frac12[3] = {0xc2, 0xbd, 0}; // Unicode frac12 symbol
const char frac34[3] = {0xc2, 0xbe, 0}; // Unicode frac34 symbol
const char plusmn[3] = {0xc2, 0xb1, 0}; // Unicode plusmn symbol
const char times[3] = {0xc3, 0x97, 0}; // Unicode times symbol
const char divide[3] = {0xc3, 0xb7, 0}; // Unicode divide symbol
repl(F("{^1}"), sup1, s, useURLencode);
repl(F("&sup1;"), sup1, s, useURLencode);
repl(F("{^2}"), sup2, s, useURLencode);
repl(F("&sup2;"), sup2, s, useURLencode);
repl(F("{^3}"), sup3, s, useURLencode);
repl(F("&sup3;"), sup3, s, useURLencode);
repl(F("{1_4}"), frac14, s, useURLencode);
repl(F("&frac14;"), frac14, s, useURLencode);
repl(F("{1_2}"), frac12, s, useURLencode);
repl(F("&frac12;"), frac12, s, useURLencode);
repl(F("{3_4}"), frac34, s, useURLencode);
repl(F("&frac34;"), frac34, s, useURLencode);
repl(F("{+-}"), plusmn, s, useURLencode);
repl(F("&plusmn;"), plusmn, s, useURLencode);
repl(F("{x}"), times, s, useURLencode);
repl(F("&times;"), times, s, useURLencode);
repl(F("{..}"), divide, s, useURLencode);
repl(F("&divide;"), divide, s, useURLencode);
}
}
// Simple macro to create the replacement string only when needed.
#define SMART_REPL(T,S) if (s.indexOf(T) != -1) { repl((T), (S), s, useURLencode);}
void parseSystemVariables(String& s, boolean useURLencode)
{
parseSpecialCharacters(s, useURLencode);
if (s.indexOf('%') == -1)
return; // Nothing to replace
#if FEATURE_ADC_VCC
repl(F("%vcc%"), String(vcc), s, useURLencode);
#endif
repl(F("%CR%"), F("\r"), s, useURLencode);
repl(F("%LF%"), F("\n"), s, useURLencode);
SMART_REPL(F("%ip%"),WiFi.localIP().toString())
SMART_REPL(F("%rssi%"), String((WiFi.status() == WL_CONNECTED) ? WiFi.RSSI() : 0))
SMART_REPL(F("%ssid%"), (WiFi.status() == WL_CONNECTED) ? WiFi.SSID() : F("--"))
SMART_REPL(F("%unit%"), String(Settings.Unit))
SMART_REPL(F("%mac%"), String(WiFi.macAddress()))
#if defined(ESP8266)
SMART_REPL(F("%mac_int%"), String(ESP.getChipId())) // Last 24 bit of MAC address as integer, to be used in rules.
#endif
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);
// valueString is being used by the macro.
char valueString[5];
#define SMART_REPL_TIME(T,F,V) if (s.indexOf(T) != -1) { sprintf_P(valueString, (F), (V)); repl((T),valueString, s, useURLencode);}
SMART_REPL_TIME(F("%syshour%"), PSTR("%02d"), hour())
SMART_REPL_TIME(F("%sysmin%"), PSTR("%02d"), minute())
SMART_REPL_TIME(F("%syssec%"),PSTR("%02d"), second())
SMART_REPL_TIME(F("%sysday%"), PSTR("%02d"), day())
SMART_REPL_TIME(F("%sysmonth%"),PSTR("%02d"), month())
SMART_REPL_TIME(F("%sysyear%"), PSTR("%04d"), year())
SMART_REPL_TIME(F("%sysyears%"),PSTR("%02d"), year()%100)
SMART_REPL(F("%sysweekday%"), String(weekday()))
SMART_REPL(F("%sysweekday_s%"), weekday_str())
#undef SMART_REPL_TIME
}
SMART_REPL(F("%lcltime%"), getDateTimeString('-',':',' '))
SMART_REPL(F("%lcltime_am%"), getDateTimeString_ampm('-',':',' '))
SMART_REPL(F("%uptime%"), String(wdcounter / 2))
repl(F("%tskname%"), ExtraTaskSettings.TaskDeviceName, s, useURLencode);
if (s.indexOf("%vname") != -1) {
repl(F("%vname1%"), ExtraTaskSettings.TaskDeviceValueNames[0], s, useURLencode);
repl(F("%vname2%"), ExtraTaskSettings.TaskDeviceValueNames[1], s, useURLencode);
repl(F("%vname3%"), ExtraTaskSettings.TaskDeviceValueNames[2], s, useURLencode);
repl(F("%vname4%"), ExtraTaskSettings.TaskDeviceValueNames[3], s, useURLencode);
}
}
void parseEventVariables(String& s, struct EventStruct *event, boolean useURLencode)
{
SMART_REPL(F("%id%"), String(event->idx))
if (s.indexOf("%val") != -1) {
if (event->sensorType == SENSOR_TYPE_LONG) {
SMART_REPL(F("%val1%"), String((unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16)))
} else {
SMART_REPL(F("%val1%"), formatUserVar(event, 0))
SMART_REPL(F("%val2%"), formatUserVar(event, 1))
SMART_REPL(F("%val3%"), formatUserVar(event, 2))
SMART_REPL(F("%val4%"), formatUserVar(event, 3))
}
}
}
#undef SMART_REPL
bool getConvertArgument(const String& marker, const String& s, float& argument, int& startIndex, int& endIndex) {
startIndex = s.indexOf(marker);
if (startIndex == -1) return false;
int startIndexArgument = startIndex + marker.length();
if (s.charAt(startIndexArgument) != '(') {
return false;
}
++startIndexArgument;
endIndex = s.indexOf(')', startIndexArgument);
if (endIndex == -1) return false;
String argumentString = s.substring(startIndexArgument, endIndex);
if (argumentString.length() == 0 || !isFloat(argumentString)) return false;
argument = argumentString.toFloat();
++endIndex; // Must also strip ')' from the original string.
return true;
}
// Parse conversions marked with "%conv_marker%(float)"
// Must be called last, since all sensor values must be converted, processed, etc.
void parseStandardConversions(String& s, boolean useURLencode) {
if (s.indexOf(F("%c_")) == -1)
return; // Nothing to replace
float arg = 0.0;
int startIndex = 0;
int endIndex = 0;
// These replacements should be done in a while loop per marker,
// since they also replace the numerical parameter.
// The marker may occur more than once per string, but with different parameters.
#define SMART_CONV(T,FUN) while (getConvertArgument((T), s, arg, startIndex, endIndex)) { repl(s.substring(startIndex, endIndex), (FUN), s, useURLencode); }
SMART_CONV(F("%c_w_dir%"), getBearing(arg))
SMART_CONV(F("%c_c2f%"), toString(CelsiusToFahrenheit(arg), 1))
SMART_CONV(F("%c_ms2Bft%"), String(m_secToBeaufort(arg)))
SMART_CONV(F("%c_cm2imp%"), centimeterToImperialLength(arg))
SMART_CONV(F("%c_mm2imp%"), millimeterToImperialLength(arg))
SMART_CONV(F("%c_m2day%"), toString(minutesToDay(arg), 2))
SMART_CONV(F("%c_m2dh%"), minutesToDayHour(arg))
SMART_CONV(F("%c_m2dhm%"), minutesToDayHourMinute(arg))
SMART_CONV(F("%c_s2dhms%"), secondsToDayHourMinuteSecond(arg))
#undef SMART_CONV
}
+553
View File
@@ -0,0 +1,553 @@
/********************************************************************************************\
Time stuff
\*********************************************************************************************/
#define SECS_PER_MIN (60UL)
#define SECS_PER_HOUR (3600UL)
#define SECS_PER_DAY (SECS_PER_HOUR * 24UL)
#define DAYS_PER_WEEK (7UL)
#define SECS_PER_WEEK (SECS_PER_DAY * DAYS_PER_WEEK)
#define SECS_PER_YEAR (SECS_PER_WEEK * 52UL)
#define SECS_YR_2000 (946684800UL) // the time at the start of y2k
#define LEAP_YEAR(Y) ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )
timeStruct tm;
uint32_t syncInterval = 3600; // time sync will be attempted after this many seconds
uint32_t sysTime = 0;
uint32_t prevMillis = 0;
uint32_t nextSyncTime = 0;
byte PrevMinutes = 0;
void breakTime(unsigned long timeInput, struct timeStruct &tm) {
uint8_t year;
uint8_t month, monthLength;
uint32_t time;
unsigned long days;
const uint8_t monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
time = (uint32_t)timeInput;
tm.Second = time % 60;
time /= 60; // now it is minutes
tm.Minute = time % 60;
time /= 60; // now it is hours
tm.Hour = time % 24;
time /= 24; // now it is days
tm.Wday = ((time + 4) % 7) + 1; // Sunday is day 1
year = 0;
days = 0;
while ((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
year++;
}
tm.Year = year; // year is offset from 1970
days -= LEAP_YEAR(year) ? 366 : 365;
time -= days; // now it is days in this year, starting at 0
days = 0;
month = 0;
monthLength = 0;
for (month = 0; month < 12; month++) {
if (month == 1) { // february
if (LEAP_YEAR(year)) {
monthLength = 29;
} else {
monthLength = 28;
}
} else {
monthLength = monthDays[month];
}
if (time >= monthLength) {
time -= monthLength;
} else {
break;
}
}
tm.Month = month + 1; // jan is month 1
tm.Day = time + 1; // day of month
}
void setTime(unsigned long t) {
sysTime = (uint32_t)t;
nextSyncTime = (uint32_t)t + syncInterval;
prevMillis = millis(); // restart counting from now (thanks to Korman for this fix)
if (Settings.UseRules)
{
static bool firstUpdate = true;
String event = firstUpdate ? F("Time#Initialized") : F("Time#Set");
firstUpdate = false;
rulesProcessing(event);
}
}
unsigned long now() {
// calculate number of seconds passed since last call to now()
const long msec_passed = timePassedSince(prevMillis);
const long seconds_passed = msec_passed / 1000;
sysTime += seconds_passed;
prevMillis += seconds_passed * 1000;
if (nextSyncTime <= sysTime) {
// nextSyncTime & sysTime are in seconds
unsigned long t = getNtpTime();
if (t != 0) {
setTime(t);
applyTimeZone(t);
} else {
// Unable to sync, retry again in a minute
nextSyncTime = sysTime + 60;
}
}
uint32_t localSystime = toLocal(sysTime);
breakTime(localSystime, tm);
return (unsigned long)localSystime;
}
int year(unsigned long t) {
timeStruct tmp;
breakTime(t, tmp);
return 1970 + tmp.Year;
}
int weekday(unsigned long t) {
timeStruct tmp;
breakTime(t, tmp);
return tmp.Wday;
}
int year()
{
return 1970 + tm.Year;
}
byte month()
{
return tm.Month;
}
byte day()
{
return tm.Day;
}
byte hour()
{
return tm.Hour;
}
byte minute()
{
return tm.Minute;
}
byte second()
{
return tm.Second;
}
// day of week, sunday is day 1
int weekday()
{
return tm.Wday;
}
String weekday_str()
{
const int wday(weekday() - 1); // here: Count from Sunday = 0
const String weekDays = F("SunMonTueWedThuFriSat");
return weekDays.substring(wday * 3, wday * 3 + 3);
}
void initTime()
{
nextSyncTime = 0;
now();
}
void checkTime()
{
now();
if (tm.Minute != PrevMinutes)
{
PluginCall(PLUGIN_CLOCK_IN, 0, dummyString);
PrevMinutes = tm.Minute;
if (Settings.UseRules)
{
String event;
event.reserve(21);
event = F("Clock#Time=");
event += weekday_str();
event += ",";
if (hour() < 10)
event += "0";
event += hour();
event += ":";
if (minute() < 10)
event += "0";
event += minute();
rulesProcessing(event);
}
}
}
unsigned long getNtpTime()
{
if (!Settings.UseNTP || !WiFiConnected(100)) {
return 0;
}
IPAddress timeServerIP;
const char* ntpServerName = "pool.ntp.org";
// Have to do a lookup eacht time, since the NTP pool always returns another IP
if (Settings.NTPHost[0] != 0)
WiFi.hostByName(Settings.NTPHost, timeServerIP);
else
WiFi.hostByName(ntpServerName, timeServerIP);
if (!hostReachable(timeServerIP))
return 0;
WiFiUDP udp;
udp.begin(123);
const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
String log = F("NTP : NTP send to ");
log += timeServerIP.toString();
addLog(LOG_LEVEL_DEBUG_MORE, log);
while (udp.parsePacket() > 0) ; // discard any previously received packets
memset(packetBuffer, 0, NTP_PACKET_SIZE);
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
udp.beginPacket(timeServerIP, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
uint32_t beginWait = millis();
while (!timeOutReached(beginWait + 1000)) {
int size = udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
log = F("NTP : NTP replied: ");
log += timePassedSince(beginWait);
log += F(" mSec");
addLog(LOG_LEVEL_DEBUG_MORE, log);
return secsSince1900 - 2208988800UL;
}
}
log = F("NTP : No reply");
addLog(LOG_LEVEL_DEBUG_MORE, log);
return 0;
}
/********************************************************************************************\
Unsigned long Timer timeOut check
\*********************************************************************************************/
// Return the time difference as a signed value, taking into account the timers may overflow.
// Returned timediff is between -24.9 days and +24.9 days.
// Returned value is positive when "next" is after "prev"
long timeDiff(unsigned long prev, unsigned long next)
{
long signed_diff = 0;
// To cast a value to a signed long, the difference may not exceed half the ULONG_MAX
const unsigned long half_max_unsigned_long = 2147483647u; // = 2^31 -1
if (next >= prev) {
const unsigned long diff = next - prev;
if (diff <= half_max_unsigned_long) {
// Normal situation, just return the difference.
// Difference is a positive value.
signed_diff = static_cast<long>(diff);
} else {
// prev has overflow, return a negative difference value
signed_diff = static_cast<long>((ULONG_MAX - next) + prev + 1u);
signed_diff = -1 * signed_diff;
}
} else {
// next < prev
const unsigned long diff = prev - next;
if (diff <= half_max_unsigned_long) {
// Normal situation, return a negative difference value
signed_diff = static_cast<long>(diff);
signed_diff = -1 * signed_diff;
} else {
// next has overflow, return a positive difference value
signed_diff = static_cast<long>((ULONG_MAX - prev) + next + 1u);
}
}
return signed_diff;
}
// Compute the number of milliSeconds passed since timestamp given.
// N.B. value can be negative if the timestamp has not yet been reached.
long timePassedSince(unsigned long timestamp) {
return timeDiff(timestamp, millis());
}
// Check if a certain timeout has been reached.
boolean timeOutReached(unsigned long timer)
{
const long passed = timePassedSince(timer);
return passed >= 0;
}
/********************************************************************************************\
Convert a 32 bit integer into a string like "Sun,12:30"
\*********************************************************************************************/
String timeLong2String(unsigned long lngTime)
{
unsigned long x = 0;
String time = "";
x = (lngTime >> 16) & 0xf;
if (x == 0x0f)
x = 0;
String weekDays = F("AllSunMonTueWedThuFriSatWrkWkd");
time = weekDays.substring(x * 3, x * 3 + 3);
time += ",";
x = (lngTime >> 12) & 0xf;
if (x == 0xf)
time += "*";
else if (x == 0xe)
time += "-";
else
time += x;
x = (lngTime >> 8) & 0xf;
if (x == 0xf)
time += "*";
else if (x == 0xe)
time += "-";
else
time += x;
time += ":";
x = (lngTime >> 4) & 0xf;
if (x == 0xf)
time += "*";
else if (x == 0xe)
time += "-";
else
time += x;
x = (lngTime) & 0xf;
if (x == 0xf)
time += "*";
else if (x == 0xe)
time += "-";
else
time += x;
return time;
}
// returns the current Date separated by the given delimiter
// date format example with '-' delimiter: 2016-12-31 (YYYY-MM-DD)
String getDateString(const timeStruct& ts, char delimiter) {
char DateString[20]; //19 digits plus the null char
const int year = 1970 + ts.Year;
sprintf_P(DateString, PSTR("%4d%c%02d%c%02d"), year, delimiter, ts.Month, delimiter, ts.Day);
return DateString;
}
String getDateString(char delimiter)
{
return getDateString(tm, delimiter);
}
// returns the current Date without delimiter
// date format example: 20161231 (YYYYMMDD)
String getDateString()
{
return getDateString('\0');
}
// 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)
{
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);
}
} 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);
}
}
return TimeString;
}
String getTimeString(char delimiter, bool show_seconds /*=true*/)
{
return getTimeString(tm, delimiter, false, show_seconds);
}
String getTimeString_ampm(char delimiter, bool show_seconds /*=true*/)
{
return getTimeString(tm, delimiter, true, show_seconds);
}
// returns the current Time without delimiter
// time format example: 235959 (HHMMSS)
String getTimeString()
{
return getTimeString('\0');
}
String getTimeString_ampm()
{
return getTimeString_ampm('\0');
}
// returns the current Date and Time separated by the given delimiter
// if called like this: getDateTimeString('\0', '\0', '\0');
// it will give back this: 20161231235959 (YYYYMMDDHHMMSS)
String getDateTimeString(const timeStruct& ts, char dateDelimiter, char timeDelimiter, char dateTimeDelimiter, bool am_pm)
{
String ret = getDateString(ts, dateDelimiter);
if (dateTimeDelimiter != '\0')
ret += dateTimeDelimiter;
ret += getTimeString(ts, timeDelimiter, am_pm, true);
return ret;
}
String getDateTimeString(char dateDelimiter, char timeDelimiter, char dateTimeDelimiter) {
return getDateTimeString(tm, dateDelimiter, timeDelimiter, dateTimeDelimiter, false);
}
String getDateTimeString_ampm(char dateDelimiter, char timeDelimiter, char dateTimeDelimiter) {
return getDateTimeString(tm, dateDelimiter, timeDelimiter, dateTimeDelimiter, true);
}
/********************************************************************************************\
Convert a string like "Sun,12:30" into a 32 bit integer
\*********************************************************************************************/
unsigned long string2TimeLong(const String &str)
{
// format 0000WWWWAAAABBBBCCCCDDDD
// WWWW=weekday, AAAA=hours tens digit, BBBB=hours, CCCC=minutes tens digit DDDD=minutes
char command[20];
char TmpStr1[10];
int w, x, y;
unsigned long a;
{
// Within a scope so the tmpString is only used for copy.
String tmpString(str);
tmpString.toLowerCase();
tmpString.toCharArray(command, 20);
}
unsigned long lngTime = 0;
if (GetArgv(command, TmpStr1, 1))
{
String day = TmpStr1;
String weekDays = F("allsunmontuewedthufrisatwrkwkd");
y = weekDays.indexOf(TmpStr1) / 3;
if (y == 0)
y = 0xf; // wildcard is 0xf
lngTime |= (unsigned long)y << 16;
}
if (GetArgv(command, TmpStr1, 2))
{
y = 0;
for (x = strlen(TmpStr1) - 1; x >= 0; x--)
{
w = TmpStr1[x];
if ( (w >= '0' && w <= '9') || w == '*')
{
a = 0xffffffff ^ (0xfUL << y); // create mask to clean nibble position y
lngTime &= a; // maak nibble leeg
if (w == '*')
lngTime |= (0xFUL << y); // fill nibble with wildcard value
else
lngTime |= (w - '0') << y; // fill nibble with token
y += 4;
}
else
if (w == ':');
else
{
break;
}
}
}
return lngTime;
}
/********************************************************************************************\
Match clock event
\*********************************************************************************************/
boolean matchClockEvent(unsigned long clockEvent, unsigned long clockSet)
{
unsigned long Mask;
for (byte y = 0; y < 8; y++)
{
if (((clockSet >> (y * 4)) & 0xf) == 0xf) // if nibble y has the wildcard value 0xf
{
Mask = 0xffffffff ^ (0xFUL << (y * 4)); // Mask to wipe nibble position y.
clockEvent &= Mask; // clear nibble
clockEvent |= (0xFUL << (y * 4)); // fill with wildcard value 0xf
}
}
if (((clockSet >> (16)) & 0xf) == 0x8) // if weekday nibble has the wildcard value 0x8 (workdays)
if (weekday() >= 2 and weekday() <= 6) // and we have a working day today...
{
Mask = 0xffffffff ^ (0xFUL << (16)); // Mask to wipe nibble position.
clockEvent &= Mask; // clear nibble
clockEvent |= (0x8UL << (16)); // fill with wildcard value 0x8
}
if (((clockSet >> (16)) & 0xf) == 0x9) // if weekday nibble has the wildcard value 0x9 (weekends)
if (weekday() == 1 or weekday() == 7) // and we have a weekend day today...
{
Mask = 0xffffffff ^ (0xFUL << (16)); // Mask to wipe nibble position.
clockEvent &= Mask; // clear nibble
clockEvent |= (0x9UL << (16)); // fill with wildcard value 0x9
}
if (clockEvent == clockSet)
return true;
return false;
}
+251
View File
@@ -0,0 +1,251 @@
/********************************************************************************************\
Time zone
\*********************************************************************************************/
// Borrowed code from Timezone: https://github.com/JChristensen/Timezon
TimeChangeRule m_dst; // rule for start of dst or summer time for any year
TimeChangeRule m_std; // rule for start of standard time for any year
uint32_t m_dstUTC = 0; // dst start for given/current year, given in UTC
uint32_t m_stdUTC = 0; // std time start for given/current year, given in UTC
uint32_t m_dstLoc = 0; // dst start for given/current year, given in local time
uint32_t m_stdLoc = 0; // std time start for given/current year, given in local time
/*
// Examples time zones
// Australia Eastern Time Zone (Sydney, Melbourne)
TimeChangeRule aEDT = {First, Sun, Oct, 2, 660}; // UTC + 11 hours
TimeChangeRule aEST = {First, Sun, Apr, 3, 600}; // UTC + 10 hours
setTimeZone(aEDT, aEST);
// Central European Time (Frankfurt, Paris)
TimeChangeRule CEST = {Last, Sun, Mar, 2, 120}; // Central European Summer Time
TimeChangeRule CET = {Last, Sun, Oct, 3, 60}; // Central European Standard Time
setTimeZone(CEST, CET);
// United Kingdom (London, Belfast)
TimeChangeRule BST = {Last, Sun, Mar, 1, 60}; // British Summer Time
TimeChangeRule GMT = {Last, Sun, Oct, 2, 0}; // Standard Time
setTimeZone(BST, GMT);
// UTC
TimeChangeRule utcRule = {Last, Sun, Mar, 1, 0}; // UTC
setTimeZone(utcRule, utcRule);
// US Eastern Time Zone (New York, Detroit)
TimeChangeRule usEDT = {Second, Sun, Mar, 2, -240}; // Eastern Daylight Time = UTC - 4 hours
TimeChangeRule usEST = {First, Sun, Nov, 2, -300}; // Eastern Standard Time = UTC - 5 hours
setTimeZone(usEDT, usEST);
// US Central Time Zone (Chicago, Houston)
TimeChangeRule usCDT = {Second, dowSunday, Mar, 2, -300};
TimeChangeRule usCST = {First, dowSunday, Nov, 2, -360};
setTimeZone(usCDT, usCST);
// US Mountain Time Zone (Denver, Salt Lake City)
TimeChangeRule usMDT = {Second, dowSunday, Mar, 2, -360};
TimeChangeRule usMST = {First, dowSunday, Nov, 2, -420};
setTimeZone(usMDT, usMST);
// Arizona is US Mountain Time Zone but does not use DST
setTimeZone(usMST, usMST);
// US Pacific Time Zone (Las Vegas, Los Angeles)
TimeChangeRule usPDT = {Second, dowSunday, Mar, 2, -420};
TimeChangeRule usPST = {First, dowSunday, Nov, 2, -480};
setTimeZone(usPDT, usPST);
*/
void getDefaultDst_flash_values(uint16_t& start, uint16_t& end) {
// DST start: Last Sunday March 2am => 3am
// DST end: Last Sunday October 3am => 2am
TimeChangeRule CEST(Last, Sun, Mar, 2, Settings.TimeZone); // Summer Time
TimeChangeRule CET(Last, Sun, Oct, 3, Settings.TimeZone); // Standard Time
start = CEST.toFlashStoredValue();
end = CET.toFlashStoredValue();
}
void applyTimeZone(uint32_t curTime) {
int dst_offset = Settings.DST ? 60 : 0;
uint16_t tmpStart(Settings.DST_Start);
uint16_t tmpEnd(Settings.DST_End);
for (int i = 0; i < 2; ++i) {
TimeChangeRule start(tmpStart, Settings.TimeZone + dst_offset); // Summer Time
TimeChangeRule end(tmpEnd, Settings.TimeZone); // Standard Time
if (start.isValid() && end.isValid()) {
setTimeZone(start, end, curTime);
return;
}
getDefaultDst_flash_values(tmpStart, tmpEnd);
}
}
void setTimeZone(const TimeChangeRule& dstStart, const TimeChangeRule& stdStart, uint32_t curTime) {
m_dst = dstStart;
m_std = stdStart;
if (calcTimeChanges(year(curTime))) {
logTimeZoneInfo();
}
}
void logTimeZoneInfo() {
String log = F("Current Time Zone: ");
if (m_std.offset != m_dst.offset) {
// Summer time
log += F(" DST time start: ");
if (m_dstLoc != 0) {
timeStruct tmp;
breakTime(m_dstLoc, tmp);
log += getDateTimeString(tmp, '-', ':', ' ', false);
}
log += F(" offset: ");
log += m_dst.offset;
log += F(" min");
}
// Standard/Winter time.
log += F("STD time start: ");
if (m_stdLoc != 0) {
timeStruct tmp;
breakTime(m_stdLoc, tmp);
log += getDateTimeString(tmp, '-', ':', ' ', false);
}
log += F(" offset: ");
log += m_std.offset;
log += F(" min");
addLog(LOG_LEVEL_INFO, log);
}
uint32_t makeTime(const timeStruct &tm) {
// assemble time elements into uint32_t
// note year argument is offset from 1970 (see macros in time.h to convert to other formats)
// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9
const uint8_t monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int i;
uint32_t seconds;
// seconds from 1970 till 1 jan 00:00:00 of the given year
seconds= tm.Year*(SECS_PER_DAY * 365);
for (i = 0; i < tm.Year; i++) {
if (LEAP_YEAR(i)) {
seconds += SECS_PER_DAY; // add extra days for leap years
}
}
// add days for this year, months start from 1
for (i = 1; i < tm.Month; i++) {
if ( (i == 2) && LEAP_YEAR(tm.Year)) {
seconds += SECS_PER_DAY * 29;
} else {
seconds += SECS_PER_DAY * monthDays[i-1]; //monthDay array starts from 0
}
}
seconds+= (tm.Day-1) * SECS_PER_DAY;
seconds+= tm.Hour * SECS_PER_HOUR;
seconds+= tm.Minute * SECS_PER_MIN;
seconds+= tm.Second;
return (uint32_t)seconds;
}
///*----------------------------------------------------------------------*
// * Convert the given time change rule to a uint32_t value *
// * for the given year. *
// *----------------------------------------------------------------------*/
uint32_t calcTimeChangeForRule(const TimeChangeRule& r, int yr)
{
uint8_t m = r.month; // temp copies of r.month and r.week
uint8_t w = r.week;
if (w == 0) // is this a "Last week" rule?
{
if (++m > 12) // yes, for "Last", go to the next month
{
m = 1;
++yr;
}
w = 1; // and treat as first week of next month, subtract 7 days later
}
// calculate first day of the month, or for "Last" rules, first day of the next month
timeStruct tm;
tm.Hour = r.hour;
tm.Minute = 0;
tm.Second = 0;
tm.Day = 1;
tm.Month = m;
tm.Year = yr - 1970;
uint32_t t = makeTime(tm);
// add offset from the first of the month to r.dow, and offset for the given week
t += ( (r.dow - weekday(t) + 7) % 7 + (w - 1) * 7 ) * SECS_PER_DAY;
// back up a week if this is a "Last" rule
if (r.week == 0) t -= 7 * SECS_PER_DAY;
return t;
}
/*----------------------------------------------------------------------*
* Calculate the DST and standard time change points for the given *
* given year as local and UTC uint32_t values. *
*----------------------------------------------------------------------*/
bool calcTimeChanges(int yr)
{
uint32_t dstLoc = calcTimeChangeForRule(m_dst, yr);
uint32_t stdLoc = calcTimeChangeForRule(m_std, yr);
bool changed = (m_dstLoc != dstLoc) || (m_stdLoc != stdLoc);
m_dstLoc = dstLoc;
m_stdLoc = stdLoc;
m_dstUTC = m_dstLoc - m_std.offset * SECS_PER_MIN;
m_stdUTC = m_stdLoc - m_dst.offset * SECS_PER_MIN;
return changed;
}
/*----------------------------------------------------------------------*
* Convert the given UTC time to local time, standard or *
* daylight time, as appropriate. *
*----------------------------------------------------------------------*/
uint32_t toLocal(uint32_t utc)
{
// recalculate the time change points if needed
if (year(utc) != year(m_dstUTC)) calcTimeChanges(year(utc));
if (utcIsDST(utc))
return utc + m_dst.offset * SECS_PER_MIN;
else
return utc + m_std.offset * SECS_PER_MIN;
}
/*----------------------------------------------------------------------*
* Determine whether the given UTC uint32_t is within the DST interval *
* or the Standard time interval. *
*----------------------------------------------------------------------*/
bool utcIsDST(uint32_t utc)
{
// recalculate the time change points if needed
if (year(utc) != year(m_dstUTC)) calcTimeChanges(year(utc));
if (m_stdUTC == m_dstUTC) // daylight time not observed in this tz
return false;
else if (m_stdUTC > m_dstUTC) // northern hemisphere
return (utc >= m_dstUTC && utc < m_stdUTC);
else // southern hemisphere
return !(utc >= m_stdUTC && utc < m_dstUTC);
}
/*----------------------------------------------------------------------*
* Determine whether the given Local uint32_t is within the DST interval *
* or the Standard time interval. *
*----------------------------------------------------------------------*/
bool locIsDST(uint32_t local)
{
// recalculate the time change points if needed
if (year(local) != year(m_dstLoc)) calcTimeChanges(year(local));
if (m_stdUTC == m_dstUTC) // daylight time not observed in this tz
return false;
else if (m_stdLoc > m_dstLoc) // northern hemisphere
return (local >= m_dstLoc && local < m_stdLoc);
else // southern hemisphere
return !(local >= m_stdLoc && local < m_dstLoc);
}
+2232 -1327
View File
File diff suppressed because it is too large Load Diff
+269 -104
View File
@@ -4,7 +4,7 @@
String WifiGetAPssid()
{
String ssid(Settings.Name);
ssid+=F("_");
ssid+=F("-");
ssid+=Settings.Unit;
return (ssid);
}
@@ -27,7 +27,10 @@ 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
WiFi.softAP(WifiGetAPssid().c_str(), SecuritySettings.WifiAPKey);
String softAPSSID=WifiGetAPssid();
String pwd = SecuritySettings.WifiAPKey;
WiFi.softAP(softAPSSID.c_str(),pwd.c_str());
// We start in STA mode
WifiAPMode(false);
@@ -75,10 +78,9 @@ void WifiAPMode(boolean state)
//********************************************************************************
// Configure network and connect to Wifi SSID and SSID2
// Set Wifi config
//********************************************************************************
boolean WifiConnect(byte connectAttempts)
{
bool prepareWiFi() {
String log = "";
char hostname[40];
strncpy(hostname, WifiGetHostname().c_str(), sizeof(hostname));
@@ -98,128 +100,284 @@ boolean WifiConnect(byte connectAttempts)
IPAddress dns = Settings.DNS;
WiFi.config(ip, gw, subnet, dns);
}
return selectValidWiFiSettings();
}
//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);
//********************************************************************************
// 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);
}
#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
return(true);
}
addLog(LOG_LEVEL_ERROR, F("WIFI : Could not connect to AP!"));
//everything failed, activate AP mode (will deactivate automaticly after a while if its connected again)
//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 WifiConnectSSID(char WifiSSID[], char WifiKey[], byte connectAttempts)
boolean WifiConnectAndWait(byte connectAttempts)
{
String log;
//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++)
wifiConnected = false;
wifi_connect_attempt = 0;
for (byte tryConnect = 0; tryConnect < connectAttempts; tryConnect++)
{
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 (WiFi.status() != WL_CONNECTED)
{
statusLED(false);
if (tryConnectWiFi()) {
do {
if (checkWifiJustConnected())
return true;
delay(50);
}
else
break;
} while (!wifiConnectTimeoutReached());
}
if (WiFi.status() == WL_CONNECTED)
{
if (Settings.UseNTP) {
initTime();
}
log = F("WIFI : Connected! IP: ");
IPAddress ip = WiFi.localIP();
char str[20];
sprintf_P(str, PSTR("%u.%u.%u.%u"), ip[0], ip[1], ip[2], ip[3]);
log += str;
log += F(" (");
log += WifiGetHostname();
log += F(")");
addLog(LOG_LEVEL_INFO, log);
statusLED(true);
return(true);
}
else
{
// log = F("WIFI : Disconnecting!");
// addLog(LOG_LEVEL_INFO, log);
// log = F("WIFI : Disconnecting!");
// addLog(LOG_LEVEL_INFO, log);
#if defined(ESP8266)
ETS_UART_INTR_DISABLE();
wifi_station_disconnect();
ETS_UART_INTR_ENABLE();
for (byte x = 0; x < 20; x++)
{
statusLED(true);
delay(50);
}
#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
@@ -227,6 +385,7 @@ boolean WifiConnectSSID(char WifiSSID[], char WifiKey[], byte connectAttempts)
void WifiDisconnect()
{
WiFi.disconnect();
wifiConnected = false;
}
@@ -268,7 +427,6 @@ void WifiScan()
//********************************************************************************
void WifiCheck()
{
if(wifiSetup)
return;
@@ -278,8 +436,11 @@ void WifiCheck()
//give it time to automaticly reconnect
if (NC_Count > 2)
{
WifiConnect(2);
if (wifiConnected) {
wifi_connect_attempt = 0;
wifiConnected = false;
WiFiConnectRelaxed();
}
C_Count=0;
NC_Count = 0;
}
@@ -294,4 +455,8 @@ void WifiCheck()
WifiAPMode(false);
}
}
if (!wifiConnected) {
if (tryConnectWiFi())
checkWifiJustConnected();
}
}
+27 -90
View File
@@ -33,7 +33,7 @@ boolean CPlugin_001(byte function, struct EventStruct *event, String& string)
{
if (event->idx != 0)
{
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
success = false;
break;
}
@@ -75,64 +75,6 @@ boolean CPlugin_001(byte function, struct EventStruct *event, String& string)
switch (event->sensorType)
{
case SENSOR_TYPE_SINGLE: // single value sensor, used for Dallas, BH1750, etc
url += F("&svalue=");
url += toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
break;
case SENSOR_TYPE_LONG: // single LONG value, stored in two floats (rfid tags)
url += F("&svalue=");
url += (unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16);
break;
case SENSOR_TYPE_DUAL: // any sensor that uses two simple values
url += F("&svalue=");
url += toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
url += (";");
url += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
break;
case SENSOR_TYPE_TEMP_HUM: // temp + hum + hum_stat, used for DHT11
url += F("&svalue=");
url += toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
url += F(";");
url += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
url += F(";");
url += humStat(UserVar[event->BaseVarIndex + 1]);
break;
case SENSOR_TYPE_TEMP_BARO: // temp + hum + hum_stat + bar + bar_fore, used for BMP085
url += F("&svalue=");
url += toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
url += F(";0;0;");
url += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
url += F(";0");
break;
case SENSOR_TYPE_TRIPLE:
url += F("&svalue=");
url += toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
url += F(";");
url += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
url += F(";");
url += toString(UserVar[event->BaseVarIndex + 2], ExtraTaskSettings.TaskDeviceValueDecimals[2]);
break;
case SENSOR_TYPE_TEMP_HUM_BARO: // temp + hum + hum_stat + bar + bar_fore, used for BME280
url += F("&svalue=");
url += toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
url += F(";");
url += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
url += F(";");
url += humStat(UserVar[event->BaseVarIndex + 1]);
url += F(";");
url += toString(UserVar[event->BaseVarIndex + 2], ExtraTaskSettings.TaskDeviceValueDecimals[2]);
url += F(";0");
break;
case SENSOR_TYPE_QUAD:
url += F("&svalue=");
url += toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
url += F(";");
url += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
url += F(";");
url += toString(UserVar[event->BaseVarIndex + 2], ExtraTaskSettings.TaskDeviceValueDecimals[2]);
url += F(";");
url += toString(UserVar[event->BaseVarIndex + 3], ExtraTaskSettings.TaskDeviceValueDecimals[3]);
break;
case SENSOR_TYPE_SWITCH:
url = F("/json.htm?type=command&param=switchlight&idx=");
url += event->idx;
@@ -146,28 +88,39 @@ boolean CPlugin_001(byte function, struct EventStruct *event, String& string)
url = F("/json.htm?type=command&param=switchlight&idx=");
url += event->idx;
url += F("&switchcmd=");
if (UserVar[event->BaseVarIndex] == 0)
if (UserVar[event->BaseVarIndex] == 0) {
url += ("Off");
else
{
} else {
url += F("Set%20Level&level=");
url += UserVar[event->BaseVarIndex];
}
break;
case (SENSOR_TYPE_WIND):
url += F("&svalue="); // WindDir in degrees; WindDir as text; Wind speed average ; Wind speed gust; 0
url += toString(UserVar[event->BaseVarIndex],ExtraTaskSettings.TaskDeviceValueDecimals[0]);
url += ";";
url += getBearing(UserVar[event->BaseVarIndex]);
url += ";";
// Domoticz expects the wind speed in (m/s * 10)
url += toString((UserVar[event->BaseVarIndex + 1] * 10),ExtraTaskSettings.TaskDeviceValueDecimals[1]);
url += ";";
url += toString((UserVar[event->BaseVarIndex + 2] * 10),ExtraTaskSettings.TaskDeviceValueDecimals[2]);
url += ";0";
case SENSOR_TYPE_SINGLE:
case SENSOR_TYPE_LONG:
case SENSOR_TYPE_DUAL:
case SENSOR_TYPE_TRIPLE:
case SENSOR_TYPE_QUAD:
case SENSOR_TYPE_TEMP_HUM:
case SENSOR_TYPE_TEMP_BARO:
case SENSOR_TYPE_TEMP_HUM_BARO:
case SENSOR_TYPE_WIND:
default:
url = F("/json.htm?type=command&param=udevice&idx=");
url += event->idx;
url += F("&nvalue=0");
url += F("&svalue=");
url += formatDomoticzSensorType(event);
break;
}
// Add WiFi reception quality
url += F("&rssi=");
url += mapRSSItoDomoticz();
#if FEATURE_ADC_VCC
url += F("&battery=");
url += mapVccToDomoticz();
#endif
// This will send the request to the server
String request = F("GET ");
@@ -181,7 +134,7 @@ boolean CPlugin_001(byte function, struct EventStruct *event, String& string)
client.print(request);
unsigned long timer = millis() + 200;
while (!client.available() && !timeOutReached(timer))
while (!client.available() && !timeOutReached(timer))
yield();
// Read all the lines of the reply from server and log them
@@ -211,19 +164,3 @@ boolean CPlugin_001(byte function, struct EventStruct *event, String& string)
}
return success;
}
int humStat(int hum){
int lHumStat;
if(hum<30){
lHumStat = 2;
}else if(hum<40){
lHumStat = 0;
}else if(hum<59){
lHumStat = 1;
}else{
lHumStat = 3;
}
return lHumStat;
}
+95 -162
View File
@@ -44,81 +44,86 @@ boolean CPlugin_002(byte function, struct EventStruct *event, String& string)
// char json[512];
// json[0] = 0;
// event->String2.toCharArray(json, 512);
// Find first enabled controller index with this protocol
byte ControllerID = findFirstEnabledControllerWithId(CPLUGIN_ID_002);
if (ControllerID < CONTROLLER_MAX) {
StaticJsonBuffer<512> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(event->String2.c_str());
if (root.success())
{
unsigned int idx = root[F("idx")];
float nvalue = root[F("nvalue")];
long nvaluealt = root[F("nvalue")];
//const char* name = root["name"]; // Not used
//const char* svalue = root["svalue"]; // Not used
const char* svalue1 = root[F("svalue1")];
//const char* svalue2 = root["svalue2"]; // Not used
//const char* svalue3 = root["svalue3"]; // Not used
const char* switchtype = root[F("switchType")]; // Expect "On/Off" or "dimmer"
if (nvalue == 0)
nvalue = nvaluealt;
if ((int)switchtype == 0)
switchtype = "?";
StaticJsonBuffer<512> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(event->String2.c_str());
if (root.success())
{
unsigned int idx = root[F("idx")];
float nvalue = root[F("nvalue")];
long nvaluealt = root[F("nvalue")];
//const char* name = root["name"]; // Not used
//const char* svalue = root["svalue"]; // Not used
const char* svalue1 = root[F("svalue1")];
//const char* svalue2 = root["svalue2"]; // Not used
//const char* svalue3 = root["svalue3"]; // Not used
const char* switchtype = root[F("switchType")]; // Expect "On/Off" or "dimmer"
if (nvalue == 0)
nvalue = nvaluealt;
if ((int)switchtype == 0)
switchtype = "?";
for (byte x = 0; x < TASKS_MAX; x++) {
// We need the index of the controller we are: 0-CONTROLLER_MAX
byte ControllerID = 0;
for (byte i=0; i < CONTROLLER_MAX; i++)
{
if (Settings.Protocol[i] == CPLUGIN_ID_002) { ControllerID = i; }
}
if (Settings.TaskDeviceID[ControllerID][x] == idx) // get idx for our controller index
{
if (Settings.TaskDeviceNumber[x] == 1) // temp solution, if input switch, update state
{
String action = F("inputSwitchState,");
action += x;
action += ",";
action += nvalue;
struct EventStruct TempEvent;
parseCommandString(&TempEvent, action);
PluginCall(PLUGIN_WRITE, &TempEvent, action);
}
if (Settings.TaskDeviceNumber[x] == 29) // temp solution, if plugin 029, set gpio
for (byte x = 0; x < TASKS_MAX; x++) {
// We need the index of the controller we are: 0...CONTROLLER_MAX
if (Settings.TaskDeviceEnabled[x] && Settings.TaskDeviceID[ControllerID][x] == idx) // get idx for our controller index
{
String action = "";
int baseVar = x * VARS_PER_TASK;
struct EventStruct TempEvent;
if (strcasecmp_P(switchtype, PSTR("dimmer")) == 0)
{
int pwmValue = UserVar[baseVar];
action = F("pwm,");
action += Settings.TaskDevicePin1[x];
action += ",";
switch ((int)nvalue)
switch (Settings.TaskDeviceNumber[x]) {
case 1: // temp solution, if input switch, update state
{
case 0:
pwmValue = 0;
break;
case 1:
pwmValue = UserVar[baseVar];
break;
case 2:
pwmValue = 10 * atol(svalue1);
UserVar[baseVar] = pwmValue;
break;
action = F("inputSwitchState,");
action += x;
action += ",";
action += nvalue;
break;
}
action += pwmValue;
case 29: // temp solution, if plugin 029, set gpio
{
action = "";
int baseVar = x * VARS_PER_TASK;
struct EventStruct TempEvent;
if (strcasecmp_P(switchtype, PSTR("dimmer")) == 0)
{
int pwmValue = UserVar[baseVar];
action = F("pwm,");
action += Settings.TaskDevicePin1[x];
action += ",";
switch ((int)nvalue)
{
case 0:
pwmValue = 0;
break;
case 1:
pwmValue = UserVar[baseVar];
break;
case 2:
pwmValue = 10 * atol(svalue1);
UserVar[baseVar] = pwmValue;
break;
}
action += pwmValue;
} else {
UserVar[baseVar] = nvalue;
action = F("gpio,");
action += Settings.TaskDevicePin1[x];
action += ",";
action += nvalue;
}
break;
}
default:
break;
}
else
{
UserVar[baseVar] = nvalue;
action = F("gpio,");
action += Settings.TaskDevicePin1[x];
action += ",";
action += nvalue;
if (action.length() > 0) {
struct EventStruct TempEvent;
parseCommandString(&TempEvent, action);
PluginCall(PLUGIN_WRITE, &TempEvent, action);
// trigger rulesprocessing
if (Settings.UseRules)
createRuleEvents(x);
}
parseCommandString(&TempEvent, action);
PluginCall(PLUGIN_WRITE, &TempEvent, action);
}
}
}
@@ -130,89 +135,23 @@ boolean CPlugin_002(byte function, struct EventStruct *event, String& string)
{
if (event->idx != 0)
{
if (WiFi.status() != WL_CONNECTED) {
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
if (!ControllerSettings.checkHostReachable(true)) {
success = false;
break;
}
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root[F("idx")] = event->idx;
String values;
// char str[80];
root[F("RSSI")] = mapRSSItoDomoticz();
#if FEATURE_ADC_VCC
root[F("Battery")] = mapVccToDomoticz();
#endif
switch (event->sensorType)
{
case SENSOR_TYPE_SINGLE: // single value sensor, used for Dallas, BH1750, etc
root[F("nvalue")] = 0;
values = toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
// values.toCharArray(str, 80);
root[F("svalue")] = values.c_str();
break;
case SENSOR_TYPE_LONG: // single LONG value, stored in two floats (rfid tags)
root[F("nvalue")] = 0;
values = (unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16);
// values.toCharArray(str, 80);
root[F("svalue")] = values.c_str();
break;
case SENSOR_TYPE_DUAL: // any sensor that uses two simple values
root[F("nvalue")] = 0;
values = toString(UserVar[event->BaseVarIndex ], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
values += ";";
values += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
// values.toCharArray(str, 80);
root[F("svalue")] = values.c_str();
// root[F("svalue")] = str;
break;
case SENSOR_TYPE_TRIPLE: // any sensor that uses three simple values
root[F("nvalue")] = 0;
values = toString(UserVar[event->BaseVarIndex ], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
values += ";";
values += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
values += ";";
values += toString(UserVar[event->BaseVarIndex + 2], ExtraTaskSettings.TaskDeviceValueDecimals[2]);
// values.toCharArray(str, 80);
root[F("svalue")] = values.c_str();
// root[F("svalue")] = str;
break;
case SENSOR_TYPE_TEMP_HUM: // temp + hum + hum_stat, used for DHT11
root[F("nvalue")] = 0;
values = toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
values += ";";
values += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
values += ";0";
// values.toCharArray(str, 80);
root[F("svalue")] = values.c_str();
// root[F("svalue")] = str;
break;
case SENSOR_TYPE_TEMP_BARO: // temp + hum + hum_stat + bar + bar_fore, used for BMP085
root[F("nvalue")] = 0;
values = toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
values += ";0;0;";
values += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
values += ";0";
// values.toCharArray(str, 80);
root[F("svalue")] = values.c_str();
// root[F("svalue")] = str;
break;
case SENSOR_TYPE_TEMP_HUM_BARO: // temp + hum + hum_stat + bar + bar_fore, used for BME280
root[F("nvalue")] = 0;
values = toString(UserVar[event->BaseVarIndex], ExtraTaskSettings.TaskDeviceValueDecimals[0]);
values += ";";
values += toString(UserVar[event->BaseVarIndex + 1], ExtraTaskSettings.TaskDeviceValueDecimals[1]);
values += ";0;";
values += toString(UserVar[event->BaseVarIndex + 2], ExtraTaskSettings.TaskDeviceValueDecimals[2]);
values += ";0";
root[F("svalue")] = values.c_str();
// values.toCharArray(str, 80);
// root[F("svalue")] = str;
break;
case SENSOR_TYPE_SWITCH:
root[F("command")] = String(F("switchlight"));
if (UserVar[event->BaseVarIndex] == 0)
@@ -227,19 +166,19 @@ boolean CPlugin_002(byte function, struct EventStruct *event, String& string)
else
root[F("Set%20Level")] = UserVar[event->BaseVarIndex];
break;
case SENSOR_TYPE_WIND: // WindDir in degrees; WindDir as text; Wind speed average ; Wind speed gust
values = toString(UserVar[event->BaseVarIndex],ExtraTaskSettings.TaskDeviceValueDecimals[0]);
values += ";";
values += getBearing(int(UserVar[event->BaseVarIndex] / 22.5));
values += ";";
// Domoticz expects the wind speed in (m/s * 10)
values += toString((UserVar[event->BaseVarIndex + 1] * 10),ExtraTaskSettings.TaskDeviceValueDecimals[1]);
values += ";";
values += toString((UserVar[event->BaseVarIndex + 2] * 10),ExtraTaskSettings.TaskDeviceValueDecimals[2]);
values += ";0;0";
root[F("svalue")] = values.c_str();
// values.toCharArray(str, 80);
// root["svalue"] = str;
case SENSOR_TYPE_SINGLE:
case SENSOR_TYPE_LONG:
case SENSOR_TYPE_DUAL:
case SENSOR_TYPE_TRIPLE:
case SENSOR_TYPE_QUAD:
case SENSOR_TYPE_TEMP_HUM:
case SENSOR_TYPE_TEMP_BARO:
case SENSOR_TYPE_TEMP_HUM_BARO:
case SENSOR_TYPE_WIND:
default:
root[F("nvalue")] = 0;
root[F("svalue")] = formatDomoticzSensorType(event);
break;
}
@@ -250,15 +189,9 @@ boolean CPlugin_002(byte function, struct EventStruct *event, String& string)
addLog(LOG_LEVEL_DEBUG, log);
String pubname = ControllerSettings.Publish;
pubname.replace(F("%sysname%"), Settings.Name);
pubname.replace(F("%tskname%"), ExtraTaskSettings.TaskDeviceName);
pubname.replace(F("%id%"), String(event->idx));
if (!MQTTclient.publish(pubname.c_str(), json.c_str(), Settings.MQTTRetainFlag))
parseControllerVariables(pubname, event, false);
if (!MQTTpublish(event->ControllerIndex, pubname.c_str(), json.c_str(), Settings.MQTTRetainFlag))
{
log = F("MQTT : publish failed");
addLog(LOG_LEVEL_DEBUG, log);
MQTTConnect();
connectionFailures++;
}
else if (connectionFailures)
+6 -6
View File
@@ -54,11 +54,11 @@ boolean CPlugin_003(byte function, struct EventStruct *event, String& string)
String url = F("variableset ");
url += event->idx;
url += ",";
url += toString(UserVar[event->BaseVarIndex],ExtraTaskSettings.TaskDeviceValueDecimals[0]);
url += formatUserVar(event, 0);
url += "\n";
strcpy_P(log, PSTR("TELNT: Sending enter"));
addLog(LOG_LEVEL_ERROR, log);
// strcpy_P(log, PSTR("TELNT: Sending enter"));
// addLog(LOG_LEVEL_ERROR, log);
client.print(" \n");
unsigned long timer = millis() + 200;
@@ -77,20 +77,20 @@ boolean CPlugin_003(byte function, struct EventStruct *event, String& string)
{
success = true;
strcpy_P(log, PSTR("TELNT: Password request ok"));
addLog(LOG_LEVEL_ERROR, log);
addLog(LOG_LEVEL_DEBUG, log);
}
delay(1);
}
strcpy_P(log, PSTR("TELNT: Sending pw"));
addLog(LOG_LEVEL_ERROR, log);
addLog(LOG_LEVEL_DEBUG, log);
client.println(SecuritySettings.ControllerPassword[event->ControllerIndex]);
delay(100);
while (client.available())
client.read();
strcpy_P(log, PSTR("TELNT: Sending cmd"));
addLog(LOG_LEVEL_ERROR, log);
addLog(LOG_LEVEL_DEBUG, log);
client.print(url);
delay(10);
while (client.available())
+18 -2
View File
@@ -16,7 +16,7 @@ boolean CPlugin_004(byte function, struct EventStruct *event, String& string)
{
Protocol[++protocolCount].Number = CPLUGIN_ID_004;
Protocol[protocolCount].usesMQTT = false;
Protocol[protocolCount].usesAccount = false;
Protocol[protocolCount].usesAccount = true;
Protocol[protocolCount].usesPassword = true;
Protocol[protocolCount].defaultPort = 80;
Protocol[protocolCount].usesID = true;
@@ -29,6 +29,22 @@ boolean CPlugin_004(byte function, struct EventStruct *event, String& string)
break;
}
case CPLUGIN_GET_PROTOCOL_DISPLAY_NAME:
{
success = true;
switch (event->idx) {
case CONTROLLER_USER:
string = F("ThingHTTP Name");
break;
case CONTROLLER_PASS:
string = F("API Key");
break;
default:
success = false;
break;
}
}
case CPLUGIN_PROTOCOL_SEND:
{
ControllerSettingsStruct ControllerSettings;
@@ -59,7 +75,7 @@ boolean CPlugin_004(byte function, struct EventStruct *event, String& string)
postDataStr += F("&field");
postDataStr += event->idx + x;
postDataStr += "=";
postDataStr += toString(UserVar[event->BaseVarIndex + x],ExtraTaskSettings.TaskDeviceValueDecimals[x]);
postDataStr += formatUserVar(event, x);
}
String hostName = F("api.thingspeak.com"); // PM_CZ: HTTP requests must contain host headers.
if (ControllerSettings.UseDNS)
+41 -44
View File
@@ -39,51 +39,50 @@ boolean CPlugin_005(byte function, struct EventStruct *event, String& string)
case CPLUGIN_PROTOCOL_RECV:
{
// Split topic into array
String tmpTopic = event->String1.substring(1);
String topicSplit[10];
int SlashIndex = tmpTopic.indexOf('/');
byte count = 0;
while (SlashIndex > 0 && count < 10 - 1)
{
topicSplit[count] = tmpTopic.substring(0, SlashIndex);
tmpTopic = tmpTopic.substring(SlashIndex + 1);
SlashIndex = tmpTopic.indexOf('/');
count++;
byte ControllerID = findFirstEnabledControllerWithId(CPLUGIN_ID_005);
if (ControllerID == CONTROLLER_MAX) {
// Controller is not enabled.
break;
} else {
String cmd;
struct EventStruct TempEvent;
bool validTopic = false;
const int lastindex = event->String1.lastIndexOf('/');
const String lastPartTopic = event->String1.substring(lastindex + 1);
if (lastPartTopic == F("cmd")) {
cmd = event->String2;
parseCommandString(&TempEvent, cmd);
TempEvent.Source = VALUE_SOURCE_MQTT;
validTopic = true;
} else {
if (lastindex > 0) {
// Topic has at least one separator
if (isFloat(event->String2) && isInt(lastPartTopic)) {
int prevLastindex = event->String1.lastIndexOf('/', lastindex - 1);
cmd = event->String1.substring(prevLastindex + 1, lastindex);
TempEvent.Par1 = lastPartTopic.toInt();
TempEvent.Par2 = event->String2.toFloat();
TempEvent.Par3 = 0;
validTopic = true;
}
}
}
if (validTopic) {
// in case of event, store to buffer and return...
String command = parseString(cmd, 1);
if (command == F("event")) {
eventBuffer = cmd.substring(6);
} else if (!PluginCall(PLUGIN_WRITE, &TempEvent, cmd)) {
remoteConfig(&TempEvent, cmd);
}
}
}
topicSplit[count] = tmpTopic;
String cmd = "";
struct EventStruct TempEvent;
if (topicSplit[count] == F("cmd"))
{
cmd = event->String2;
parseCommandString(&TempEvent, cmd);
TempEvent.Source = VALUE_SOURCE_MQTT;
}
else
{
cmd = topicSplit[count - 1];
TempEvent.Par1 = topicSplit[count].toInt();
TempEvent.Par2 = event->String2.toFloat();
TempEvent.Par3 = 0;
}
// in case of event, store to buffer and return...
String command = parseString(cmd, 1);
if (command == F("event"))
eventBuffer = cmd.substring(6);
else if
(PluginCall(PLUGIN_WRITE, &TempEvent, cmd));
else
remoteConfig(&TempEvent, cmd);
break;
}
case CPLUGIN_PROTOCOL_SEND:
{
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
success = false;
break;
}
@@ -96,9 +95,7 @@ boolean CPlugin_005(byte function, struct EventStruct *event, String& string)
PluginCall(PLUGIN_GET_DEVICEVALUENAMES, event, dummyString);
String pubname = ControllerSettings.Publish;
pubname.replace(F("%sysname%"), Settings.Name);
pubname.replace(F("%tskname%"), ExtraTaskSettings.TaskDeviceName);
pubname.replace(F("%id%"), String(event->idx));
parseControllerVariables(pubname, event, false);
String value = "";
// byte DeviceIndex = getDeviceIndex(Settings.TaskDeviceNumber[event->TaskIndex]);
@@ -110,8 +107,8 @@ boolean CPlugin_005(byte function, struct EventStruct *event, String& string)
if (event->sensorType == SENSOR_TYPE_LONG)
value = (unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16);
else
value = toString(UserVar[event->BaseVarIndex + x], ExtraTaskSettings.TaskDeviceValueDecimals[x]);
MQTTclient.publish(tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);
value = formatUserVar(event, x);
MQTTpublish(event->ControllerIndex, tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);
String log = F("MQTT : ");
log += tmppubname;
log += " ";
+4 -6
View File
@@ -76,7 +76,7 @@ boolean CPlugin_006(byte function, struct EventStruct *event, String& string)
case CPLUGIN_PROTOCOL_SEND:
{
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
success = false;
break;
}
@@ -89,9 +89,7 @@ boolean CPlugin_006(byte function, struct EventStruct *event, String& string)
PluginCall(PLUGIN_GET_DEVICEVALUENAMES, event, dummyString);
String pubname = ControllerSettings.Publish;
pubname.replace(F("%sysname%"), Settings.Name);
pubname.replace(F("%tskname%"), ExtraTaskSettings.TaskDeviceName);
pubname.replace(F("%id%"), String(event->idx));
parseControllerVariables(pubname, event, false);
String value = "";
// byte DeviceIndex = getDeviceIndex(Settings.TaskDeviceNumber[event->TaskIndex]);
@@ -103,8 +101,8 @@ boolean CPlugin_006(byte function, struct EventStruct *event, String& string)
if (event->sensorType == SENSOR_TYPE_LONG)
value = (unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16);
else
value = toString(UserVar[event->BaseVarIndex + x], ExtraTaskSettings.TaskDeviceValueDecimals[x]);
MQTTclient.publish(tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);
value = formatUserVar(event, x);
MQTTpublish(event->ControllerIndex, tmppubname.c_str(), value.c_str(), Settings.MQTTRetainFlag);
}
break;
}
+14 -41
View File
@@ -31,10 +31,16 @@ boolean CPlugin_007(byte function, struct EventStruct *event, String& string)
case CPLUGIN_PROTOCOL_SEND:
{
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
success = false;
break;
}
const byte valueCount = getValueCountFromSensorType(event->sensorType);
if (valueCount == 0 || valueCount > 3) {
addLog(LOG_LEVEL_ERROR, F("emoncms : Unknown sensortype or too many sensor values"));
break;
}
ControllerSettingsStruct ControllerSettings;
LoadControllerSettings(event->ControllerIndex, (byte*)&ControllerSettings, sizeof(ControllerSettings));
@@ -59,47 +65,14 @@ boolean CPlugin_007(byte function, struct EventStruct *event, String& string)
postDataStr += Settings.Unit;
postDataStr += F("&json=");
switch (event->sensorType)
{
case SENSOR_TYPE_SINGLE: // single value sensor, used for Dallas, BH1750, etc
postDataStr += F("{field");
postDataStr += event->idx;
postDataStr += ":";
postDataStr += toString(UserVar[event->BaseVarIndex],ExtraTaskSettings.TaskDeviceValueDecimals[0]);
postDataStr += "}";
break;
case SENSOR_TYPE_TEMP_HUM: // dual value
case SENSOR_TYPE_TEMP_BARO:
case SENSOR_TYPE_DUAL:
postDataStr += F("{field");
postDataStr += event->idx;
postDataStr += ":";
postDataStr += toString(UserVar[event->BaseVarIndex],ExtraTaskSettings.TaskDeviceValueDecimals[0]);
postDataStr += F(",field");
postDataStr += event->idx + 1;
postDataStr += ":";
postDataStr += toString(UserVar[event->BaseVarIndex + 1],ExtraTaskSettings.TaskDeviceValueDecimals[1]);
postDataStr += "}";
break;
case SENSOR_TYPE_TEMP_HUM_BARO:
case SENSOR_TYPE_TRIPLE:
postDataStr += F("{field");
postDataStr += event->idx;
postDataStr += ":";
postDataStr += toString(UserVar[event->BaseVarIndex],ExtraTaskSettings.TaskDeviceValueDecimals[0]);
postDataStr += F(",field");
postDataStr += event->idx + 1;
postDataStr += ":";
postDataStr += toString(UserVar[event->BaseVarIndex + 1],ExtraTaskSettings.TaskDeviceValueDecimals[1]);
postDataStr += F(",field");
postDataStr += event->idx + 2;
postDataStr += ":";
postDataStr += toString(UserVar[event->BaseVarIndex + 2],ExtraTaskSettings.TaskDeviceValueDecimals[2]);
postDataStr += "}";
break;
case SENSOR_TYPE_SWITCH:
break;
for (byte i = 0; i < valueCount; ++i) {
postDataStr += (i == 0) ? F("{") : F(",");
postDataStr += F("field");
postDataStr += event->idx + i;
postDataStr += ":";
postDataStr += formatUserVar(event, i);
}
postDataStr += "}";
postDataStr += F("&apikey=");
postDataStr += SecuritySettings.ControllerPassword[event->ControllerIndex]; // "0UDNN17RW6XAS2E5" // api key
+3 -5
View File
@@ -68,7 +68,7 @@ boolean CPlugin_008(byte function, struct EventStruct *event, String& string)
//********************************************************************************
boolean HTTPSend(struct EventStruct *event, byte varIndex, float value, unsigned long longValue)
{
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
return false;
}
ControllerSettingsStruct ControllerSettings;
@@ -105,10 +105,8 @@ boolean HTTPSend(struct EventStruct *event, byte varIndex, float value, unsigned
String url = "/";
url += ControllerSettings.Publish;
//TODO: move this to a generic replacement function?
url.replace(F("%sysname%"), URLEncode(Settings.Name));
url.replace(F("%tskname%"), URLEncode(ExtraTaskSettings.TaskDeviceName));
url.replace(F("%id%"), String(event->idx));
parseControllerVariables(url, event, true);
url.replace(F("%valname%"), URLEncode(ExtraTaskSettings.TaskDeviceValueNames[varIndex]));
if (longValue)
url.replace(F("%value%"), String(longValue));
+2 -2
View File
@@ -56,7 +56,7 @@ boolean CPlugin_009(byte function, struct EventStruct *event, String& string)
case CPLUGIN_PROTOCOL_SEND:
{
if (WiFi.status() != WL_CONNECTED) {
if (!WiFiConnected(100)) {
success = false;
break;
}
@@ -107,7 +107,7 @@ boolean CPlugin_009(byte function, struct EventStruct *event, String& string)
val[F("value")] = (unsigned long)UserVar[event->BaseVarIndex] + ((unsigned long)UserVar[event->BaseVarIndex + 1] << 16);
}
else { // All other sensor types
val[F("value")] = toString(UserVar[event->BaseVarIndex + x], ExtraTaskSettings.TaskDeviceValueDecimals[x]);
val[F("value")] = formatUserVar(event, x);
}
}
+1 -3
View File
@@ -80,9 +80,7 @@ void C010_Send(struct EventStruct *event, byte varIndex, float value, unsigned l
String msg = "";
msg += ControllerSettings.Publish;
msg.replace(F("%sysname%"), Settings.Name);
msg.replace(F("%tskname%"), ExtraTaskSettings.TaskDeviceName);
msg.replace(F("%id%"), String(event->idx));
parseControllerVariables(msg, event, false);
msg.replace(F("%valname%"), ExtraTaskSettings.TaskDeviceValueNames[varIndex]);
if (longValue)
msg.replace(F("%value%"), String(longValue));

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