Merge branch 'main' into PJH_ADD_Linearbounce

This commit is contained in:
Blaz Kristan 2023-08-01 18:08:29 +02:00
commit 9a78d28cd7
388 changed files with 98940 additions and 23608 deletions

22
.devcontainer/Dockerfile Normal file
View File

@ -0,0 +1,22 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.148.1/containers/python-3/.devcontainer/base.Dockerfile
# [Choice] Python version: 3, 3.9, 3.8, 3.7, 3.6
ARG VARIANT="3"
FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT}
# [Option] Install Node.js
ARG INSTALL_NODE="true"
ARG NODE_VERSION="lts/*"
RUN if [ "${INSTALL_NODE}" = "true" ]; then su vscode -c "source /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
# [Optional] If your pip requirements rarely change, uncomment this section to add them to the image.
# COPY requirements.txt /tmp/pip-tmp/
# RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
# && rm -rf /tmp/pip-tmp
# [Optional] Uncomment this section to install additional OS packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>
# [Optional] Uncomment this line to install global node packages.
# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1

View File

@ -0,0 +1,47 @@
{
"name": "Python 3",
"build": {
"dockerfile": "Dockerfile",
"context": "..",
"args": {
// Update 'VARIANT' to pick a Python version: 3, 3.6, 3.7, 3.8, 3.9
"VARIANT": "3",
// Options
"INSTALL_NODE": "true",
"NODE_VERSION": "lts/*"
}
},
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.shell.linux": "/bin/bash",
"python.pythonPath": "/usr/local/bin/python",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
"python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
"python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
"python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
"python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
"python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
"python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
"python.linting.pylintPath": "/usr/local/py-utils/bin/pylint"
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"ms-python.python",
"platformio.platformio-ide"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
"postCreateCommand": "npm install",
// Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode"
}

1
.envrc Normal file
View File

@ -0,0 +1 @@
layout python-venv python3

2
.github/FUNDING.yml vendored Normal file
View File

@ -0,0 +1,2 @@
github: [Aircoookie,blazoncek]
custom: ['https://paypal.me/Aircoookie','https://paypal.me/blazoncek']

View File

@ -1,27 +0,0 @@
---
name: Bug
about: Noticed an issue with your lights?
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is. Please quickly search existing issues first!
**To Reproduce**
Steps to reproduce the behavior, if consistently possible
**Expected behavior**
A clear and concise description of what you expected to happen.
**WLED version**
- Board: [e.g. Wemos D1, ESP32 dev]
- Version [e.g. 0.10.0, dev200603]
- Format [e.g. Binary, self-compiled]
**Additional context**
Anything else you'd like to say about the problem?
Thank you for your help!

86
.github/ISSUE_TEMPLATE/bug.yml vendored Normal file
View File

@ -0,0 +1,86 @@
name: Bug Report
description: File a bug report
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Please quickly search existing issues first before submitting a bug.
- type: textarea
id: what-happened
attributes:
label: What happened?
description: A clear and concise description of what the bug is.
placeholder: Tell us what the problem is.
validations:
required: true
- type: textarea
id: how-to-reproduce
attributes:
label: To Reproduce Bug
description: Steps to reproduce the behavior, if consistently possible.
placeholder: Tell us how to make the bug appear.
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected Behavior
description: A clear and concise description of what you expected to happen.
placeholder: Tell us what you expected to happen.
validations:
required: true
- type: dropdown
id: install_format
attributes:
label: Install Method
description: How did you install WLED?
options:
- Binary from WLED.me
- Self-Compiled
validations:
required: true
- type: input
id: version
attributes:
label: What version of WLED?
description: You can find this in by going to Config -> Security & Updates -> Scroll to Bottom. Copy and paste the entire line after "Server message"
placeholder: "e.g. WLED 0.13.1 (build 2203150)"
validations:
required: true
- type: dropdown
id: Board
attributes:
label: Which microcontroller/board are you seeing the problem on?
multiple: true
options:
- ESP8266
- ESP32
- ESP32-S3
- ESP32-S2
- ESP32-C3
- Other
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant log/trace output
description: Please copy and paste any relevant log output if you have it. This will be automatically formatted into code, so no need for backticks.
render: shell
- type: textarea
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false
- type: checkboxes
id: terms
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/Aircoookie/WLED/blob/master/CODE_OF_CONDUCT.md)
options:
- label: I agree to follow this project's Code of Conduct
required: true

11
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: WLED Discord community
url: https://discord.gg/KuqP7NE
about: Please ask and answer questions and discuss setup issues here!
- name: WLED community forum
url: https://wled.discourse.group/
about: For issues and ideas that might need longer discussion.
- name: kno.wled.ge base
url: https://kno.wled.ge/basics/faq/
about: Take a look at the frequently asked questions and documentation, perhaps your question is already answered!

View File

@ -1,19 +0,0 @@
---
name: Question
about: Have a question about using WLED?
title: ''
labels: question
assignees: ''
---
**Take a look at the wiki and FAQ, perhaps your question is already answered!**
[FAQ](https://github.com/Aircoookie/WLED/wiki/FAQ)
**Please consider asking your question on the WLED forum or Discord**
[Forum](https://wled.discourse.group/)
[Discord](https://discord.gg/KuqP7NE)
[What to post where?](https://github.com/Aircoookie/WLED/issues/658)
**If you do not like to use these platforms, delete this template and ask away!**
Please keep in mind though that the issue section is generally not the preferred place for general questions.

91
.github/workflows/wled-ci.yml vendored Normal file
View File

@ -0,0 +1,91 @@
name: PlatformIO CI
on: [push, pull_request]
jobs:
get_default_envs:
name: Gather Environments
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Cache pip
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-
- uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install PlatformIO
run: pip install -r requirements.txt
- name: Get default environments
id: envs
run: |
echo "environments=$(pio project config --json-output | jq -cr '.[0][1][0][1]')" >> $GITHUB_OUTPUT
outputs:
environments: ${{ steps.envs.outputs.environments }}
build:
name: Build Enviornments
runs-on: ubuntu-latest
needs: get_default_envs
strategy:
fail-fast: false
matrix:
environment: ${{ fromJSON(needs.get_default_envs.outputs.environments) }}
steps:
- uses: actions/checkout@v3
- name: Cache pip
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-
- name: Cache PlatformIO
uses: actions/cache@v3
with:
path: ~/.platformio
key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }}
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install PlatformIO
run: pip install -r requirements.txt
- name: Build firmware
env:
WLED_RELEASE: True
run: pio run -e ${{ matrix.environment }}
- uses: actions/upload-artifact@v2
with:
name: firmware-${{ matrix.environment }}
path: |
build_output/firmware/*.bin
build_output/firmware/*.gz
- uses: actions/upload-artifact@v2
if: startsWith(github.ref, 'refs/tags/')
with:
name: firmware-release
path: build_output/release/*.bin
release:
name: Create Release
runs-on: ubuntu-latest
needs: [get_default_envs, build]
if: startsWith(github.ref, 'refs/tags/')
steps:
- uses: actions/download-artifact@v2
with:
name: firmware-release
- name: Create draft release
uses: softprops/action-gh-release@v1
with:
draft: True
files: |
*.bin
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

11
.gitignore vendored
View File

@ -1,12 +1,21 @@
.pio
.cache
.pioenvs
.piolibdeps
.vscode
!.vscode/extensions.json
/wled00/Release
/wled00/extLibs
/platformio_override.ini
/wled00/my_config.h
/build_output
.DS_Store
.gitignore
.clang-format
node_modules
.idea
.direnv
wled-update.sh
esp01-update.sh
/wled00/LittleFS
replace_fs.py
wled00/wled00.ino.cpp

3
.gitpod.Dockerfile vendored Normal file
View File

@ -0,0 +1,3 @@
FROM gitpod/workspace-full
USER gitpod

11
.gitpod.yml Normal file
View File

@ -0,0 +1,11 @@
tasks:
- command: pip3 install -U platformio && platformio run
image:
file: .gitpod.Dockerfile
vscode:
extensions:
- Atishay-Jain.All-Autocomplete
- esbenp.prettier-vscode
- shardulm94.trailing-spaces

View File

@ -1,43 +0,0 @@
# Continuous Integration (CI) is the practice, in software
# engineering, of merging all developer working copies with a shared mainline
# several times a day < https://docs.platformio.org/page/ci/index.html >
#
# Documentation:
#
# * Travis CI Embedded Builds with PlatformIO
# < https://docs.travis-ci.com/user/integration/platformio/ >
#
# * PlatformIO integration with Travis CI
# < https://docs.platformio.org/page/ci/travis.html >
#
# * User Guide for `platformio ci` command
# < https://docs.platformio.org/page/userguide/cmd_ci.html >
#
#
# Please choose one of the following templates (proposed below) and uncomment
# it (remove "# " before each line) or use own configuration according to the
# Travis CI documentation (see above).
#
# * Test the Travis config here:
# < https://config.travis-ci.com/explore >
#
language: python
python:
# - "2.7"
- "3.5"
os: linux
cache:
bundler: true
ccache: true
directories:
- "~/.platformio"
- "~/.buildcache"
env:
- PLATFORMIO_CI_SRC=wled00
install:
- pip install -U platformio
- platformio update
script:
# - platformio ci --project-conf=./platformio.ini
- platformio run

View File

@ -3,5 +3,8 @@
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

42
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,42 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "Build: HTML and binary",
"dependsOn": [
"Build: HTML only",
"Build: binary only"
],
"dependsOrder": "sequence",
"problemMatcher": [
"$platformio",
],
},
{
"type": "PlatformIO",
"label": "Build: binary only",
"task": "Build",
"group": {
"kind": "build",
"isDefault": true,
},
"problemMatcher": [
"$platformio"
],
"presentation": {
"panel": "shared"
}
},
{
"type": "npm",
"script": "build",
"group": "build",
"problemMatcher": [],
"label": "Build: HTML only",
"detail": "npm run build",
"presentation": {
"panel": "shared"
}
}
]
}

File diff suppressed because it is too large Load Diff

78
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,78 @@
## Thank you for making WLED better!
Here are a few suggestions to make it easier for you to contribute!
### Code style
When in doubt, it is easiest to replicate the code style you find in the files you want to edit :)
Below are the guidelines we use in the WLED repository.
#### Indentation
We use tabs for Indentation in Web files (.html/.css/.js) and spaces (2 per indentation level) for all other files.
You are all set if you have enabled `Editor: Detect Indentation` in VS Code.
#### Blocks
Whether the opening bracket of e.g. an `if` block is in the same line as the condition or in a separate line is up to your discretion. If there is only one statement, leaving out block braches is acceptable.
Good:
```cpp
if (a == b) {
doStuff(a);
}
```
```cpp
if (a == b)
{
doStuff(a);
}
```
```cpp
if (a == b) doStuff(a);
```
There should always be a space between a keyword and its condition and between the condition and brace.
Within the condition, no space should be between the paranthesis and variables.
Spaces between variables and operators are up to the authors discretion.
There should be no space between function names and their argument parenthesis.
Good:
```cpp
if (a == b) {
doStuff(a);
}
```
Not good:
```cpp
if( a==b ){
doStuff ( a);
}
```
#### Comments
Comments should have a space between the delimiting characters (e.g. `//`) and the comment text.
Note: This is a recent change, the majority of the codebase still has comments without spaces.
Good:
```
// This is a comment.
/* This is a CSS inline comment */
/*
* This is a comment
* wrapping over multiple lines,
* used in WLED for file headers and function explanations
*/
<!-- This is an HTML comment -->
```
There is no set character limit for a comment within a line,
though as a rule of thumb you should wrap your comment if it exceeds the width of your editor window.
Inline comments are OK if they describe that line only and are not exceedingly wide.

5
images/Readme.md Normal file
View File

@ -0,0 +1,5 @@
### Additional Logos
Additional awesome logos for WLED can be found here [Aircoookie/Akemi](https://github.com/Aircoookie/Akemi).
<img src="https://github.com/Aircoookie/Akemi/blob/master/akemi/001_cheerful.png">

Binary file not shown.

Before

Width:  |  Height:  |  Size: 490 KiB

After

Width:  |  Height:  |  Size: 489 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

BIN
images/wled_logo_akemi.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
images/wled_logo_old.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

918
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "wled",
"version": "0.10.1",
"version": "0.14.0-b3",
"description": "Tools for WLED project",
"main": "tools/cdata.js",
"directories": {
@ -23,9 +23,9 @@
"homepage": "https://github.com/Aircoookie/WLED#readme",
"dependencies": {
"clean-css": "^4.2.3",
"html-minifier": "^4.0.0",
"html-minifier-terser": "^5.1.1",
"inliner": "^1.13.1",
"nodemon": "^2.0.4",
"nodemon": "^2.0.20",
"zlib": "^1.0.5"
}
}

9
pio-scripts/obj-dump.py Normal file
View File

@ -0,0 +1,9 @@
# Little convenience script to get an object dump
Import('env')
def obj_dump_after_elf(source, target, env):
print("Create firmware.asm")
env.Execute("xtensa-lx106-elf-objdump "+ "-D " + str(target[0]) + " > "+ "${PROGNAME}.asm")
env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", [obj_dump_after_elf])

View File

@ -0,0 +1,69 @@
Import('env')
import os
import shutil
import gzip
OUTPUT_DIR = "build_output{}".format(os.path.sep)
def _get_cpp_define_value(env, define):
define_list = [item[-1] for item in env["CPPDEFINES"] if item[0] == define]
if define_list:
return define_list[0]
return None
def _create_dirs(dirs=["firmware", "map"]):
# check if output directories exist and create if necessary
if not os.path.isdir(OUTPUT_DIR):
os.mkdir(OUTPUT_DIR)
for d in dirs:
if not os.path.isdir("{}{}".format(OUTPUT_DIR, d)):
os.mkdir("{}{}".format(OUTPUT_DIR, d))
def bin_rename_copy(source, target, env):
_create_dirs()
variant = env["PIOENV"]
# create string with location and file names based on variant
map_file = "{}map{}{}.map".format(OUTPUT_DIR, os.path.sep, variant)
bin_file = "{}firmware{}{}.bin".format(OUTPUT_DIR, os.path.sep, variant)
release_name = _get_cpp_define_value(env, "WLED_RELEASE_NAME")
if release_name:
_create_dirs(["release"])
version = _get_cpp_define_value(env, "WLED_VERSION")
release_file = "{}release{}WLED_{}_{}.bin".format(OUTPUT_DIR, os.path.sep, version, release_name)
shutil.copy(str(target[0]), release_file)
# check if new target files exist and remove if necessary
for f in [map_file, bin_file]:
if os.path.isfile(f):
os.remove(f)
# copy firmware.bin to firmware/<variant>.bin
shutil.copy(str(target[0]), bin_file)
# copy firmware.map to map/<variant>.map
if os.path.isfile("firmware.map"):
shutil.move("firmware.map", map_file)
def bin_gzip(source, target, env):
_create_dirs()
variant = env["PIOENV"]
# create string with location and file names based on variant
bin_file = "{}firmware{}{}.bin".format(OUTPUT_DIR, os.path.sep, variant)
gzip_file = "{}firmware{}{}.bin.gz".format(OUTPUT_DIR, os.path.sep, variant)
# check if new target files exist and remove if necessary
if os.path.isfile(gzip_file): os.remove(gzip_file)
# write gzip firmware file
with open(bin_file,"rb") as fp:
with gzip.open(gzip_file, "wb", compresslevel = 9) as f:
shutil.copyfileobj(fp, f)
env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", [bin_rename_copy, bin_gzip])

View File

@ -0,0 +1,8 @@
Import('env')
import json
PACKAGE_FILE = "package.json"
with open(PACKAGE_FILE, "r") as package:
version = json.load(package)["version"]
env.Append(BUILD_FLAGS=[f"-DWLED_VERSION={version}"])

View File

@ -0,0 +1,15 @@
Import('env')
#
# Dump build environment (for debug)
#print env.Dump()
#
flags = " ".join(env['LINKFLAGS'])
flags = flags.replace("-u _printf_float", "")
flags = flags.replace("-u _scanf_float", "")
newflags = flags.split()
env.Replace(
LINKFLAGS=newflags
)

View File

@ -0,0 +1,9 @@
Import('env')
import os
import shutil
# copy WLED00/my_config_sample.h to WLED00/my_config.h
if os.path.isfile("wled00/my_config.h"):
print ("*** use existing my_config.h ***")
else:
shutil.copy("wled00/my_config_sample.h", "wled00/my_config.h")

View File

@ -2,29 +2,27 @@
; Please visit documentation: https://docs.platformio.org/page/projectconf.html
[platformio]
src_dir = ./wled00
data_dir = ./wled00/data
lib_dir = ./wled00/src
build_cache_dir = ~/.buildcache
extra_configs =
platformio_override.ini
# ------------------------------------------------------------------------------
# ENVIRONMENTS
#
# Please uncomment one of the lines below to select your board(s)
# (use `platformio_override.ini` when building for your own board; see `platformio_override.ini.sample` for an example)
# ------------------------------------------------------------------------------
# Travis CI binaries
default_envs = travis_esp8266, esp01, esp01_1m_ota, travis_esp32
# CI binaries
; default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth # ESP32 variant builds are temporarily excluded from CI due to toolchain issues on the GitHub Actions Linux environment
default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, lolin_s2_mini, esp32c3dev, esp32s3dev_8MB, esp32s3dev_8MB_PSRAM_opi
# Release binaries
; default_envs = nodemcuv2, esp01, esp01_1m_ota, esp01_1m_full, esp32dev, custom_WS2801, custom_APA102, custom_LEDPIN_16, custom_LEDPIN_4, custom32_LEDPIN_16
; default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, lolin_s2_mini, esp32c3dev, esp32s3dev_8MB
# Build everything
; default_envs = esp32dev, esp8285_4CH_MagicHome, codm-controller-0_6-rev2, codm-controller-0_6, esp32s2_saola, d1_mini_5CH_Shojo_PCB, d1_mini, sp501e, nodemcuv2, esp32_eth, anavi_miracle_controller, esp07, esp01_1m_full, m5atom, h803wf, d1_mini_ota, heltec_wifi_kit_8, esp8285_H801, d1_mini_debug, wemos_shield_esp32, elekstube_ips
# Single binaries (uncomment your board)
; default_envs = elekstube_ips
; default_envs = nodemcuv2
; default_envs = esp01
; default_envs = esp01_1m_ota
; default_envs = esp8266_2m
; default_envs = esp01_1m_full
; default_envs = esp07
; default_envs = d1_mini
@ -34,49 +32,58 @@ default_envs = travis_esp8266, esp01, esp01_1m_ota, travis_esp32
; default_envs = d1_mini_ota
; default_envs = esp32dev
; default_envs = esp8285_4CH_MagicHome
; default_envs = esp8285_4CH_H801
; default_envs = esp8285_5CH_H801
; default_envs = esp8285_H801
; default_envs = d1_mini_5CH_Shojo_PCB
; default_envs = wemos_shield_esp32
; default_envs = m5atom
; default_envs = esp32_eth
; default_envs = esp32dev_qio80
; default_envs = esp32_eth_ota1mapp
; default_envs = esp32s2_saola
; default_envs = esp32c3dev
; default_envs = lolin_s2_mini
src_dir = ./wled00
data_dir = ./wled00/data
build_cache_dir = ~/.buildcache
extra_configs =
platformio_override.ini
[common]
# ------------------------------------------------------------------------------
# PLATFORM:
# !! DO NOT confuse platformio's ESP8266 development platform with Arduino core for ESP8266
#
# arduino core 2.3.0 = platformIO 1.5.0
# arduino core 2.4.0 = platformIO 1.6.0
# arduino core 2.4.1 = platformIO 1.7.3
# arduino core 2.4.2 = platformIO 1.8.0
# arduino core 2.5.0 = platformIO 2.0.4
# arduino core 2.5.1 = platformIO 2.1.1
# arduino core 2.5.2 = platformIO 2.2.3
# arduino core 2.6.1 = platformIO 2.3.0
# arduino core 2.6.2 = platformIO 2.3.1
# arduino core 2.6.3 = platformIO 2.3.2
# arduino core 2.7.0 = platformIO 2.5.0
# ------------------------------------------------------------------------------
arduino_core_2_3_0 = espressif8266@1.5.0
arduino_core_2_4_0 = espressif8266@1.6.0
arduino_core_2_4_1 = espressif8266@1.7.3
arduino_core_2_4_2 = espressif8266@1.8.0
arduino_core_2_5_0 = espressif8266@2.0.4
arduino_core_2_5_1 = espressif8266@2.1.1
arduino_core_2_5_2 = espressif8266@2.2.3
arduino_core_2_6_1 = espressif8266@2.3.0
arduino_core_2_6_2 = espressif8266@2.3.1
arduino_core_2_6_3 = espressif8266@2.3.3
arduino_core_2_7_1 = espressif8266@2.5.1
arduino_core_2_7_4 = espressif8266@2.6.2
arduino_core_3_0_0 = espressif8266@3.0.0
arduino_core_3_2_0 = espressif8266@3.2.0
arduino_core_4_1_0 = espressif8266@4.1.0
arduino_core_3_1_2 = espressif8266@4.2.0
# Development platforms
arduino_core_develop = https://github.com/platformio/platform-espressif8266#develop
arduino_core_git = https://github.com/platformio/platform-espressif8266#feature/stage
# Platform to use for ESP8266
platform_wled_default = ${common.arduino_core_2_7_1}
# We use 2.7.0+ on analog boards because of PWM flicker fix
platform_latest = ${common.arduino_core_2_7_1}
platform_wled_default = ${common.arduino_core_3_1_2}
# We use 2.7.4.7 for all, includes PWM flicker fix and Wstring optimization
#platform_packages = tasmota/framework-arduinoespressif8266 @ 3.20704.7
platform_packages = platformio/framework-arduinoespressif8266
platformio/toolchain-xtensa @ ~2.100300.220621 #2.40802.200502
platformio/tool-esptool #@ ~1.413.0
platformio/tool-esptoolpy #@ ~1.30000.0
## previous platform for 8266, in case of problems with the new one
## you'll need makuna/NeoPixelBus@ 2.6.9 for arduino_core_3_2_0, which does not support Ucs890x
;; platform_wled_default = ${common.arduino_core_3_2_0}
;; platform_packages = tasmota/framework-arduinoespressif8266 @ 3.20704.7
;; platformio/toolchain-xtensa @ ~2.40802.200502
;; platformio/tool-esptool @ ~1.413.0
;; platformio/tool-esptoolpy @ ~1.30000.0
# ------------------------------------------------------------------------------
# FLAGS: DEBUG
@ -87,17 +94,15 @@ debug_flags = -D DEBUG=1 -D WLED_DEBUG -DDEBUG_ESP_WIFI -DDEBUG_ESP_HTTP_CLIENT
#-DDEBUG_ESP_CORE is not working right now
# ------------------------------------------------------------------------------
# FLAGS: ldscript
# ldscript_512k ( 512 KB) = 487 KB sketch, 4 KB eeprom, no spiffs, 16 KB reserved
# ldscript_1m0m (1024 KB) = 999 KB sketch, 4 KB eeprom, no spiffs, 16 KB reserved
# FLAGS: ldscript (available ldscripts at https://github.com/esp8266/Arduino/tree/master/tools/sdk/ld)
# ldscript_2m1m (2048 KB) = 1019 KB sketch, 4 KB eeprom, 1004 KB spiffs, 16 KB reserved
# ldscript_4m1m (4096 KB) = 1019 KB sketch, 4 KB eeprom, 1002 KB spiffs, 16 KB reserved, 2048 KB empty/ota?
# ldscript_4m3m (4096 KB) = 1019 KB sketch, 4 KB eeprom, 3040 KB spiffs, 16 KB reserved
#
# Available lwIP variants (macros):
# -DPIO_FRAMEWORK_ARDUINO_LWIP_HIGHER_BANDWIDTH = v1.4 Higher Bandwidth (default)
# -DPIO_FRAMEWORK_ARDUINO_LWIP2_LOW_MEMORY = v2 Lower Memory
# -DPIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH = v2 Higher Bandwidth
# -DPIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH_LOW_FLASH
#
# BearSSL performance:
# When building with -DSECURE_CLIENT=SECURE_CLIENT_BEARSSL, please add `board_build.f_cpu = 160000000` to the environment configuration
@ -110,8 +115,14 @@ debug_flags = -D DEBUG=1 -D WLED_DEBUG -DDEBUG_ESP_WIFI -DDEBUG_ESP_HTTP_CLIENT
# TLS_RSA_WITH_AES_256_CBC_SHA / AES256-SHA
# This reduces the OTA size with ~45KB, so it's especially useful on low memory boards (512k/1m).
# ------------------------------------------------------------------------------
build_flags = -g -w -DMQTT_MAX_PACKET_SIZE=1024 -DPIO_FRAMEWORK_ARDUINO_LWIP_HIGHER_BANDWIDTH
-DSECURE_CLIENT=SECURE_CLIENT_BEARSSL -DBEARSSL_SSL_BASIC
build_flags =
-Wno-attributes
-DMQTT_MAX_PACKET_SIZE=1024
-DSECURE_CLIENT=SECURE_CLIENT_BEARSSL
-DBEARSSL_SSL_BASIC
-D CORE_DEBUG_LEVEL=0
-D NDEBUG
-Wno-attributes ;; silence warnings about unknown attribute 'maybe_unused' in NeoPixelBus
#build_flags for the IRremoteESP8266 library (enabled decoders have to appear here)
-D _IR_ENABLE_DEFAULT_=false
-D DECODE_HASH=true
@ -119,26 +130,29 @@ build_flags = -g -w -DMQTT_MAX_PACKET_SIZE=1024 -DPIO_FRAMEWORK_ARDUINO_LWIP_HIG
-D DECODE_SONY=true
-D DECODE_SAMSUNG=true
-D DECODE_LG=true
;-Dregister= # remove warnings in C++17 due to use of deprecated register keyword by the FastLED library ;; warning: this breaks framework code on ESP32-C3 and ESP32-S2
-DWLED_USE_MY_CONFIG
; -D USERMOD_SENSORSTOMQTT
#For ADS1115 sensor uncomment following
; -D USERMOD_ADS1115
build_flags_esp8266 = ${common.build_flags} -DESP8266
build_flags_esp32 = ${common.build_flags} -DARDUINO_ARCH_ESP32
build_unflags =
# enables all features for travis CI
build_flags_all_features =
-D WLED_USE_ANALOG_LED
-D WLED_USE_H801
-D WLED_ENABLE_5CH_LEDS
-D WLED_ENABLE_ADALIGHT
-D WLED_ENABLE_DMX
-D WLED_ENABLE_MQTT
build_flags_esp8266 = ${common.build_flags} ${esp8266.build_flags}
build_flags_esp32 = ${common.build_flags} ${esp32.build_flags}
build_flags_esp32_V4= ${common.build_flags} ${esp32_idf_V4.build_flags}
ldscript_512k = eagle.flash.512k.ld ;for older versions change this to eagle.flash.512k0.ld
ldscript_1m0m = eagle.flash.1m.ld ;for older versions change this to eagle.flash.1m0.ld
ldscript_1m128k = eagle.flash.1m128.ld
ldscript_2m512k = eagle.flash.2m512.ld
ldscript_2m1m = eagle.flash.2m1m.ld
ldscript_4m1m = eagle.flash.4m1m.ld
ldscript_4m3m = eagle.flash.4m3m.ld
shared_libdeps_dir = ./wled00/src
[scripts_defaults]
extra_scripts =
pre:pio-scripts/set_version.py
post:pio-scripts/output_bins.py
post:pio-scripts/strip-floats.py
pre:pio-scripts/user_config_copy.py
# ------------------------------------------------------------------------------
# COMMON SETTINGS:
@ -147,36 +161,163 @@ shared_libdeps_dir = ./wled00/src
framework = arduino
board_build.flash_mode = dout
monitor_speed = 115200
# slow upload speed (comment this out with a ';' when building for development use)
upload_speed = 115200
lib_extra_dirs =
${common.shared_libdeps_dir}
# fast upload speed (remove ';' when building for development use)
; upload_speed = 921600
# ------------------------------------------------------------------------------
# LIBRARIES: required dependencies
# Please note that we don't always use the latest version of a library.
#
# The following libraries have been included (and some of them changd) in the source:
# ArduinoJson@5.13.5, Blynk@0.5.4(changed), E131@1.0.0(changed), Time@1.5, Timezone@1.2.1
# The following libraries have been included (and some of them changed) in the source:
# ArduinoJson@5.13.5, E131@1.0.0(changed), Time@1.5, Timezone@1.2.1
# ------------------------------------------------------------------------------
lib_compat_mode = strict
lib_deps =
FastLED@3.3.2
NeoPixelBus@2.5.7
ESPAsyncTCP@1.2.0
ESPAsyncUDP@697c75a025
AsyncTCP@1.0.3
Esp Async WebServer@1.2.0
IRremoteESP8266@2.7.3
fastled/FastLED @ 3.6.0
IRremoteESP8266 @ 2.8.2
makuna/NeoPixelBus @ 2.7.5
https://github.com/Aircoookie/ESPAsyncWebServer.git @ ~2.0.7
#For use of the TTGO T-Display ESP32 Module with integrated TFT display uncomment the following line
#TFT_eSPI
#For use SSD1306 OLED display uncomment following
#U8g2@~2.27.2
#For Dallas sensor uncomment following 2 lines
#OneWire@~2.3.5
#For compatible OLED display uncomment following
#U8g2 #@ ~2.33.15
#For Dallas sensor uncomment following
#OneWire @ ~2.3.7
#For BME280 sensor uncomment following
#BME280@~3.0.0
lib_ignore =
AsyncTCP
#BME280 @ ~3.0.0
; adafruit/Adafruit BMP280 Library @ 2.1.0
; adafruit/Adafruit CCS811 Library @ 1.0.4
; adafruit/Adafruit Si7021 Library @ 1.4.0
#For ADS1115 sensor uncomment following
; adafruit/Adafruit BusIO @ 1.13.2
; adafruit/Adafruit ADS1X15 @ 2.4.0
extra_scripts = ${scripts_defaults.extra_scripts}
[esp8266]
build_flags =
-DESP8266
-DFP_IN_IROM
;-Wno-deprecated-declarations
;-Wno-register ;; leaves some warnings when compiling C files: command-line option '-Wno-register' is valid for C++/ObjC++ but not for C
;-Dregister= # remove warnings in C++17 due to use of deprecated register keyword by the FastLED library ;; warning: this can be dangerous
-Wno-misleading-indentation
; NONOSDK22x_190703 = 2.2.2-dev(38a443e)
-DPIO_FRAMEWORK_ARDUINO_ESPRESSIF_SDK22x_190703
; lwIP 2 - Higher Bandwidth no Features
; -DPIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH_LOW_FLASH
; lwIP 1.4 - Higher Bandwidth (Aircoookie has)
-DPIO_FRAMEWORK_ARDUINO_LWIP_HIGHER_BANDWIDTH
; VTABLES in Flash
-DVTABLES_IN_FLASH
; restrict to minimal mime-types
-DMIMETYPE_MINIMAL
lib_deps =
#https://github.com/lorol/LITTLEFS.git
ESPAsyncTCP @ 1.2.2
ESPAsyncUDP
${env.lib_deps}
[esp32]
#platform = https://github.com/tasmota/platform-espressif32/releases/download/v2.0.2.3/platform-espressif32-2.0.2.3.zip
platform = espressif32@3.5.0
platform_packages = framework-arduinoespressif32 @ https://github.com/Aircoookie/arduino-esp32.git#1.0.6.4
build_flags = -g
-DARDUINO_ARCH_ESP32
#-DCONFIG_LITTLEFS_FOR_IDF_3_2
-D CONFIG_ASYNC_TCP_USE_WDT=0
#use LITTLEFS library by lorol in ESP32 core 1.x.x instead of built-in in 2.x.x
-D LOROL_LITTLEFS
; -DARDUINO_USB_CDC_ON_BOOT=0 ;; this flag is mandatory for "classic ESP32" when building with arduino-esp32 >=2.0.3
default_partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
lib_deps =
https://github.com/lorol/LITTLEFS.git
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
${env.lib_deps}
[esp32_idf_V4]
;; experimental build environment for ESP32 using ESP-IDF 4.4.x / arduino-esp32 v2.0.5
;; very similar to the normal ESP32 flags, but omitting Lorol LittleFS, as littlefs is included in the new framework already.
;;
;; please note that you can NOT update existing ESP32 installs with a "V4" build. Also updating by OTA will not work properly.
;; You need to completely erase your device (esptool erase_flash) first, then install the "V4" build from VSCode+platformio.
platform = espressif32@5.3.0
platform_packages =
build_flags = -g
-Wshadow=compatible-local ;; emit warning in case a local variable "shadows" another local one
-DARDUINO_ARCH_ESP32 -DESP32
#-DCONFIG_LITTLEFS_FOR_IDF_3_2
-D CONFIG_ASYNC_TCP_USE_WDT=0
-DARDUINO_USB_CDC_ON_BOOT=0 ;; this flag is mandatory for "classic ESP32" when building with arduino-esp32 >=2.0.3
default_partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
lib_deps =
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
${env.lib_deps}
[esp32s2]
;; generic definitions for all ESP32-S2 boards
platform = espressif32@5.3.0
platform_packages =
build_flags = -g
-DARDUINO_ARCH_ESP32
-DARDUINO_ARCH_ESP32S2
-DCONFIG_IDF_TARGET_ESP32S2=1
-D CONFIG_ASYNC_TCP_USE_WDT=0
-DARDUINO_USB_MSC_ON_BOOT=0 -DARDUINO_USB_DFU_ON_BOOT=0
-DCO
-DARDUINO_USB_MODE=0 ;; this flag is mandatory for ESP32-S2 !
;; please make sure that the following flags are properly set (to 0 or 1) by your board.json, or included in your custom platformio_override.ini entry:
;; ARDUINO_USB_CDC_ON_BOOT
lib_deps =
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
${env.lib_deps}
[esp32c3]
;; generic definitions for all ESP32-C3 boards
platform = espressif32@5.3.0
platform_packages =
build_flags = -g
-DARDUINO_ARCH_ESP32
-DARDUINO_ARCH_ESP32C3
-DCONFIG_IDF_TARGET_ESP32C3=1
-D CONFIG_ASYNC_TCP_USE_WDT=0
-DCO
-DARDUINO_USB_MODE=1 ;; this flag is mandatory for ESP32-C3
;; please make sure that the following flags are properly set (to 0 or 1) by your board.json, or included in your custom platformio_override.ini entry:
;; ARDUINO_USB_CDC_ON_BOOT
lib_deps =
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
${env.lib_deps}
[esp32s3]
;; generic definitions for all ESP32-S3 boards
platform = espressif32@5.3.0
platform_packages =
build_flags = -g
-DESP32
-DARDUINO_ARCH_ESP32
-DARDUINO_ARCH_ESP32S3
-DCONFIG_IDF_TARGET_ESP32S3=1
-D CONFIG_ASYNC_TCP_USE_WDT=0
-DARDUINO_USB_MSC_ON_BOOT=0 -DARDUINO_DFU_ON_BOOT=0
-DCO
;; please make sure that the following flags are properly set (to 0 or 1) by your board.json, or included in your custom platformio_override.ini entry:
;; ARDUINO_USB_MODE, ARDUINO_USB_CDC_ON_BOOT
lib_deps =
https://github.com/pbolduc/AsyncTCP.git @ 1.2.0
${env.lib_deps}
# ------------------------------------------------------------------------------
# WLED BUILDS
@ -185,84 +326,218 @@ lib_ignore =
[env:nodemcuv2]
board = nodemcuv2
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_flags = ${common.build_flags_esp8266}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 #-DWLED_DISABLE_2D
lib_deps = ${esp8266.lib_deps}
monitor_filters = esp8266_exception_decoder
[env:esp01]
board = esp01
[env:esp8266_2m]
board = esp_wroom_02
platform = ${common.platform_wled_default}
board_build.ldscript = ${common.ldscript_512k}
build_flags = ${common.build_flags_esp8266} -D WLED_DISABLE_OTA -D WLED_DISABLE_ALEXA -D WLED_DISABLE_BLYNK
-D WLED_DISABLE_CRONIXIE -D WLED_DISABLE_HUESYNC -D WLED_DISABLE_INFRARED -D WLED_DISABLE_MQTT
[env:esp01_1m_ota]
board = esp01_1m
platform = ${common.platform_wled_default}
board_build.ldscript = ${common.ldscript_1m0m}
build_flags = ${common.build_flags_esp8266} -D WLED_DISABLE_ALEXA -D WLED_DISABLE_BLYNK -D WLED_DISABLE_CRONIXIE -D WLED_DISABLE_HUESYNC -D WLED_DISABLE_INFRARED -D WLED_DISABLE_MQTT
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_2m512k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP02
lib_deps = ${esp8266.lib_deps}
[env:esp01_1m_full]
board = esp01_1m
platform = ${common.platform_wled_default}
board_build.ldscript = ${common.ldscript_1m0m}
build_flags = ${common.build_flags_esp8266} -D WLED_DISABLE_OTA
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_1m128k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP01 -D WLED_DISABLE_OTA
lib_deps = ${esp8266.lib_deps}
[env:esp07]
board = esp07
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266}
lib_deps = ${esp8266.lib_deps}
[env:d1_mini]
board = d1_mini
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
upload_speed = 921600
board_build.ldscript = ${common.ldscript_4m1m}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266}
lib_deps = ${esp8266.lib_deps}
monitor_filters = esp8266_exception_decoder
[env:heltec_wifi_kit_8]
board = d1_mini
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266}
lib_deps = ${esp8266.lib_deps}
[env:h803wf]
board = d1_mini
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D LEDPIN=1 -D WLED_DISABLE_INFRARED
lib_deps = ${esp8266.lib_deps}
[env:esp32dev]
board = esp32dev
platform = espressif32@1.11.2
build_flags = ${common.build_flags_esp32}
lib_ignore =
ESPAsyncTCP
ESPAsyncUDP
platform = ${esp32.platform}
platform_packages = ${esp32.platform_packages}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32 #-D WLED_DISABLE_BROWNOUT_DET
lib_deps = ${esp32.lib_deps}
monitor_filters = esp32_exception_decoder
board_build.partitions = ${esp32.default_partitions}
[env:esp32dev_qio80]
board = esp32dev
platform = ${esp32.platform}
platform_packages = ${esp32.platform_packages}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32_qio80 #-D WLED_DISABLE_BROWNOUT_DET
lib_deps = ${esp32.lib_deps}
monitor_filters = esp32_exception_decoder
board_build.partitions = ${esp32.default_partitions}
board_build.f_flash = 80000000L
board_build.flash_mode = qio
[env:esp32dev_V4_dio80]
;; experimental ESP32 env using ESP-IDF V4.4.x
;; Warning: this build environment is not stable!!
;; please erase your device before installing.
board = esp32dev
platform = ${esp32_idf_V4.platform}
platform_packages = ${esp32_idf_V4.platform_packages}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp32_idf_V4.build_flags} -D WLED_RELEASE_NAME=ESP32_V4_qio80 #-D WLED_DISABLE_BROWNOUT_DET
lib_deps = ${esp32_idf_V4.lib_deps}
monitor_filters = esp32_exception_decoder
board_build.partitions = ${esp32_idf_V4.default_partitions}
board_build.f_flash = 80000000L
board_build.flash_mode = dio
[env:esp32_eth]
board = esp32-poe
platform = ${esp32.platform}
platform_packages = ${esp32.platform_packages}
upload_speed = 921600
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32_Ethernet -D RLYPIN=-1 -D WLED_USE_ETHERNET -D BTNPIN=-1
lib_deps = ${esp32.lib_deps}
board_build.partitions = ${esp32.default_partitions}
[env:esp32s2_saola]
board = esp32-s2-saola-1
platform = https://github.com/tasmota/platform-espressif32/releases/download/v2.0.2.2/platform-tasmota-espressif32-2.0.2.zip
platform_packages =
framework = arduino
board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
board_build.flash_mode = qio
upload_speed = 460800
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp32s2.build_flags} #-D WLED_RELEASE_NAME=S2_saola
;-DLOLIN_WIFI_FIX ;; try this in case Wifi does not work
-DARDUINO_USB_CDC_ON_BOOT=1
lib_deps = ${esp32s2.lib_deps}
[env:esp32c3dev]
extends = esp32c3
platform = ${esp32c3.platform}
platform_packages = ${esp32c3.platform_packages}
framework = arduino
board = esp32-c3-devkitm-1
board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
build_flags = ${common.build_flags} ${esp32c3.build_flags} #-D WLED_RELEASE_NAME=ESP32-C3
-D WLED_WATCHDOG_TIMEOUT=0
-DLOLIN_WIFI_FIX ; seems to work much better with this
-DARDUINO_USB_CDC_ON_BOOT=1 ;; for virtual CDC USB
;-DARDUINO_USB_CDC_ON_BOOT=0 ;; for serial-to-USB chip
upload_speed = 460800
build_unflags = ${common.build_unflags}
lib_deps = ${esp32c3.lib_deps}
[env:esp32s3dev_8MB]
;; ESP32-S3-DevKitC-1 development board, with 8MB FLASH, no PSRAM (flash_mode: qio)
board = esp32-s3-devkitc-1
platform = ${esp32s3.platform}
platform_packages = ${esp32s3.platform_packages}
upload_speed = 921600 ; or 460800
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp32s3.build_flags}
-D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0
-D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip
;-D ARDUINO_USB_CDC_ON_BOOT=1 ;; -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
;-D WLED_DEBUG
lib_deps = ${esp32s3.lib_deps}
board_build.partitions = tools/WLED_ESP32_8MB.csv
board_build.f_flash = 80000000L
board_build.flash_mode = qio
; board_build.flash_mode = dio ;; try this if you have problems at startup
monitor_filters = esp32_exception_decoder
[env:esp32s3dev_8MB_PSRAM_opi]
;; ESP32-S3 development board, with 8MB FLASH and >= 8MB PSRAM (memory_type: qio_opi)
board = esp32-s3-devkitc-1 ;; generic dev board; the next line adds PSRAM support
board_build.arduino.memory_type = qio_opi ;; use with PSRAM: 8MB or 16MB
platform = ${esp32s3.platform}
platform_packages = ${esp32s3.platform_packages}
upload_speed = 921600
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags} ${esp32s3.build_flags}
-D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0
;-D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip
-D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
; -D WLED_RELEASE_NAME=ESP32-S3_PSRAM
-D WLED_USE_PSRAM -DBOARD_HAS_PSRAM ; tells WLED that PSRAM shall be used
lib_deps = ${esp32s3.lib_deps}
board_build.partitions = tools/WLED_ESP32_8MB.csv
board_build.f_flash = 80000000L
board_build.flash_mode = qio
monitor_filters = esp32_exception_decoder
[env:esp32s3dev_8MB_PSRAM_qspi]
;; ESP32-TinyS3 development board, with 8MB FLASH and PSRAM (memory_type: qio_qspi)
extends = env:esp32s3dev_8MB_PSRAM_opi
;board = um_tinys3 ; -> needs workaround from https://github.com/Aircoookie/WLED/pull/2905#issuecomment-1328049860
board = esp32-s3-devkitc-1 ;; generic dev board; the next line adds PSRAM support
board_build.arduino.memory_type = qio_qspi ;; use with PSRAM: 2MB or 4MB
[env:esp8285_4CH_MagicHome]
board = esp8285
platform = ${common.platform_latest}
board_build.ldscript = ${common.ldscript_1m0m}
build_flags = ${common.build_flags_esp8266} -D WLED_DISABLE_HUESYNC -D WLED_USE_ANALOG_LEDS
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_1m128k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_DISABLE_OTA
lib_deps = ${esp8266.lib_deps}
[env:esp8285_4CH_H801]
[env:esp8285_H801]
board = esp8285
platform = ${common.platform_latest}
board_build.ldscript = ${common.ldscript_1m0m}
build_flags = ${common.build_flags_esp8266} -D WLED_DISABLE_HUESYNC -D WLED_USE_ANALOG_LEDS -D WLED_USE_H801
[env:esp8285_5CH_H801]
board = esp8285
platform = ${common.platform_latest}
board_build.ldscript = ${common.ldscript_1m0m}
build_flags = ${common.build_flags_esp8266} -D WLED_DISABLE_HUESYNC -D WLED_USE_ANALOG_LEDS -D WLED_USE_H801 -D WLED_ENABLE_5CH_LEDS
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_1m128k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_DISABLE_OTA
lib_deps = ${esp8266.lib_deps}
[env:d1_mini_5CH_Shojo_PCB]
board = d1_mini
platform = ${common.platform_latest}
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_flags = ${common.build_flags_esp8266} -D WLED_USE_ANALOG_LEDS -D WLED_USE_SHOJO_PCB -D WLED_ENABLE_5CH_LEDS
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_USE_SHOJO_PCB
lib_deps = ${esp8266.lib_deps}
# ------------------------------------------------------------------------------
# DEVELOPMENT BOARDS
@ -272,8 +547,11 @@ build_flags = ${common.build_flags_esp8266} -D WLED_USE_ANALOG_LEDS -D WLED_USE_
board = d1_mini
build_type = debug
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} ${common.debug_flags}
lib_deps = ${esp8266.lib_deps}
[env:d1_mini_ota]
board = d1_mini
@ -281,74 +559,229 @@ upload_protocol = espota
# exchange for your WLED IP
upload_port = "10.10.1.27"
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266}
lib_deps = ${esp8266.lib_deps}
[env:anavi_miracle_controller]
board = d1_mini
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D LEDPIN=12 -D IRPIN=-1 -D RLYPIN=2
lib_deps = ${esp8266.lib_deps}
[env:lolin_s2_mini]
platform = ${esp32s2.platform}
platform_packages = ${esp32s2.platform_packages}
board = lolin_s2_mini
board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv
build_unflags = ${common.build_unflags} #-DARDUINO_USB_CDC_ON_BOOT=1
build_flags = ${common.build_flags} ${esp32s2.build_flags} #-D WLED_RELEASE_NAME=LolinS2
-DBOARD_HAS_PSRAM
-DARDUINO_USB_CDC_ON_BOOT=1 # try disabling and enabling unflag above in case of board-specific issues, will disable Serial
-DARDUINO_USB_MSC_ON_BOOT=0
-DARDUINO_USB_DFU_ON_BOOT=0
-DLOLIN_WIFI_FIX ; seems to work much better with this
-D WLED_USE_PSRAM
-D WLED_WATCHDOG_TIMEOUT=0
-D CONFIG_ASYNC_TCP_USE_WDT=0
-D LEDPIN=16
-D BTNPIN=18
-D RLYPIN=9
-D IRPIN=7
-D HW_PIN_SCL=35
-D HW_PIN_SDA=33
-D HW_PIN_CLOCKSPI=7
-D HW_PIN_DATASPI=11
-D HW_PIN_MISOSPI=9
; -D STATUSLED=15
lib_deps = ${esp32s2.lib_deps}
# ------------------------------------------------------------------------------
# custom board configurations
# ------------------------------------------------------------------------------
[env:custom_LEDPIN_4]
board = d1_mini
platform = ${common.platform_latest}
board_build.ldscript = ${common.ldscript_4m1m}
build_flags = ${common.build_flags_esp8266} -D LEDPIN=4 -D IRPIN=5
[env:custom_LEDPIN_16]
board = d1_mini
platform = ${common.platform_latest}
board_build.ldscript = ${common.ldscript_4m1m}
build_flags = ${common.build_flags_esp8266} -D LEDPIN=16
[env:custom_APA102]
board = d1_mini
platform = ${common.platform_latest}
board_build.ldscript = ${common.ldscript_4m1m}
build_flags = ${common.build_flags_esp8266} -D USE_APA102
[env:custom_WS2801]
board = d1_mini
platform = ${common.platform_latest}
board_build.ldscript = ${common.ldscript_4m1m}
build_flags = ${common.build_flags_esp8266} -D USE_WS2801
[env:custom32_LEDPIN_16]
board = esp32dev
platform = espressif32@1.11.2
build_flags = ${common.build_flags_esp32} -D LEDPIN=16
lib_ignore =
ESPAsyncTCP
ESPAsyncUDP
[env:esp32c3dev_2MB]
;; for ESP32-C3 boards with 2MB flash (instead of 4MB).
;; this board need a specific partition file. OTA not possible.
extends = esp32c3
platform = ${esp32c3.platform}
platform_packages = ${esp32c3.platform_packages}
board = esp32-c3-devkitm-1
build_flags = ${common.build_flags} ${esp32c3.build_flags} #-D WLED_RELEASE_NAME=ESP32-C3
-D WLED_WATCHDOG_TIMEOUT=0
-D WLED_DISABLE_OTA
; -DARDUINO_USB_CDC_ON_BOOT=1 ;; for virtual CDC USB
-DARDUINO_USB_CDC_ON_BOOT=0 ;; for serial-to-USB chip
build_unflags = ${common.build_unflags}
upload_speed = 115200
lib_deps = ${esp32c3.lib_deps}
board_build.partitions = tools/WLED_ESP32_2MB_noOTA.csv
board_build.flash_mode = dio
[env:wemos_shield_esp32]
board = esp32dev
platform = espressif32@1.11.2
upload_port = /dev/cu.SLAB_USBtoUART
monitor_port = /dev/cu.SLAB_USBtoUART
platform = ${esp32.platform}
platform_packages = ${esp32.platform_packages}
upload_speed = 460800
build_flags = ${common.build_flags_esp32} -D LEDPIN=16 -D RLYPIN=19 -D BTNPIN=17
lib_ignore =
ESPAsyncTCP
ESPAsyncUDP
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp32}
-D LEDPIN=16
-D RLYPIN=19
-D BTNPIN=17
-D IRPIN=18
-D UWLED_USE_MY_CONFIG
-D USERMOD_DALLASTEMPERATURE
-D USERMOD_FOUR_LINE_DISPLAY
-D TEMPERATURE_PIN=23
-D USE_ALT_DISPlAY ; new versions of USERMOD_FOUR_LINE_DISPLAY and USERMOD_ROTARY_ENCODER_UI
-D USERMOD_AUDIOREACTIVE
lib_deps = ${esp32.lib_deps}
OneWire@~2.3.5
olikraus/U8g2 @ ^2.28.8
https://github.com/blazoncek/arduinoFFT.git
board_build.partitions = ${esp32.default_partitions}
[env:m5atom]
board = esp32dev
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp32} -D LEDPIN=27 -D BTNPIN=39
lib_ignore =
ESPAsyncTCP
ESPAsyncUDP
platform = espressif32@1.11.2
lib_deps = ${esp32.lib_deps}
platform = ${esp32.platform}
platform_packages = ${esp32.platform_packages}
board_build.partitions = ${esp32.default_partitions}
[env:sp501e]
board = esp_wroom_02
platform = ${common.platform_wled_default}
board_build.ldscript = ${common.ldscript_2m512k}
build_flags = ${common.build_flags_esp8266} -D LEDPIN=3 -D BTNPIN=1
lib_deps = ${esp8266.lib_deps}
[env:sp511e]
board = esp_wroom_02
platform = ${common.platform_wled_default}
board_build.ldscript = ${common.ldscript_2m512k}
build_flags = ${common.build_flags_esp8266} -D LEDPIN=3 -D BTNPIN=2 -D IRPIN=5 -D WLED_MAX_BUTTONS=3
lib_deps = ${esp8266.lib_deps}
[env:Athom_RGBCW] ;7w and 5w(GU10) bulbs
board = esp8285
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_2m512k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=-1 -D RLYPIN=-1 -D DATA_PINS=4,12,14,13,5
-D DEFAULT_LED_TYPE=TYPE_ANALOG_5CH -D WLED_DISABLE_INFRARED -D WLED_MAX_CCT_BLEND=0
lib_deps = ${esp8266.lib_deps}
[env:Athom_15w_RGBCW] ;15w bulb
board = esp8285
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_2m512k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=-1 -D RLYPIN=-1 -D DATA_PINS=4,12,14,5,13
-D DEFAULT_LED_TYPE=TYPE_ANALOG_5CH -D WLED_DISABLE_INFRARED -D WLED_MAX_CCT_BLEND=0 -D WLED_USE_IC_CCT
lib_deps = ${esp8266.lib_deps}
[env:Athom_3Pin_Controller] ;small controller with only data
board = esp8285
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_2m512k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=0 -D RLYPIN=-1 -D LEDPIN=1 -D WLED_DISABLE_INFRARED
lib_deps = ${esp8266.lib_deps}
[env:Athom_4Pin_Controller] ; With clock and data interface
board = esp8285
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_2m512k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=0 -D RLYPIN=12 -D LEDPIN=1 -D WLED_DISABLE_INFRARED
lib_deps = ${esp8266.lib_deps}
[env:Athom_5Pin_Controller] ;Analog light strip controller
board = esp8285
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_2m512k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=0 -D RLYPIN=-1 DATA_PINS=4,12,14,13 -D WLED_DISABLE_INFRARED
lib_deps = ${esp8266.lib_deps}
[env:MY9291]
board = esp01_1m
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_1m128k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP01 -D WLED_DISABLE_OTA -D USERMOD_MY9291
lib_deps = ${esp8266.lib_deps}
# ------------------------------------------------------------------------------
# travis test board configurations
# codm pixel controller board configurations
# codm-controller-0_6 can also be used for the TYWE3S controller
# ------------------------------------------------------------------------------
[env:travis_esp8266]
extends = env:d1_mini
build_type = debug
build_flags = ${common.build_flags_esp8266} ${common.debug_flags} ${common.build_flags_all_features}
[env:codm-controller-0_6]
board = esp_wroom_02
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_2m512k}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266}
lib_deps = ${esp8266.lib_deps}
[env:travis_esp32]
extends = env:esp32dev
build_type = debug
build_flags = ${common.build_flags_esp32} ${common.debug_flags} ${common.build_flags_all_features}
[env:codm-controller-0_6-rev2]
board = esp_wroom_02
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_4m1m}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266}
lib_deps = ${esp8266.lib_deps}
# ------------------------------------------------------------------------------
# EleksTube-IPS
# ------------------------------------------------------------------------------
[env:elekstube_ips]
board = esp32dev
platform = ${esp32.platform}
platform_packages = ${esp32.platform_packages}
upload_speed = 921600
build_flags = ${common.build_flags_esp32} -D WLED_DISABLE_BROWNOUT_DET -D WLED_DISABLE_INFRARED
-D USERMOD_RTC
-D USERMOD_ELEKSTUBE_IPS
-D LEDPIN=12
-D RLYPIN=27
-D BTNPIN=34
-D DEFAULT_LED_COUNT=6
# Display config
-D ST7789_DRIVER
-D TFT_WIDTH=135
-D TFT_HEIGHT=240
-D CGRAM_OFFSET
-D TFT_SDA_READ
-D TFT_MOSI=23
-D TFT_SCLK=18
-D TFT_DC=25
-D TFT_RST=26
-D SPI_FREQUENCY=40000000
-D USER_SETUP_LOADED
monitor_filters = esp32_exception_decoder
lib_deps =
${esp32.lib_deps}
TFT_eSPI @ ^2.3.70
board_build.partitions = ${esp32.default_partitions}

View File

@ -1,36 +0,0 @@
# Example PlatformIO Project Configuration Override
# ------------------------------------------------------------------------------
# Copy to platformio_override.ini to activate overrides
# ------------------------------------------------------------------------------
# Please visit documentation: https://docs.platformio.org/page/projectconf.html
[env:esp8266_1m_custom]
board = esp01_1m
platform = ${common.arduino_core_2_4_2}
board_build.ldscript = ${common.ldscript_1m0m}
build_flags = ${common.build_flags_esp8266}
-D WLED_DISABLE_OTA
-D WLED_DISABLE_ALEXA
-D WLED_DISABLE_BLYNK
-D WLED_DISABLE_CRONIXIE
-D WLED_DISABLE_HUESYNC
-D WLED_DISABLE_INFRARED
; PIN defines - uncomment and change, if needed:
; -D LEDPIN=2
; -D BTNPIN=0
; -D IR_PIN=4
; -D RLYPIN=12
; -D RLYMDE=1
; digital LED strip types - uncomment only one ! - this will disable WS281x / SK681x support
; -D USE_APA102
; -D USE_WS2801
; -D USE_LPD8806
; to drive analog LED strips (aka 5050), uncomment the following
; PWM pins 5,12,13,15 are used with Magic Home LED Controller (default)
; -D WLED_USE_ANALOG_LEDS
; for the H801 controller (PINs 15,13,12,14 (W2 = 04)) uncomment this
; -D WLED_USE_H801
; for the BW-LT11 controller (PINs 12,4,14,5 ) uncomment this
; -D WLED_USE_BWLT11
; and to enable channel 5 for RGBW-CT led strips this
; -D WLED_USE_5CH_LEDS

View File

@ -0,0 +1,65 @@
# Example PlatformIO Project Configuration Override
# ------------------------------------------------------------------------------
# Copy to platformio_override.ini to activate overrides
# ------------------------------------------------------------------------------
# Please visit documentation: https://docs.platformio.org/page/projectconf.html
[platformio]
default_envs = WLED_tasmota_1M
[env:WLED_tasmota_1M]
board = esp01_1m
platform = ${common.platform_wled_default}
platform_packages = ${common.platform_packages}
board_build.ldscript = ${common.ldscript_1m128k}
lib_deps = ${esp8266.lib_deps}
build_unflags = ${common.build_unflags}
build_flags = ${common.build_flags_esp8266}
; *********************************************************************
; *** Use custom settings from file my_config.h
-DWLED_USE_MY_CONFIG
; *********************************************************************
;
;
; *** To use the below defines/overrides, copy and paste each onto it's own line just below build_flags in the section above.
;
; disable specific features
; -D WLED_DISABLE_OTA
; -D WLED_DISABLE_ALEXA
; -D WLED_DISABLE_HUESYNC
; -D WLED_DISABLE_INFRARED
; -D WLED_DISABLE_WEBSOCKETS
; PIN defines - uncomment and change, if needed:
; -D LEDPIN=2
; -D BTNPIN=0
; -D TOUCHPIN=T0
; -D IRPIN=4
; -D RLYPIN=12
; -D RLYMDE=1
; digital LED strip types - uncomment only one ! - this will disable WS281x / SK681x support
; -D USE_APA102
; -D USE_WS2801
; -D USE_LPD8806
; PIN defines for 2 wire LEDs
-D CLKPIN=0
-D DATAPIN=2
; to drive analog LED strips (aka 5050) hardware configuration is no longer necessary
; configure the settings in the UI as follows (hard):
; for the Magic Home LED Controller use PWM pins 5,12,13,15
; for the H801 controller use PINs 15,13,12,14 (W2 = 04)
; for the BW-LT11 controller use PINs 12,4,14,5
;
; set the name of the module - make sure there is a quote-backslash-quote before the name and a backslash-quote-quote after the name
; -D SERVERNAME="\"WLED\""
;
; set the number of LEDs
; -D DEFAULT_LED_COUNT=30
;
; set milliampere limit when using ESP pin to power leds
; -D ABL_MILLIAMPS_DEFAULT=850
;
; enable IR by setting remote type
; -D IRTYPE=0 ;0 Remote disabled | 1 24-key RGB | 2 24-key with CT | 3 40-key blue | 4 40-key RGB | 5 21-key RGB | 6 6-key black | 7 9-key red | 8 JSON remote
;
; set default color order of your led strip
; -D DEFAULT_LED_COLOR_ORDER=COL_ORDER_GRB

View File

@ -1,95 +1,84 @@
<p align="center">
<img src="/images/wled_logo.png">
<img src="/images/wled_logo_akemi.png">
<a href="https://github.com/Aircoookie/WLED/releases"><img src="https://img.shields.io/github/release/Aircoookie/WLED.svg?style=flat-square"></a>
<a href="https://raw.githubusercontent.com/Aircoookie/WLED/master/LICENSE"><img src="https://img.shields.io/github/license/Aircoookie/wled?color=blue&style=flat-square"></a>
<a href="https://wled.discourse.group"><img src="https://img.shields.io/discourse/topics?colorB=blue&label=forum&server=https%3A%2F%2Fwled.discourse.group%2F&style=flat-square"></a>
<a href="https://discord.gg/KuqP7NE"><img src="https://img.shields.io/discord/473448917040758787.svg?colorB=blue&label=discord&style=flat-square"></a>
<a href="https://github.com/Aircoookie/WLED/wiki"><img src="https://img.shields.io/badge/quick_start-wiki-blue.svg?style=flat-square"></a>
<a href="https://kno.wled.ge"><img src="https://img.shields.io/badge/quick_start-wiki-blue.svg?style=flat-square"></a>
<a href="https://github.com/Aircoookie/WLED-App"><img src="https://img.shields.io/badge/app-wled-blue.svg?style=flat-square"></a>
<a href="https://gitpod.io/#https://github.com/Aircoookie/WLED"><img src="https://img.shields.io/badge/Gitpod-ready--to--code-blue?style=flat-square&logo=gitpod"></a>
</p>
# Welcome to my project WLED! ✨
A fast and feature-rich implementation of an ESP8266/ESP32 webserver to control NeoPixel (WS2812B, WS2811, SK6812, APA102) LEDs or also SPI based chipsets like the WS2801!
A fast and feature-rich implementation of an ESP8266/ESP32 webserver to control NeoPixel (WS2812B, WS2811, SK6812) LEDs or also SPI based chipsets like the WS2801 and APA102!
## ⚙️ Features
- WS2812FX library integrated for over 100 special effects
- WS2812FX library with more than 100 special effects
- FastLED noise effects and 50 palettes
- Modern UI with color, effect and segment controls
- Segments to set different effects and colors to parts of the LEDs
- Settings page - configuration over network
- Segments to set different effects and colors to user defined parts of the LED string
- Settings page - configuration via the network
- Access Point and station mode - automatic failsafe AP
- Up to 10 LED outputs per instance
- Support for RGBW strips
- 16 user presets to save and load colors/effects easily, supports cycling through them.
- Macro functions to automatically execute API calls
- Up to 250 user presets to save and load colors/effects easily, supports cycling through them.
- Presets can be used to automatically execute API calls
- Nightlight function (gradually dims down)
- Full OTA software updatability (HTTP + ArduinoOTA), password protectable
- Configurable analog clock + support for the Cronixie kit by Diamex
- Configurable Auto Brightness limit for safer operation
- Configurable analog clock (Cronixie, 7-segment and EleksTube IPS clock support via usermods)
- Configurable Auto Brightness limit for safe operation
- Filesystem-based config for easier backup of presets and settings
## 💡 Supported light control interfaces
- WLED app for Android and iOS
- WLED app for [Android](https://play.google.com/store/apps/details?id=com.aircoookie.WLED) and [iOS](https://apps.apple.com/us/app/wled/id1475695033)
- JSON and HTTP request APIs
- MQTT
- Blynk IoT
- E1.31
- Hyperion
- E1.31, Art-Net, DDP and TPM2.net
- [diyHue](https://github.com/diyhue/diyHue) (Wled is supported by diyHue, including Hue Sync Entertainment under udp. Thanks to [Gregory Mallios](https://github.com/gmallios))
- [Hyperion](https://github.com/hyperion-project/hyperion.ng)
- UDP realtime
- Alexa voice control (including dimming and color)
- Sync to Philips hue lights
- Adalight (PC ambilight via serial)
- Adalight (PC ambilight via serial) and TPM2
- Sync color of multiple WLED devices (UDP notifier)
- Infrared remotes (24-key RGB, receiver required)
- Simple timers/schedules (time from NTP, timezones/DST supported)
## 📲 Quick start guide and documentation
See the [wiki](https://github.com/Aircoookie/WLED/wiki)!
See the [documentation on our official site](https://kno.wled.ge)!
DrZzs has made some excellent video guides:
[Introduction, hardware and installation](https://www.youtube.com/watch?v=tXvtxwK3jRk)
[Settings, tips and tricks](https://www.youtube.com/watch?v=6eCE2BpLaUQ)
[On this page](https://kno.wled.ge/basics/tutorials/) you can find excellent tutorials and tools to help you get your new project up and running!
If you'd rather read, here is a very [detailed step-by-step beginner tutorial](https://tynick.com/blog/11-03-2019/getting-started-with-wled-on-esp8266/) by tynick!
Russian speakers, check out the videos by Room31:
[WLED Firmware Overview: Interface and Settings](https://youtu.be/h7lKsczEI7E)
[ESP8266 based LED controller for WS2812b strip. WLED Firmware + OpenHAB](https://youtu.be/K4ioTt3XvGc)
## 🖼️ Images
## 🖼️ User interface
<img src="/images/macbook-pro-space-gray-on-the-wooden-table.jpg" width="50%"><img src="/images/walking-with-iphone-x.jpg" width="50%">
## 💾 Compatible LED Strips
Type | Voltage | Comments
|---|---|---|
WS2812B | 5v |
WS2813 | 5v |
SK6812 | 5v | RGBW
APA102 | 5v | C/D
WS2801 | 5v | C/D
LPD8806 | 5v | C/D
TM1814 | 12v | RGBW
WS2811 | 12v | 3-LED segments
WS2815 | 12v |
GS8208 | 12v |
## 💾 Compatible hardware
See [here](https://kno.wled.ge/basics/compatible-hardware)!
## ✌️ Other
Licensed under the MIT license
Credits [here](https://github.com/Aircoookie/WLED/wiki/Contributors-&-About)!
Uses Linearicons by Perxis!
Credits [here](https://kno.wled.ge/about/contributors/)!
Join the Discord server to discuss everything about WLED!
<a href="https://discord.gg/KuqP7NE"><img src="https://discordapp.com/api/guilds/473448917040758787/widget.png?style=banner2" width="25%"></a>
Check out the WLED [Discourse forum](https://wled.discourse.group)!
You can also send me mails to [dev.aircoookie@gmail.com](mailto:dev.aircoookie@gmail.com), but please only do so if you want to talk to me privately.
If WLED really brightens up your every day, you can [![](https://img.shields.io/badge/send%20me%20a%20small%20gift-paypal-blue.svg?style=flat-square)](https://paypal.me/aircoookie)
You can also send me mails to [dev.aircoookie@gmail.com](mailto:dev.aircoookie@gmail.com), but please, only do so if you want to talk to me privately.
If WLED really brightens up your day, you can [![](https://img.shields.io/badge/send%20me%20a%20small%20gift-paypal-blue.svg?style=flat-square)](https://paypal.me/aircoookie)
*Disclaimer:*
If you are sensitive to photoeleptic seizures it is not recommended that you use this software.
In case you still want to try, don't use strobe, lighting or noise modes or high effect speed settings.
As per the MIT license, i assume no liability for any damage to you or any other person or equipment.
If you are prone to photosensitive epilepsy, we recommended you do **not** use this software.
If you still want to try, don't use strobe, lighting or noise modes or high effect speed settings.
As per the MIT license, I assume no liability for any damage to you or any other person or equipment.

1
requirements.in Normal file
View File

@ -0,0 +1 @@
platformio

58
requirements.txt Normal file
View File

@ -0,0 +1,58 @@
#
# This file is autogenerated by pip-compile with python 3.8
# To update, run:
#
# pip-compile
#
aiofiles==22.1.0
# via platformio
ajsonrpc==1.2.0
# via platformio
anyio==3.6.2
# via starlette
bottle==0.12.25
# via platformio
certifi==2023.7.22
# via requests
charset-normalizer==3.1.0
# via requests
click==8.1.3
# via
# platformio
# uvicorn
colorama==0.4.6
# via platformio
h11==0.14.0
# via
# uvicorn
# wsproto
idna==3.4
# via
# anyio
# requests
marshmallow==3.19.0
# via platformio
packaging==23.1
# via marshmallow
platformio==6.1.6
# via -r requirements.in
pyelftools==0.29
# via platformio
pyserial==3.5
# via platformio
requests==2.31.0
# via platformio
semantic-version==2.10.0
# via platformio
sniffio==1.3.0
# via anyio
starlette==0.23.1
# via platformio
tabulate==0.9.0
# via platformio
urllib3==1.26.15
# via requests
uvicorn==0.20.0
# via platformio
wsproto==1.2.0
# via platformio

View File

@ -0,0 +1,6 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x180000,
app1, app, ota_1, 0x190000,0x180000,
spiffs, data, spiffs, 0x310000,0xF0000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xe000 0x2000
4 app0 app ota_0 0x10000 0x180000
5 app1 app ota_1 0x190000 0x180000
6 spiffs data spiffs 0x310000 0xF0000

View File

@ -0,0 +1,6 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x200000,
app1, app, ota_1, 0x210000,0x200000,
spiffs, data, spiffs, 0x410000,0xBE0000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xe000 0x2000
4 app0 app ota_0 0x10000 0x200000
5 app1 app ota_1 0x210000 0x200000
6 spiffs data spiffs 0x410000 0xBE0000

View File

@ -0,0 +1,8 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x300000,
app1, app, ota_1, 0x310000,0x300000,
spiffs, data, spiffs, 0x610000,0x9E0000,
coredump, data, coredump,,64K
# to create/use ffat, see https://github.com/marcmerlin/esp32_fatfsimage
1 # Name, Type, SubType, Offset, Size, Flags
2 nvs, data, nvs, 0x9000, 0x5000,
3 otadata, data, ota, 0xe000, 0x2000,
4 app0, app, ota_0, 0x10000, 0x300000,
5 app1, app, ota_1, 0x310000,0x300000,
6 spiffs, data, spiffs, 0x610000,0x9E0000,
7 coredump, data, coredump,,64K
8 # to create/use ffat, see https://github.com/marcmerlin/esp32_fatfsimage

View File

@ -0,0 +1,5 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 20K,
otadata, data, ota, 0xe000, 8K,
app0, app, ota_0, 0x10000, 1536K,
spiffs, data, spiffs, 0x190000, 384K,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 20K
3 otadata data ota 0xe000 8K
4 app0 app ota_0 0x10000 1536K
5 spiffs data spiffs 0x190000 384K

View File

@ -0,0 +1,6 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x180000,
app1, app, ota_1, 0x190000,0x180000,
spiffs, data, spiffs, 0x310000,0xF0000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xe000 0x2000
4 app0 app ota_0 0x10000 0x180000
5 app1 app ota_1 0x190000 0x180000
6 spiffs data spiffs 0x310000 0xF0000

7
tools/WLED_ESP32_8MB.csv Normal file
View File

@ -0,0 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x200000,
app1, app, ota_1, 0x210000,0x200000,
spiffs, data, spiffs, 0x410000,0x3E0000,
coredump, data, coredump,,64K
1 # Name, Type, SubType, Offset, Size, Flags
2 nvs, data, nvs, 0x9000, 0x5000,
3 otadata, data, ota, 0xe000, 0x2000,
4 app0, app, ota_0, 0x10000, 0x200000,
5 app1, app, ota_1, 0x210000,0x200000,
6 spiffs, data, spiffs, 0x410000,0x3E0000,
7 coredump, data, coredump,,64K

View File

@ -16,21 +16,32 @@
*/
const fs = require("fs");
const inliner = require("inliner");
const zlib = require("zlib");
const CleanCSS = require("clean-css");
const MinifyHTML = require("html-minifier-terser").minify;
const packageJson = require("../package.json");
/**
*
*/
function hexdump(buffer) {
function hexdump(buffer,isHex=false) {
let lines = [];
for (let i = 0; i < buffer.length; i += 16) {
let block = buffer.slice(i, i + 16); // cut buffer into blocks of 16
for (let i = 0; i < buffer.length; i +=(isHex?32:16)) {
var block;
let hexArray = [];
if (isHex) {
block = buffer.slice(i, i + 32)
for (let j = 0; j < block.length; j +=2 ) {
hexArray.push("0x" + block.slice(j,j+2))
}
} else {
block = buffer.slice(i, i + 16); // cut buffer into blocks of 16
for (let value of block) {
hexArray.push("0x" + value.toString(16).padStart(2, "0"));
}
}
let hexString = hexArray.join(", ");
let line = ` ${hexString}`;
@ -40,9 +51,6 @@ function hexdump(buffer) {
return lines.join(",\n");
}
const inliner = require("inliner");
const zlib = require("zlib");
function strReplace(str, search, replacement) {
return str.split(search).join(replacement);
}
@ -56,64 +64,26 @@ function adoptVersionAndRepo(html) {
html = strReplace(html, "https://github.com/atuline/WLED", repoUrl);
html = strReplace(html, "https://github.com/Aircoookie/WLED", repoUrl);
}
let version = packageJson.version;
if (version) {
html = strReplace(html, "##VERSION##", version);
}
return html;
}
function writeHtmlGzipped(sourceFile, resultFile) {
console.info("Reading " + sourceFile);
new inliner(sourceFile, function (error, html) {
console.info("Inlined " + html.length + " characters");
if (error) {
console.warn(error);
throw error;
}
html = adoptVersionAndRepo(html);
zlib.gzip(html, function (error, result) {
if (error) {
console.warn(error);
throw error;
}
console.info("Compressed " + result.length + " bytes");
const array = hexdump(result);
const src = `/*
* Binary array for the Web UI.
* gzip is used for smaller size and improved speeds.
*
* Please see https://github.com/Aircoookie/WLED/wiki/Add-own-functionality#web-ui
* to find out how to easily modify the web UI source!
*/
// Autogenerated from ${sourceFile}, do not edit!!
const uint16_t PAGE_index_L = ${result.length};
const uint8_t PAGE_index[] PROGMEM = {
${array}
};
`;
console.info("Writing " + resultFile);
fs.writeFileSync(resultFile, src);
});
});
}
const CleanCSS = require("clean-css");
const MinifyHTML = require("html-minifier").minify;
function filter(str, type) {
str = adoptVersionAndRepo(str);
if (type === undefined) {
return str;
} else if (type == "css-minify") {
return new CleanCSS({}).minify(str).styles;
} else if (type == "js-minify") {
return MinifyHTML('<script>' + str + '</script>', {
collapseWhitespace: true,
minifyJS: true,
continueOnParseError: false,
removeComments: true,
}).replace(/<[\/]*script>/g,'');
} else if (type == "html-minify") {
return MinifyHTML(str, {
collapseWhitespace: true,
@ -123,16 +93,67 @@ function filter(str, type) {
continueOnParseError: false,
removeComments: true,
});
} else if (type == "html-minify-ui") {
return MinifyHTML(str, {
collapseWhitespace: true,
conservativeCollapse: true,
maxLineLength: 80,
minifyCSS: true,
minifyJS: true,
continueOnParseError: false,
removeComments: true,
});
} else {
console.warn("Unknown filter: " + type);
return str;
}
}
function writeHtmlGzipped(sourceFile, resultFile, page) {
console.info("Reading " + sourceFile);
new inliner(sourceFile, function (error, html) {
console.info("Inlined " + html.length + " characters");
html = filter(html, "html-minify-ui");
console.info("Minified to " + html.length + " characters");
if (error) {
console.warn(error);
throw error;
}
html = adoptVersionAndRepo(html);
zlib.gzip(html, { level: zlib.constants.Z_BEST_COMPRESSION }, function (error, result) {
if (error) {
console.warn(error);
throw error;
}
console.info("Compressed " + result.length + " bytes");
const array = hexdump(result);
const src = `/*
* Binary array for the Web UI.
* gzip is used for smaller size and improved speeds.
*
* Please see https://kno.wled.ge/advanced/custom-features/#changing-web-ui
* to find out how to easily modify the web UI source!
*/
// Autogenerated from ${sourceFile}, do not edit!!
const uint16_t PAGE_${page}_L = ${result.length};
const uint8_t PAGE_${page}[] PROGMEM = {
${array}
};
`;
console.info("Writing " + resultFile);
fs.writeFileSync(resultFile, src);
});
});
}
function specToChunk(srcDir, s) {
if (s.method == "plaintext") {
const buf = fs.readFileSync(srcDir + "/" + s.file);
const str = buf.toString("ascii");
const str = buf.toString("utf-8");
const chunk = `
// Autogenerated from ${srcDir}/${s.file}, do not edit!!
const char ${s.name}[] PROGMEM = R"${s.prepend || ""}${filter(str, s.filter)}${
@ -141,6 +162,21 @@ const char ${s.name}[] PROGMEM = R"${s.prepend || ""}${filter(str, s.filter)}${
`;
return s.mangle ? s.mangle(chunk) : chunk;
} else if (s.method == "gzip") {
const buf = fs.readFileSync(srcDir + "/" + s.file);
var str = buf.toString('utf-8');
if (s.mangle) str = s.mangle(str);
const zip = zlib.gzipSync(filter(str, s.filter), { level: zlib.constants.Z_BEST_COMPRESSION });
const result = hexdump(zip.toString('hex'), true);
const chunk = `
// Autogenerated from ${srcDir}/${s.file}, do not edit!!
const uint16_t ${s.name}_length = ${zip.length};
const uint8_t ${s.name}[] PROGMEM = {
${result}
};
`;
return chunk;
} else if (s.method == "binary") {
const buf = fs.readFileSync(srcDir + "/" + s.file);
const result = hexdump(buf);
@ -152,7 +188,7 @@ ${result}
};
`;
return s.mangle ? s.mangle(chunk) : chunk;
return chunk;
} else {
console.warn("Unknown method: " + s.method);
return undefined;
@ -163,7 +199,7 @@ function writeChunks(srcDir, specs, resultFile) {
let src = `/*
* More web UI HTML source arrays.
* This file is auto generated, please don't make any changes manually.
* Instead, see https://github.com/Aircoookie/WLED/wiki/Add-own-functionality#web-ui
* Instead, see https://kno.wled.ge/advanced/custom-features/#changing-web-ui
* to find out how to easily modify the web UI source!
*/
`;
@ -182,141 +218,115 @@ function writeChunks(srcDir, specs, resultFile) {
fs.writeFileSync(resultFile, src);
}
writeHtmlGzipped("wled00/data/index.htm", "wled00/html_ui.h");
writeHtmlGzipped("wled00/data/index.htm", "wled00/html_ui.h", 'index');
writeHtmlGzipped("wled00/data/simple.htm", "wled00/html_simple.h", 'simple');
writeHtmlGzipped("wled00/data/pixart/pixart.htm", "wled00/html_pixart.h", 'pixart');
writeHtmlGzipped("wled00/data/cpal/cpal.htm", "wled00/html_cpal.h", 'cpal');
writeHtmlGzipped("wled00/data/pxmagic/pxmagic.htm", "wled00/html_pxmagic.h", 'pxmagic');
/*
writeChunks(
"wled00/data",
[
{
file: "simple.css",
name: "PAGE_simpleCss",
method: "gzip",
filter: "css-minify",
},
{
file: "simple.js",
name: "PAGE_simpleJs",
method: "gzip",
filter: "js-minify",
},
{
file: "simple.htm",
name: "PAGE_simple",
method: "gzip",
filter: "html-minify-ui",
}
],
"wled00/html_simplex.h"
);
*/
writeChunks(
"wled00/data",
[
{
file: "style.css",
name: "PAGE_settingsCss",
prepend: "=====(<style>",
append: "</style>)=====",
method: "plaintext",
method: "gzip",
filter: "css-minify",
mangle: (str) =>
str
.replace("%%","%")
},
{
file: "settings.htm",
name: "PAGE_settings",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
},
{
file: "settings_wifi.htm",
name: "PAGE_settings_wifi",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) =>
str
.replace(/\<link rel="stylesheet".*\>/gms, "")
.replace(/\<style\>.*\<\/style\>/gms, "%CSS%%SCSS%")
.replace(
/function GetV().*\<\/script\>/gms,
"function GetV() {var d=document;\n"
),
},
{
file: "settings_leds.htm",
name: "PAGE_settings_leds",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) =>
str
.replace(/\<link rel="stylesheet".*\>/gms, "")
.replace(/\<style\>.*\<\/style\>/gms, "%CSS%%SCSS%")
.replace(
/function GetV().*\<\/script\>/gms,
"function GetV() {var d=document;\n"
),
},
{
file: "settings_dmx.htm",
name: "PAGE_settings_dmx",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) => {
const nocss = str
.replace(/\<link rel="stylesheet".*\>/gms, "")
.replace(/\<style\>.*\<\/style\>/gms, "%CSS%%SCSS%")
.replace(
/function GetV().*\<\/script\>/gms,
"function GetV() {var d=document;\n"
);
return `
#ifdef WLED_ENABLE_DMX
${nocss}
#else
const char PAGE_settings_dmx[] PROGMEM = R"=====()=====";
#endif
`;
},
},
{
file: "settings_ui.htm",
name: "PAGE_settings_ui",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) =>
str
.replace(/\<link rel="stylesheet".*\>/gms, "")
.replace(/\<style\>.*\<\/style\>/gms, "%CSS%%SCSS%")
.replace(
/function GetV().*\<\/script\>/gms,
"function GetV() {var d=document;\n"
),
},
{
file: "settings_sync.htm",
name: "PAGE_settings_sync",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) =>
str
.replace(/\<link rel="stylesheet".*\>/gms, "")
.replace(/\<style\>.*\<\/style\>/gms, "%CSS%%SCSS%")
.replace(/function GetV().*\<\/script\>/gms, "function GetV() {\n"),
},
{
file: "settings_time.htm",
name: "PAGE_settings_time",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) =>
str
.replace(/\<link rel="stylesheet".*\>/gms, "")
.replace(/\<style\>.*\<\/style\>/gms, "%CSS%%SCSS%")
.replace(/function GetV().*\<\/script\>/gms, "function GetV() {\n"),
},
{
file: "settings_sec.htm",
name: "PAGE_settings_sec",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) =>
str
.replace(/\<link rel="stylesheet".*\>/gms, "")
.replace(/\<style\>.*\<\/style\>/gms, "%CSS%%SCSS%")
.replace(
/function GetV().*\<\/script\>/gms,
"function GetV() {var d=document;\n"
),
},
{
file: "settings_um.htm",
name: "PAGE_settings_um",
method: "gzip",
filter: "html-minify",
},
{
file: "settings_2D.htm",
name: "PAGE_settings_2D",
method: "gzip",
filter: "html-minify",
},
{
file: "settings_pin.htm",
name: "PAGE_settings_pin",
method: "gzip",
filter: "html-minify"
}
],
"wled00/html_settings.h"
);
@ -327,9 +337,7 @@ writeChunks(
{
file: "usermod.htm",
name: "PAGE_usermod",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) =>
str.replace(/fetch\("http\:\/\/.*\/win/gms, 'fetch("/win'),
@ -361,25 +369,37 @@ const char PAGE_dmxmap[] PROGMEM = R"=====()=====";
{
file: "update.htm",
name: "PAGE_update",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
mangle: (str) =>
str
.replace(
/function GetV().*\<\/script\>/gms,
"</script><script src=\"/settings/s.js?p=9\"></script>"
)
},
{
file: "welcome.htm",
name: "PAGE_welcome",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
},
{
file: "liveview.htm",
name: "PAGE_liveview",
prepend: "=====(",
append: ")=====",
method: "plaintext",
method: "gzip",
filter: "html-minify",
},
{
file: "liveviewws2D.htm",
name: "PAGE_liveviewws2D",
method: "gzip",
filter: "html-minify",
},
{
file: "404.htm",
name: "PAGE_404",
method: "gzip",
filter: "html-minify",
},
{
@ -387,6 +407,16 @@ const char PAGE_dmxmap[] PROGMEM = R"=====()=====";
name: "favicon",
method: "binary",
},
{
file: "iro.js",
name: "iroJs",
method: "gzip"
},
{
file: "rangetouch.js",
name: "rangetouchJs",
method: "gzip"
}
],
"wled00/html_other.h"
);

232
tools/fps_test.htm Normal file
View File

@ -0,0 +1,232 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>WLED frame rate test tool</title>
<style>
body {
background-color: #222;
color: #fff;
font-family: Helvetica, Verdana, sans-serif;
}
input {
background-color: #333;
color: #fff;
}
#ip {
width: 100px;
}
#secs {
width: 36px;
}
#csva {
position: absolute;
top: -100px; /*gtfo*/
}
button {
background-color: #333;
color: #fff;
}
table, th, td {
border: 1px solid #aaa;
border-collapse: collapse;
text-align: center;
}
.red {
color: #d20;
}
</style>
<script>
var gotfx = false, running = false;
var pos = 0, prev = 0, min = 999, max = 0, fpslist = [], names = [], names_checked = [];
var to;
function S() {
document.getElementById('ip').value = localStorage.getItem('locIpFps');
if (document.getElementById('ip').value) req(false);
}
function loadC() {
hide(false);
var list = localStorage.getItem('fpsFxSelection');
if (!list) return;
list = JSON.parse(list);
var chks = document.querySelectorAll('.fxcheck');
for (let i = 0; i < chks.length; i++) {
if (i < list.length) chks[i].checked = list[i];
}
}
function saveC() {
var list = [];
var chks = document.querySelectorAll('.fxcheck');
for (let i = 0; i < chks.length; i++) {
list.push(chks[i].checked);
}
localStorage.setItem('fpsFxSelection', JSON.stringify(list));
}
function setC(c) {
hide(false);
var chks = document.querySelectorAll('.fxcheck');
for (let i = 0; i < chks.length; i++) {
chks[i].checked = (c == 255);
}
if (c == 1 && chks.length > 100) {
chks[1].checked = true; //Blink
chks[15].checked = true; //Running
chks[16].checked = true; //Saw
chks[37].checked = true; //Running 2
chks[44].checked = true; //Tetrix
chks[63].checked = true; //Pride 2015
chks[74].checked = true; //Colortwinkles
chks[101].checked = true;//Pacifica
}
}
function hide(h) {
var trs = document.querySelectorAll('.trs');
var chks = document.querySelectorAll('.fxcheck');
for (let i = 0; i < trs.length; i++) {
trs[i].style.display = (h && !chks[i].checked) ? "none":"table-row";
}
}
function run(init) {
if (init) {
running = !running;
document.getElementById('runbtn').innerText = running ? 'Stop':'Run';
if (running) {pos = 0; prev = -1; min = 999; max = 0; fpslist = []; names_checked = []; hide(true);}
clearTimeout(to);
if (!running) {req({seg:{fx:0},v:true,stop:true}); return;}
}
if (!gotfx) {req(false); return;}
var chks = document.querySelectorAll('.fxcheck');
var fpsb = document.querySelectorAll('.fps');
if (prev >= 0) {pos++};
if (pos >= chks.length) {run(true); return;} //end
while (!chks[pos].checked) {
fpsb[pos].innerText = "-";
pos++;
if (pos >= chks.length) {run(true); return;} //end
}
names_checked.push(names[pos]);
var extra = {};
try {
extra = JSON.parse(document.getElementById('ej').value);
} catch (e) {
}
var cmd = {seg:{fx:pos},v:true};
Object.assign(cmd, extra);
req(cmd);
}
function req(command) {
var ip = document.getElementById('ip').value;
if (!ip) {alert("Please enter WLED IP"); return;}
if (ip != localStorage.getItem('locIpFps')) localStorage.setItem('locIpFps', document.getElementById('ip').value);
var url = command ? `http://${ip}/json/si` : `http://${ip}/json/effects`;
var type = command ? 'post':'get';
var req = undefined;
if (command)
{
req = JSON.stringify(command);
}
fetch
(url, {
method: type,
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: req
})
.then(res => {
if (!res.ok) {
alert('Data malfunction');
}
return res.json();
})
.then(json => {
if (!json) {
alert('Empty response'); return;
}
if (!command) {
names = json;
var tblc = '';
for (let i = 0; i < json.length; i++) {
tblc += `<tr class="trs"><td><input type="checkbox" class="fxcheck" /></td><td>${i}</td><td>${json[i]}</td><td class="fps"></td></tr>`
}
var tbl = `<table>
<tr>
<th>Test?</th><th>ID</th><th>Effect Name</th><th>FPS</th>
</tr>
${tblc}
</table>`;
document.getElementById('tablecon').innerHTML = tbl;
setC(1);
loadC();
gotfx = true;
document.getElementById('runbtn').innerText = "Run";
} else {
if (!json.info) return;
document.getElementById('leds').innerText = json.info.leds.count;
document.getElementById('seg').innerText = json.state.seg[0].len;
document.getElementById('bri').innerText = json.state.bri;
if (prev >= 0) {
var lastfps = parseInt(json.info.leds.fps); //previous FX
if (lastfps < min) min = lastfps;
if (lastfps > max) max = lastfps;
fpslist.push(lastfps);
var sum = 0;
for (let i = 0; i < fpslist.length; i++) {
sum += fpslist[i];
}
sum /= fpslist.length;
document.getElementById('fps_min').innerText = min;
document.getElementById('fps_max').innerText = max;
document.getElementById('fps_avg').innerText = Math.round(sum*10)/10;
var fpsb = document.querySelectorAll('.fps');
fpsb[prev].innerHTML = lastfps;
}
prev = pos;
var delay = parseInt(document.getElementById('secs').value)*1000;
delay = Math.min(Math.max(delay, 2000), 15000)
if (!command.stop) to = setTimeout(run,delay);
}
})
.catch(function (error) {
alert('Comms malfunction');
console.log(error);
});
}
function csv(n) {
var txt = "";
for (let i = 0; i < fpslist.length; i++) {
if (!n) txt += names_checked[i] + ',';
txt += fpslist[i]; txt += "\n";
}
document.getElementById('csva').value = txt;
var copyText = document.getElementById('csva');
copyText.select();
copyText.setSelectionRange(0, 999999);
document.execCommand("copy");
}
</script>
</head>
<body onload="S()">
<h2>Starship monitoring dashboard</h2>
(or rather just a WLED frame rate tester lol)<br><br>
IP: <input id="ip" /><br>
Time per effect: <input type=number id=secs value=5 max=15 min=2 />s<br>
Effects to test:
<button type="button" onclick="setC(255)">All</button>
<button type="button" onclick="setC(1)">Selection 1</button>
<button type="button" onclick="setC(0)">None</button>
<button type="button" onclick="loadC()">Get LS</button>
<button type="button" class="red" onclick="saveC()">Save to LS</button><br>
Extra JSON: <input id="ej" /><br>
<button type="button" onclick="run(true)" id="runbtn">Fetch FX list</button><br>
LEDs: <span id="leds">-</span>, Seg: <span id="seg">-</span>, Bri: <span id="bri">-</span><br>
FPS min: <span id="fps_min">-</span>, max: <span id="fps_max">-</span>, avg: <span id="fps_avg">-</span><br><br>
<div id="tablecon">
</div><br>
<button type="button" onclick="csv(false)">Copy csv to clipboard</button>
<button type="button" onclick="csv(true)">Copy csv (FPS only)</button>
<textarea id=csva></textarea>
</body>
</html>

16
tools/multi-update.cmd Normal file
View File

@ -0,0 +1,16 @@
@echo off
SETLOCAL
SET FWPATH=c:\path\to\your\WLED\build_output\firmware
GOTO ESPS
:UPDATEONE
IF NOT EXIST %FWPATH%\%2 GOTO SKIP
ping -w 1000 -n 1 %1 | find "TTL=" || GOTO SKIP
ECHO Updating %1
curl -s -F "update=@%FWPATH%/%2" %1/update >nul
:SKIP
GOTO:EOF
:ESPS
call :UPDATEONE 192.168.x.x firmware.bin
call :UPDATEONE ....

19
tools/multi-update.sh Normal file
View File

@ -0,0 +1,19 @@
#!/bin/bash
FWPATH=/path/to/your/WLED/build_output/firmware
update_one() {
if [ -f $FWPATH/$2 ]; then
ping -c 1 $1 >/dev/null
PINGRESULT=$?
if [ $PINGRESULT -eq 0 ]; then
echo Updating $1
curl -s -F "update=@${FWPATH}/$2" $1/update >/dev/null
return 0
fi
return 1
fi
}
update_one 192.168.x.x firmware.bin
update_one 192.168.x.x firmware.bin
# ...

View File

@ -0,0 +1,15 @@
#include "wled.h"
namespace ADS1115
{
struct ChannelSettings {
const String settingName;
bool isEnabled;
String name;
String units;
const uint16_t mux;
float multiplier;
float offset;
uint8_t decimals;
};
}

View File

@ -0,0 +1,10 @@
# ADS1115 16-Bit ADC with four inputs
This usermod will read from an ADS1115 ADC. The voltages are displayed in the Info section of the web UI.
Configuration is performed via the Usermod menu. There are no parameters to set in code!
## Installation
Add the build flag `-D USERMOD_ADS1115` to your platformio environment.
Uncomment libraries with comment `#For ADS1115 sensor uncomment following`

View File

@ -0,0 +1,255 @@
#pragma once
#include "wled.h"
#include <Adafruit_ADS1X15.h>
#include <math.h>
#include "ChannelSettings.h"
using namespace ADS1115;
class ADS1115Usermod : public Usermod {
public:
void setup() {
ads.setGain(GAIN_ONE); // 1x gain +/- 4.096V
if (!ads.begin()) {
Serial.println("Failed to initialize ADS");
return;
}
if (!initChannel()) {
isInitialized = true;
return;
}
startReading();
isEnabled = true;
isInitialized = true;
}
void loop() {
if (isEnabled && millis() - lastTime > loopInterval) {
lastTime = millis();
// If we don't have new data, skip this iteration.
if (!ads.conversionComplete()) {
return;
}
updateResult();
moveToNextChannel();
startReading();
}
}
void addToJsonInfo(JsonObject& root)
{
if (!isEnabled) {
return;
}
JsonObject user = root[F("u")];
if (user.isNull()) user = root.createNestedObject(F("u"));
for (uint8_t i = 0; i < channelsCount; i++) {
ChannelSettings* settingsPtr = &(channelSettings[i]);
if (!settingsPtr->isEnabled) {
continue;
}
JsonArray lightArr = user.createNestedArray(settingsPtr->name); //name
float value = round((readings[i] + settingsPtr->offset) * settingsPtr->multiplier, settingsPtr->decimals);
lightArr.add(value); //value
lightArr.add(" " + settingsPtr->units); //unit
}
}
void addToConfig(JsonObject& root)
{
JsonObject top = root.createNestedObject(F("ADC ADS1115"));
for (uint8_t i = 0; i < channelsCount; i++) {
ChannelSettings* settingsPtr = &(channelSettings[i]);
JsonObject channel = top.createNestedObject(settingsPtr->settingName);
channel[F("Enabled")] = settingsPtr->isEnabled;
channel[F("Name")] = settingsPtr->name;
channel[F("Units")] = settingsPtr->units;
channel[F("Multiplier")] = settingsPtr->multiplier;
channel[F("Offset")] = settingsPtr->offset;
channel[F("Decimals")] = settingsPtr->decimals;
}
top[F("Loop Interval")] = loopInterval;
}
bool readFromConfig(JsonObject& root)
{
JsonObject top = root[F("ADC ADS1115")];
bool configComplete = !top.isNull();
bool hasEnabledChannels = false;
for (uint8_t i = 0; i < channelsCount && configComplete; i++) {
ChannelSettings* settingsPtr = &(channelSettings[i]);
JsonObject channel = top[settingsPtr->settingName];
configComplete &= !channel.isNull();
configComplete &= getJsonValue(channel[F("Enabled")], settingsPtr->isEnabled);
configComplete &= getJsonValue(channel[F("Name")], settingsPtr->name);
configComplete &= getJsonValue(channel[F("Units")], settingsPtr->units);
configComplete &= getJsonValue(channel[F("Multiplier")], settingsPtr->multiplier);
configComplete &= getJsonValue(channel[F("Offset")], settingsPtr->offset);
configComplete &= getJsonValue(channel[F("Decimals")], settingsPtr->decimals);
hasEnabledChannels |= settingsPtr->isEnabled;
}
configComplete &= getJsonValue(top[F("Loop Interval")], loopInterval);
isEnabled = isInitialized && configComplete && hasEnabledChannels;
return configComplete;
}
uint16_t getId()
{
return USERMOD_ID_ADS1115;
}
private:
static const uint8_t channelsCount = 8;
ChannelSettings channelSettings[channelsCount] = {
{
"Differential reading from AIN0 (P) and AIN1 (N)",
false,
"Differential AIN0 AIN1",
"V",
ADS1X15_REG_CONFIG_MUX_DIFF_0_1,
1,
0,
3
},
{
"Differential reading from AIN0 (P) and AIN3 (N)",
false,
"Differential AIN0 AIN3",
"V",
ADS1X15_REG_CONFIG_MUX_DIFF_0_3,
1,
0,
3
},
{
"Differential reading from AIN1 (P) and AIN3 (N)",
false,
"Differential AIN1 AIN3",
"V",
ADS1X15_REG_CONFIG_MUX_DIFF_1_3,
1,
0,
3
},
{
"Differential reading from AIN2 (P) and AIN3 (N)",
false,
"Differential AIN2 AIN3",
"V",
ADS1X15_REG_CONFIG_MUX_DIFF_2_3,
1,
0,
3
},
{
"Single-ended reading from AIN0",
false,
"Single-ended AIN0",
"V",
ADS1X15_REG_CONFIG_MUX_SINGLE_0,
1,
0,
3
},
{
"Single-ended reading from AIN1",
false,
"Single-ended AIN1",
"V",
ADS1X15_REG_CONFIG_MUX_SINGLE_1,
1,
0,
3
},
{
"Single-ended reading from AIN2",
false,
"Single-ended AIN2",
"V",
ADS1X15_REG_CONFIG_MUX_SINGLE_2,
1,
0,
3
},
{
"Single-ended reading from AIN3",
false,
"Single-ended AIN3",
"V",
ADS1X15_REG_CONFIG_MUX_SINGLE_3,
1,
0,
3
},
};
float readings[channelsCount] = {0, 0, 0, 0, 0, 0, 0, 0};
unsigned long loopInterval = 1000;
unsigned long lastTime = 0;
Adafruit_ADS1115 ads;
uint8_t activeChannel;
bool isEnabled = false;
bool isInitialized = false;
static float round(float value, uint8_t decimals) {
return roundf(value * powf(10, decimals)) / powf(10, decimals);
}
bool initChannel() {
for (uint8_t i = 0; i < channelsCount; i++) {
if (channelSettings[i].isEnabled) {
activeChannel = i;
return true;
}
}
activeChannel = 0;
return false;
}
void moveToNextChannel() {
uint8_t oldActiveChannel = activeChannel;
do
{
if (++activeChannel >= channelsCount){
activeChannel = 0;
}
}
while (!channelSettings[activeChannel].isEnabled && oldActiveChannel != activeChannel);
}
void startReading() {
ads.startADCReading(channelSettings[activeChannel].mux, /*continuous=*/false);
}
void updateResult() {
int16_t results = ads.getLastConversionResults();
readings[activeChannel] = ads.computeVolts(results);
}
};

View File

@ -0,0 +1,256 @@
#pragma once
#include "wled.h"
/*
* Usermod for analog clock
*/
extern Timezone* tz;
class AnalogClockUsermod : public Usermod {
private:
static constexpr uint32_t refreshRate = 50; // per second
static constexpr uint32_t refreshDelay = 1000 / refreshRate;
struct Segment {
// config
int16_t firstLed = 0;
int16_t lastLed = 59;
int16_t centerLed = 0;
// runtime
int16_t size;
Segment() {
update();
}
void validateAndUpdate() {
if (firstLed < 0 || firstLed >= strip.getLengthTotal() ||
lastLed < firstLed || lastLed >= strip.getLengthTotal()) {
*this = {};
return;
}
if (centerLed < firstLed || centerLed > lastLed) {
centerLed = firstLed;
}
update();
}
void update() {
size = lastLed - firstLed + 1;
}
};
// configuration (available in API and stored in flash)
bool enabled = false;
Segment mainSegment;
bool hourMarksEnabled = true;
uint32_t hourMarkColor = 0xFF0000;
uint32_t hourColor = 0x0000FF;
uint32_t minuteColor = 0x00FF00;
bool secondsEnabled = true;
Segment secondsSegment;
uint32_t secondColor = 0xFF0000;
bool blendColors = true;
uint16_t secondsEffect = 0;
// runtime
bool initDone = false;
uint32_t lastOverlayDraw = 0;
void validateAndUpdate() {
mainSegment.validateAndUpdate();
secondsSegment.validateAndUpdate();
if (secondsEffect < 0 || secondsEffect > 1) {
secondsEffect = 0;
}
}
int16_t adjustToSegment(double progress, Segment const& segment) {
int16_t led = segment.centerLed + progress * segment.size;
return led > segment.lastLed
? segment.firstLed + led - segment.lastLed - 1
: led;
}
void setPixelColor(uint16_t n, uint32_t c) {
if (!blendColors) {
strip.setPixelColor(n, c);
} else {
uint32_t oldC = strip.getPixelColor(n);
strip.setPixelColor(n, qadd32(oldC, c));
}
}
String colorToHexString(uint32_t c) {
char buffer[9];
sprintf(buffer, "%06X", c);
return buffer;
}
bool hexStringToColor(String const& s, uint32_t& c, uint32_t def) {
char *ep;
unsigned long long r = strtoull(s.c_str(), &ep, 16);
if (*ep == 0) {
c = r;
return true;
} else {
c = def;
return false;
}
}
void secondsEffectSineFade(int16_t secondLed, Toki::Time const& time) {
uint32_t ms = time.ms % 1000;
uint8_t b0 = (cos8(ms * 64 / 1000) - 128) * 2;
setPixelColor(secondLed, gamma32(scale32(secondColor, b0)));
uint8_t b1 = (sin8(ms * 64 / 1000) - 128) * 2;
setPixelColor(inc(secondLed, 1, secondsSegment), gamma32(scale32(secondColor, b1)));
}
static inline uint32_t qadd32(uint32_t c1, uint32_t c2) {
return RGBW32(
qadd8(R(c1), R(c2)),
qadd8(G(c1), G(c2)),
qadd8(B(c1), B(c2)),
qadd8(W(c1), W(c2))
);
}
static inline uint32_t scale32(uint32_t c, fract8 scale) {
return RGBW32(
scale8(R(c), scale),
scale8(G(c), scale),
scale8(B(c), scale),
scale8(W(c), scale)
);
}
static inline int16_t dec(int16_t n, int16_t i, Segment const& seg) {
return n - seg.firstLed >= i
? n - i
: seg.lastLed - seg.firstLed - i + n + 1;
}
static inline int16_t inc(int16_t n, int16_t i, Segment const& seg) {
int16_t r = n + i;
if (r > seg.lastLed) {
return seg.firstLed + n - seg.lastLed;
}
return r;
}
public:
AnalogClockUsermod() {
}
void setup() override {
initDone = true;
validateAndUpdate();
}
void loop() override {
if (millis() - lastOverlayDraw > refreshDelay) {
strip.trigger();
}
}
void handleOverlayDraw() override {
if (!enabled) {
return;
}
lastOverlayDraw = millis();
auto time = toki.getTime();
double secondP = second(localTime) / 60.0;
double minuteP = minute(localTime) / 60.0;
double hourP = (hour(localTime) % 12) / 12.0 + minuteP / 12.0;
if (hourMarksEnabled) {
for (int Led = 0; Led <= 55; Led = Led + 5)
{
int16_t hourmarkled = adjustToSegment(Led / 60.0, mainSegment);
setPixelColor(hourmarkled, hourMarkColor);
}
}
if (secondsEnabled) {
int16_t secondLed = adjustToSegment(secondP, secondsSegment);
switch (secondsEffect) {
case 0: // no effect
setPixelColor(secondLed, secondColor);
break;
case 1: // fading seconds
secondsEffectSineFade(secondLed, time);
break;
}
// TODO: move to secondsTrailEffect
// for (uint16_t i = 1; i < secondsTrail + 1; ++i) {
// uint16_t trailLed = dec(secondLed, i, secondsSegment);
// uint8_t trailBright = 255 / (secondsTrail + 1) * (secondsTrail - i + 1);
// setPixelColor(trailLed, gamma32(scale32(secondColor, trailBright)));
// }
}
setPixelColor(adjustToSegment(minuteP, mainSegment), minuteColor);
setPixelColor(adjustToSegment(hourP, mainSegment), hourColor);
}
void addToConfig(JsonObject& root) override {
validateAndUpdate();
JsonObject top = root.createNestedObject(F("Analog Clock"));
top[F("Overlay Enabled")] = enabled;
top[F("First LED (Main Ring)")] = mainSegment.firstLed;
top[F("Last LED (Main Ring)")] = mainSegment.lastLed;
top[F("Center/12h LED (Main Ring)")] = mainSegment.centerLed;
top[F("Hour Marks Enabled")] = hourMarksEnabled;
top[F("Hour Mark Color (RRGGBB)")] = colorToHexString(hourMarkColor);
top[F("Hour Color (RRGGBB)")] = colorToHexString(hourColor);
top[F("Minute Color (RRGGBB)")] = colorToHexString(minuteColor);
top[F("Show Seconds")] = secondsEnabled;
top[F("First LED (Seconds Ring)")] = secondsSegment.firstLed;
top[F("Last LED (Seconds Ring)")] = secondsSegment.lastLed;
top[F("Center/12h LED (Seconds Ring)")] = secondsSegment.centerLed;
top[F("Second Color (RRGGBB)")] = colorToHexString(secondColor);
top[F("Seconds Effect (0-1)")] = secondsEffect;
top[F("Blend Colors")] = blendColors;
}
bool readFromConfig(JsonObject& root) override {
JsonObject top = root[F("Analog Clock")];
bool configComplete = !top.isNull();
String color;
configComplete &= getJsonValue(top[F("Overlay Enabled")], enabled, false);
configComplete &= getJsonValue(top[F("First LED (Main Ring)")], mainSegment.firstLed, 0);
configComplete &= getJsonValue(top[F("Last LED (Main Ring)")], mainSegment.lastLed, 59);
configComplete &= getJsonValue(top[F("Center/12h LED (Main Ring)")], mainSegment.centerLed, 0);
configComplete &= getJsonValue(top[F("Hour Marks Enabled")], hourMarksEnabled, false);
configComplete &= getJsonValue(top[F("Hour Mark Color (RRGGBB)")], color, F("161616")) && hexStringToColor(color, hourMarkColor, 0x161616);
configComplete &= getJsonValue(top[F("Hour Color (RRGGBB)")], color, F("0000FF")) && hexStringToColor(color, hourColor, 0x0000FF);
configComplete &= getJsonValue(top[F("Minute Color (RRGGBB)")], color, F("00FF00")) && hexStringToColor(color, minuteColor, 0x00FF00);
configComplete &= getJsonValue(top[F("Show Seconds")], secondsEnabled, true);
configComplete &= getJsonValue(top[F("First LED (Seconds Ring)")], secondsSegment.firstLed, 0);
configComplete &= getJsonValue(top[F("Last LED (Seconds Ring)")], secondsSegment.lastLed, 59);
configComplete &= getJsonValue(top[F("Center/12h LED (Seconds Ring)")], secondsSegment.centerLed, 0);
configComplete &= getJsonValue(top[F("Second Color (RRGGBB)")], color, F("FF0000")) && hexStringToColor(color, secondColor, 0xFF0000);
configComplete &= getJsonValue(top[F("Seconds Effect (0-1)")], secondsEffect, 0);
configComplete &= getJsonValue(top[F("Blend Colors")], blendColors, true);
if (initDone) {
validateAndUpdate();
}
return configComplete;
}
uint16_t getId() override {
return USERMOD_ID_ANALOG_CLOCK;
}
};

View File

@ -0,0 +1,553 @@
/*
* Usermod for detecting people entering/leaving a staircase and switching the
* staircase on/off.
*
* Edit the Animated_Staircase_config.h file to compile this usermod for your
* specific configuration.
*
* See the accompanying README.md file for more info.
*/
#pragma once
#include "wled.h"
class Animated_Staircase : public Usermod {
private:
/* configuration (available in API and stored in flash) */
bool enabled = false; // Enable this usermod
unsigned long segment_delay_ms = 150; // Time between switching each segment
unsigned long on_time_ms = 30000; // The time for the light to stay on
int8_t topPIRorTriggerPin = -1; // disabled
int8_t bottomPIRorTriggerPin = -1; // disabled
int8_t topEchoPin = -1; // disabled
int8_t bottomEchoPin = -1; // disabled
bool useUSSensorTop = false; // using PIR or UltraSound sensor?
bool useUSSensorBottom = false; // using PIR or UltraSound sensor?
unsigned int topMaxDist = 50; // default maximum measured distance in cm, top
unsigned int bottomMaxDist = 50; // default maximum measured distance in cm, bottom
/* runtime variables */
bool initDone = false;
// Time between checking of the sensors
const unsigned int scanDelay = 100;
// Lights on or off.
// Flipping this will start a transition.
bool on = false;
// Swipe direction for current transition
#define SWIPE_UP true
#define SWIPE_DOWN false
bool swipe = SWIPE_UP;
// Indicates which Sensor was seen last (to determine
// the direction when swiping off)
#define LOWER false
#define UPPER true
bool lastSensor = LOWER;
// Time of the last transition action
unsigned long lastTime = 0;
// Time of the last sensor check
unsigned long lastScanTime = 0;
// Last time the lights were switched on or off
unsigned long lastSwitchTime = 0;
// segment id between onIndex and offIndex are on.
// controll the swipe by setting/moving these indices around.
// onIndex must be less than or equal to offIndex
byte onIndex = 0;
byte offIndex = 0;
// The maximum number of configured segments.
// Dynamically updated based on user configuration.
byte maxSegmentId = 1;
byte minSegmentId = 0;
// These values are used by the API to read the
// last sensor state, or trigger a sensor
// through the API
bool topSensorRead = false;
bool topSensorWrite = false;
bool bottomSensorRead = false;
bool bottomSensorWrite = false;
bool topSensorState = false;
bool bottomSensorState = false;
// strings to reduce flash memory usage (used more than twice)
static const char _name[];
static const char _enabled[];
static const char _segmentDelay[];
static const char _onTime[];
static const char _useTopUltrasoundSensor[];
static const char _topPIRorTrigger_pin[];
static const char _topEcho_pin[];
static const char _useBottomUltrasoundSensor[];
static const char _bottomPIRorTrigger_pin[];
static const char _bottomEcho_pin[];
static const char _topEchoCm[];
static const char _bottomEchoCm[];
void publishMqtt(bool bottom, const char* state) {
#ifndef WLED_DISABLE_MQTT
//Check if MQTT Connected, otherwise it will crash the 8266
if (WLED_MQTT_CONNECTED){
char subuf[64];
sprintf_P(subuf, PSTR("%s/motion/%d"), mqttDeviceTopic, (int)bottom);
mqtt->publish(subuf, 0, false, state);
}
#endif
}
void updateSegments() {
for (int i = minSegmentId; i < maxSegmentId; i++) {
Segment &seg = strip.getSegment(i);
if (!seg.isActive()) continue; // skip gaps
if (i >= onIndex && i < offIndex) {
seg.setOption(SEG_OPTION_ON, true);
// We may need to copy mode and colors from segment 0 to make sure
// changes are propagated even when the config is changed during a wipe
// seg.setMode(mainsegment.mode);
// seg.setColor(0, mainsegment.colors[0]);
} else {
seg.setOption(SEG_OPTION_ON, false);
}
// Always mark segments as "transitional", we are animating the staircase
//seg.setOption(SEG_OPTION_TRANSITIONAL, true); // not needed anymore as setOption() does it
}
strip.trigger(); // force strip refresh
stateChanged = true; // inform external devices/UI of change
colorUpdated(CALL_MODE_DIRECT_CHANGE);
}
/*
* Detects if an object is within ultrasound range.
* signalPin: The pin where the pulse is sent
* echoPin: The pin where the echo is received
* maxTimeUs: Detection timeout in microseconds. If an echo is
* received within this time, an object is detected
* and the function will return true.
*
* The speed of sound is 343 meters per second at 20 degress Celcius.
* Since the sound has to travel back and forth, the detection
* distance for the sensor in cm is (0.0343 * maxTimeUs) / 2.
*
* For practical reasons, here are some useful distances:
*
* Distance = maxtime
* 5 cm = 292 uS
* 10 cm = 583 uS
* 20 cm = 1166 uS
* 30 cm = 1749 uS
* 50 cm = 2915 uS
* 100 cm = 5831 uS
*/
bool ultrasoundRead(int8_t signalPin, int8_t echoPin, unsigned int maxTimeUs) {
if (signalPin<0 || echoPin<0) return false;
digitalWrite(signalPin, LOW);
delayMicroseconds(2);
digitalWrite(signalPin, HIGH);
delayMicroseconds(10);
digitalWrite(signalPin, LOW);
return pulseIn(echoPin, HIGH, maxTimeUs) > 0;
}
bool checkSensors() {
bool sensorChanged = false;
if ((millis() - lastScanTime) > scanDelay) {
lastScanTime = millis();
bottomSensorRead = bottomSensorWrite ||
(!useUSSensorBottom ?
(bottomPIRorTriggerPin<0 ? false : digitalRead(bottomPIRorTriggerPin)) :
ultrasoundRead(bottomPIRorTriggerPin, bottomEchoPin, bottomMaxDist*59) // cm to us
);
topSensorRead = topSensorWrite ||
(!useUSSensorTop ?
(topPIRorTriggerPin<0 ? false : digitalRead(topPIRorTriggerPin)) :
ultrasoundRead(topPIRorTriggerPin, topEchoPin, topMaxDist*59) // cm to us
);
if (bottomSensorRead != bottomSensorState) {
bottomSensorState = bottomSensorRead; // change previous state
sensorChanged = true;
publishMqtt(true, bottomSensorState ? "on" : "off");
DEBUG_PRINTLN(F("Bottom sensor changed."));
}
if (topSensorRead != topSensorState) {
topSensorState = topSensorRead; // change previous state
sensorChanged = true;
publishMqtt(false, topSensorState ? "on" : "off");
DEBUG_PRINTLN(F("Top sensor changed."));
}
// Values read, reset the flags for next API call
topSensorWrite = false;
bottomSensorWrite = false;
if (topSensorRead != bottomSensorRead) {
lastSwitchTime = millis();
if (on) {
lastSensor = topSensorRead;
} else {
// If the bottom sensor triggered, we need to swipe up, ON
swipe = bottomSensorRead;
DEBUG_PRINT(F("ON -> Swipe "));
DEBUG_PRINTLN(swipe ? F("up.") : F("down."));
if (onIndex == offIndex) {
// Position the indices for a correct on-swipe
if (swipe == SWIPE_UP) {
onIndex = minSegmentId;
} else {
onIndex = maxSegmentId;
}
offIndex = onIndex;
}
on = true;
}
}
}
return sensorChanged;
}
void autoPowerOff() {
if ((millis() - lastSwitchTime) > on_time_ms) {
// if sensors are still on, do nothing
if (bottomSensorState || topSensorState) return;
// Swipe OFF in the direction of the last sensor detection
swipe = lastSensor;
on = false;
DEBUG_PRINT(F("OFF -> Swipe "));
DEBUG_PRINTLN(swipe ? F("up.") : F("down."));
}
}
void updateSwipe() {
if ((millis() - lastTime) > segment_delay_ms) {
lastTime = millis();
byte oldOn = onIndex;
byte oldOff = offIndex;
if (on) {
// Turn on all segments
onIndex = MAX(minSegmentId, onIndex - 1);
offIndex = MIN(maxSegmentId, offIndex + 1);
} else {
if (swipe == SWIPE_UP) {
onIndex = MIN(offIndex, onIndex + 1);
} else {
offIndex = MAX(onIndex, offIndex - 1);
}
}
if (oldOn != onIndex || oldOff != offIndex) updateSegments(); // reduce the number of updates to necessary ones
}
}
// send sesnor values to JSON API
void writeSensorsToJson(JsonObject& staircase) {
staircase[F("top-sensor")] = topSensorRead;
staircase[F("bottom-sensor")] = bottomSensorRead;
}
// allow overrides from JSON API
void readSensorsFromJson(JsonObject& staircase) {
bottomSensorWrite = bottomSensorState || (staircase[F("bottom-sensor")].as<bool>());
topSensorWrite = topSensorState || (staircase[F("top-sensor")].as<bool>());
}
void enable(bool enable) {
if (enable) {
DEBUG_PRINTLN(F("Animated Staircase enabled."));
DEBUG_PRINT(F("Delay between steps: "));
DEBUG_PRINT(segment_delay_ms);
DEBUG_PRINT(F(" milliseconds.\nStairs switch off after: "));
DEBUG_PRINT(on_time_ms / 1000);
DEBUG_PRINTLN(F(" seconds."));
if (!useUSSensorBottom)
pinMode(bottomPIRorTriggerPin, INPUT_PULLUP);
else {
pinMode(bottomPIRorTriggerPin, OUTPUT);
pinMode(bottomEchoPin, INPUT);
}
if (!useUSSensorTop)
pinMode(topPIRorTriggerPin, INPUT_PULLUP);
else {
pinMode(topPIRorTriggerPin, OUTPUT);
pinMode(topEchoPin, INPUT);
}
onIndex = minSegmentId = strip.getMainSegmentId(); // it may not be the best idea to start with main segment as it may not be the first one
offIndex = maxSegmentId = strip.getLastActiveSegmentId() + 1;
// shorten the strip transition time to be equal or shorter than segment delay
transitionDelayTemp = transitionDelay = segment_delay_ms;
strip.setTransition(segment_delay_ms/100);
strip.trigger();
} else {
// Restore segment options
for (int i = 0; i <= strip.getLastActiveSegmentId(); i++) {
Segment &seg = strip.getSegment(i);
if (!seg.isActive()) continue; // skip vector gaps
seg.setOption(SEG_OPTION_ON, true);
}
strip.trigger(); // force strip update
stateChanged = true; // inform external dvices/UI of change
colorUpdated(CALL_MODE_DIRECT_CHANGE);
DEBUG_PRINTLN(F("Animated Staircase disabled."));
}
enabled = enable;
}
public:
void setup() {
// standardize invalid pin numbers to -1
if (topPIRorTriggerPin < 0) topPIRorTriggerPin = -1;
if (topEchoPin < 0) topEchoPin = -1;
if (bottomPIRorTriggerPin < 0) bottomPIRorTriggerPin = -1;
if (bottomEchoPin < 0) bottomEchoPin = -1;
// allocate pins
PinManagerPinType pins[4] = {
{ topPIRorTriggerPin, useUSSensorTop },
{ topEchoPin, false },
{ bottomPIRorTriggerPin, useUSSensorBottom },
{ bottomEchoPin, false },
};
// NOTE: this *WILL* return TRUE if all the pins are set to -1.
// this is *BY DESIGN*.
if (!pinManager.allocateMultiplePins(pins, 4, PinOwner::UM_AnimatedStaircase)) {
topPIRorTriggerPin = -1;
topEchoPin = -1;
bottomPIRorTriggerPin = -1;
bottomEchoPin = -1;
enabled = false;
}
enable(enabled);
initDone = true;
}
void loop() {
if (!enabled || strip.isUpdating()) return;
minSegmentId = strip.getMainSegmentId(); // it may not be the best idea to start with main segment as it may not be the first one
maxSegmentId = strip.getLastActiveSegmentId() + 1;
checkSensors();
if (on) autoPowerOff();
updateSwipe();
}
uint16_t getId() { return USERMOD_ID_ANIMATED_STAIRCASE; }
#ifndef WLED_DISABLE_MQTT
/**
* handling of MQTT message
* topic only contains stripped topic (part after /wled/MAC)
* topic should look like: /swipe with amessage of [up|down]
*/
bool onMqttMessage(char* topic, char* payload) {
if (strlen(topic) == 6 && strncmp_P(topic, PSTR("/swipe"), 6) == 0) {
String action = payload;
if (action == "up") {
bottomSensorWrite = true;
return true;
} else if (action == "down") {
topSensorWrite = true;
return true;
} else if (action == "on") {
enable(true);
return true;
} else if (action == "off") {
enable(false);
return true;
}
}
return false;
}
/**
* subscribe to MQTT topic for controlling usermod
*/
void onMqttConnect(bool sessionPresent) {
//(re)subscribe to required topics
char subuf[64];
if (mqttDeviceTopic[0] != 0) {
strcpy(subuf, mqttDeviceTopic);
strcat_P(subuf, PSTR("/swipe"));
mqtt->subscribe(subuf, 0);
}
}
#endif
void addToJsonState(JsonObject& root) {
JsonObject staircase = root[FPSTR(_name)];
if (staircase.isNull()) {
staircase = root.createNestedObject(FPSTR(_name));
}
writeSensorsToJson(staircase);
DEBUG_PRINTLN(F("Staircase sensor state exposed in API."));
}
/*
* Reads configuration settings from the json API.
* See void addToJsonState(JsonObject& root)
*/
void readFromJsonState(JsonObject& root) {
if (!initDone) return; // prevent crash on boot applyPreset()
bool en = enabled;
JsonObject staircase = root[FPSTR(_name)];
if (!staircase.isNull()) {
if (staircase[FPSTR(_enabled)].is<bool>()) {
en = staircase[FPSTR(_enabled)].as<bool>();
} else {
String str = staircase[FPSTR(_enabled)]; // checkbox -> off or on
en = (bool)(str!="off"); // off is guaranteed to be present
}
if (en != enabled) enable(en);
readSensorsFromJson(staircase);
DEBUG_PRINTLN(F("Staircase sensor state read from API."));
}
}
void appendConfigData() {
//oappend(SET_F("dd=addDropdown('staircase','selectfield');"));
//oappend(SET_F("addOption(dd,'1st value',0);"));
//oappend(SET_F("addOption(dd,'2nd value',1);"));
//oappend(SET_F("addInfo('staircase:selectfield',1,'additional info');")); // 0 is field type, 1 is actual field
}
/*
* Writes the configuration to internal flash memory.
*/
void addToConfig(JsonObject& root) {
JsonObject staircase = root[FPSTR(_name)];
if (staircase.isNull()) {
staircase = root.createNestedObject(FPSTR(_name));
}
staircase[FPSTR(_enabled)] = enabled;
staircase[FPSTR(_segmentDelay)] = segment_delay_ms;
staircase[FPSTR(_onTime)] = on_time_ms / 1000;
staircase[FPSTR(_useTopUltrasoundSensor)] = useUSSensorTop;
staircase[FPSTR(_topPIRorTrigger_pin)] = topPIRorTriggerPin;
staircase[FPSTR(_topEcho_pin)] = useUSSensorTop ? topEchoPin : -1;
staircase[FPSTR(_useBottomUltrasoundSensor)] = useUSSensorBottom;
staircase[FPSTR(_bottomPIRorTrigger_pin)] = bottomPIRorTriggerPin;
staircase[FPSTR(_bottomEcho_pin)] = useUSSensorBottom ? bottomEchoPin : -1;
staircase[FPSTR(_topEchoCm)] = topMaxDist;
staircase[FPSTR(_bottomEchoCm)] = bottomMaxDist;
DEBUG_PRINTLN(F("Staircase config saved."));
}
/*
* Reads the configuration to internal flash memory before setup() is called.
*
* The function should return true if configuration was successfully loaded or false if there was no configuration.
*/
bool readFromConfig(JsonObject& root) {
bool oldUseUSSensorTop = useUSSensorTop;
bool oldUseUSSensorBottom = useUSSensorBottom;
int8_t oldTopAPin = topPIRorTriggerPin;
int8_t oldTopBPin = topEchoPin;
int8_t oldBottomAPin = bottomPIRorTriggerPin;
int8_t oldBottomBPin = bottomEchoPin;
JsonObject top = root[FPSTR(_name)];
if (top.isNull()) {
DEBUG_PRINT(FPSTR(_name));
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
return false;
}
enabled = top[FPSTR(_enabled)] | enabled;
segment_delay_ms = top[FPSTR(_segmentDelay)] | segment_delay_ms;
segment_delay_ms = (unsigned long) min((unsigned long)10000,max((unsigned long)10,(unsigned long)segment_delay_ms)); // max delay 10s
on_time_ms = top[FPSTR(_onTime)] | on_time_ms/1000;
on_time_ms = min(900,max(10,(int)on_time_ms)) * 1000; // min 10s, max 15min
useUSSensorTop = top[FPSTR(_useTopUltrasoundSensor)] | useUSSensorTop;
topPIRorTriggerPin = top[FPSTR(_topPIRorTrigger_pin)] | topPIRorTriggerPin;
topEchoPin = top[FPSTR(_topEcho_pin)] | topEchoPin;
useUSSensorBottom = top[FPSTR(_useBottomUltrasoundSensor)] | useUSSensorBottom;
bottomPIRorTriggerPin = top[FPSTR(_bottomPIRorTrigger_pin)] | bottomPIRorTriggerPin;
bottomEchoPin = top[FPSTR(_bottomEcho_pin)] | bottomEchoPin;
topMaxDist = top[FPSTR(_topEchoCm)] | topMaxDist;
topMaxDist = min(150,max(30,(int)topMaxDist)); // max distnace ~1.5m (a lag of 9ms may be expected)
bottomMaxDist = top[FPSTR(_bottomEchoCm)] | bottomMaxDist;
bottomMaxDist = min(150,max(30,(int)bottomMaxDist)); // max distance ~1.5m (a lag of 9ms may be expected)
DEBUG_PRINT(FPSTR(_name));
if (!initDone) {
// first run: reading from cfg.json
DEBUG_PRINTLN(F(" config loaded."));
} else {
// changing parameters from settings page
DEBUG_PRINTLN(F(" config (re)loaded."));
bool changed = false;
if ((oldUseUSSensorTop != useUSSensorTop) ||
(oldUseUSSensorBottom != useUSSensorBottom) ||
(oldTopAPin != topPIRorTriggerPin) ||
(oldTopBPin != topEchoPin) ||
(oldBottomAPin != bottomPIRorTriggerPin) ||
(oldBottomBPin != bottomEchoPin)) {
changed = true;
pinManager.deallocatePin(oldTopAPin, PinOwner::UM_AnimatedStaircase);
pinManager.deallocatePin(oldTopBPin, PinOwner::UM_AnimatedStaircase);
pinManager.deallocatePin(oldBottomAPin, PinOwner::UM_AnimatedStaircase);
pinManager.deallocatePin(oldBottomBPin, PinOwner::UM_AnimatedStaircase);
}
if (changed) setup();
}
// use "return !top["newestParameter"].isNull();" when updating Usermod with new features
return true;
}
/*
* Shows the delay between steps and power-off time in the "info"
* tab of the web-UI.
*/
void addToJsonInfo(JsonObject& root) {
JsonObject user = root["u"];
if (user.isNull()) {
user = root.createNestedObject("u");
}
JsonArray infoArr = user.createNestedArray(FPSTR(_name)); // name
String uiDomString = F("<button class=\"btn btn-xs\" onclick=\"requestJson({");
uiDomString += FPSTR(_name);
uiDomString += F(":{");
uiDomString += FPSTR(_enabled);
uiDomString += enabled ? F(":false}});\">") : F(":true}});\">");
uiDomString += F("<i class=\"icons ");
uiDomString += enabled ? "on" : "off";
uiDomString += F("\">&#xe08f;</i></button>");
infoArr.add(uiDomString);
}
};
// strings to reduce flash memory usage (used more than twice)
const char Animated_Staircase::_name[] PROGMEM = "staircase";
const char Animated_Staircase::_enabled[] PROGMEM = "enabled";
const char Animated_Staircase::_segmentDelay[] PROGMEM = "segment-delay-ms";
const char Animated_Staircase::_onTime[] PROGMEM = "on-time-s";
const char Animated_Staircase::_useTopUltrasoundSensor[] PROGMEM = "useTopUltrasoundSensor";
const char Animated_Staircase::_topPIRorTrigger_pin[] PROGMEM = "topPIRorTrigger_pin";
const char Animated_Staircase::_topEcho_pin[] PROGMEM = "topEcho_pin";
const char Animated_Staircase::_useBottomUltrasoundSensor[] PROGMEM = "useBottomUltrasoundSensor";
const char Animated_Staircase::_bottomPIRorTrigger_pin[] PROGMEM = "bottomPIRorTrigger_pin";
const char Animated_Staircase::_bottomEcho_pin[] PROGMEM = "bottomEcho_pin";
const char Animated_Staircase::_topEchoCm[] PROGMEM = "top-dist-cm";
const char Animated_Staircase::_bottomEchoCm[] PROGMEM = "bottom-dist-cm";

View File

@ -0,0 +1,130 @@
# Usermod Animated Staircase
This usermod makes your staircase look cool by illuminating it with an animation. It uses
PIR or ultrasonic sensors at the top and bottom of your stairs to:
- Light up the steps in the direction you're walking.
- Switch off the steps after you, in the direction of the last detected movement.
- Always switch on when one of the sensors detects movement, even if an effect
is still running. It can gracefully handle multiple people on the stairs.
The Animated Staircase can be controlled by the WLED API. Change settings such as
speed, on/off time and distance by sending an HTTP request, see below.
## WLED integration
To include this usermod in your WLED setup, you have to be able to [compile WLED from source](https://github.com/Aircoookie/WLED/wiki/Compiling-WLED).
Before compiling, you have to make the following modifications:
Edit `usermods_list.cpp`:
1. Open `wled00/usermods_list.cpp`
2. add `#include "../usermods/Animated_Staircase/Animated_Staircase.h"` to the top of the file
3. add `usermods.add(new Animated_Staircase());` to the end of the `void registerUsermods()` function.
You can configure usermod using the Usermods settings page.
Please enter GPIO pins for PIR or ultrasonic sensors (trigger and echo).
If you use PIR sensor enter -1 for echo pin.
Maximum distance for ultrasonic sensor can be configured as the time needed for an echo (see below).
## Hardware installation
1. Attach the LED strip to each step of the stairs.
2. Connect the ESP8266 pin D4 or ESP32 pin D2 to the first LED data pin at the bottom step.
3. Connect the data-out pin at the end of each strip per step to the data-in pin on the
next step, creating one large virtual LED strip.
4. Mount sensors of choice at the bottom and top of the stairs and connect them to the ESP.
5. To make sure all LEDs get enough power and have your staircase lighted evenly, power each
step from one side, using at least AWG14 or 2.5mm^2 cable. Don't connect them serial as you
do for the datacable!
You _may_ need to use 10k pull-down resistors on the selected PIR pins, depending on the sensor.
## WLED configuration
1. In the WLED UI, confgure a segment for each step. The lowest step of the stairs is the
lowest segment id.
2. Save your segments into a preset.
3. Ideally, add the preset in the config > LED setup menu to the "apply
preset **n** at boot" setting.
## Changing behavior through API
The Staircase settings can be changed through the WLED JSON api.
**NOTE:** We are using [curl](https://curl.se/) to send HTTP POSTs to the WLED API.
If you're using Windows and want to use the curl commands, replace the `\` with a `^`
or remove them and put everything on one line.
| Setting | Description | Default |
|------------------|---------------------------------------------------------------|---------|
| enabled | Enable or disable the usermod | true |
| bottom-sensor | Manually trigger a down to up animation via API | false |
| top-sensor | Manually trigger an up to down animation via API | false |
To read the current settings, open a browser to `http://xxx.xxx.xxx.xxx/json/state` (use your WLED
device IP address). The device will respond with a json object containing all WLED settings.
The staircase settings and sensor states are inside the WLED "state" element:
```json
{
"state": {
"staircase": {
"enabled": true,
"bottom-sensor": false,
"top-sensor": false
},
}
```
### Enable/disable the usermod
By disabling the usermod you will be able to keep the LED's on, independent from the sensor
activity. This enables you to play with the lights without the usermod switching them on or off.
To disable the usermod:
```bash
curl -X POST -H "Content-Type: application/json" \
-d {"staircase":{"enabled":false}} \
xxx.xxx.xxx.xxx/json/state
```
To enable the usermod again, use `"enabled":true`.
Alternatively you can use _Usermod_ Settings page where you can change other parameters as well.
### Changing animation parameters and detection range of the ultrasonic HC-SR04 sensor
Using _Usermod_ Settings page you can define different usermod parameters, includng sensor pins, delay between segment activation etc.
When an ultrasonic sensor is enabled you can enter maximum detection distance in centimeters separately for top and bottom sensors.
**Please note:** using an HC-SR04 sensor, particularly when detecting echos at longer
distances creates delays in the WLED software, _might_ introduce timing hiccups in your animation or
a less responsive web interface. It is therefore advised to keep the detection distance as short as possible.
### Animation triggering through the API
In addition to activation by one of the stair sensors, you can also trigger the animation manually
via the API. To simulate triggering the bottom sensor, use:
```bash
curl -X POST -H "Content-Type: application/json" \
-d '{"staircase":{"bottom-sensor":true}}' \
xxx.xxx.xxx.xxx/json/state
```
Likewise, to trigger the top sensor:
```bash
curl -X POST -H "Content-Type: application/json" \
-d '{"staircase":{"top-sensor":true}}' \
xxx.xxx.xxx.xxx/json/state
```
**MQTT**
You can publish a message with either `up` or `down` on topic `/swipe` to trigger animation.
You can also use `on` or `off` for enabling or disabling the usermod.
Have fun with this usermod.<br/>
www.rolfje.com
Modifications @blazoncek
## Change log
2021-04
* Adaptation for runtime configuration.

View File

@ -0,0 +1,5 @@
Usermod to allow WLED to receive via UDP port from RGB.NET (and therefore add as a device to be controlled within artemis on PC)
This is only a very simple code to support a single led strip, it does not support the full function of the RGB.NET sketch for esp8266 only what is needed to be used with Artemis. It will show as a ws281x device in artemis when you provide the correct hostname or ip. Artemis queries the number of LEDs via the web interface (/config) but communication to set the LEDs is all done via the UDP interface.
To install, copy the usermod.cpp file to wled00 folder and recompile

View File

@ -0,0 +1,93 @@
/*
* RGB.NET (artemis) receiver
*
* This works via the UDP, http is not supported apart from reporting LED count
*
*
*/
#include "wled.h"
#include <WiFiUdp.h>
WiFiUDP UDP;
const unsigned int RGBNET_localUdpPort = 1872; // local port to listen on
unsigned char RGBNET_packet[770];
long lastTime = 0;
int delayMs = 10;
bool isRGBNETUDPEnabled;
void RGBNET_readValues() {
int RGBNET_packetSize = UDP.parsePacket();
if (RGBNET_packetSize) {
// receive incoming UDP packets
int sequenceNumber = UDP.read();
int channel = UDP.read();
//channel data is not used we only supports one channel
int len = UDP.read(RGBNET_packet, strip.getLengthTotal()*3);
if(len==0){
return;
}
for (int i = 0; i < len; i=i+3) {
strip.setPixelColor(i/3, RGBNET_packet[i], RGBNET_packet[i+1], RGBNET_packet[i+2], 0);
}
//strip.show();
}
}
//update LED strip
void RGBNET_show() {
strip.show();
lastTime = millis();
}
//This function provides a json with info on the number of LEDs connected
// it is needed by artemis to know how many LEDs to display on the surface
void handleConfig(AsyncWebServerRequest *request)
{
String config = (String)"{\
\"channels\": [\
{\
\"channel\": 1,\
\"leds\": " + strip.getLengthTotal() + "\
},\
{\
\"channel\": 2,\
\"leds\": " + "0" + "\
},\
{\
\"channel\": 3,\
\"leds\": " + "0" + "\
},\
{\
\"channel\": 4,\
\"leds\": " + "0" + "\
}\
]\
}";
request->send(200, "application/json", config);
}
void userSetup()
{
server.on("/config", HTTP_GET, [](AsyncWebServerRequest *request){
handleConfig(request);
});
}
void userConnected()
{
// new wifi, who dis?
UDP.begin(RGBNET_localUdpPort);
isRGBNETUDPEnabled = true;
}
void userLoop()
{
RGBNET_readValues();
if (millis()-lastTime > delayMs) {
RGBNET_show();
}
}

View File

@ -0,0 +1,49 @@
# BH1750 usermod
This usermod will read from an ambient light sensor like the BH1750.
The luminance is displayed in both the Info section of the web UI, as well as published to the `/luminance` MQTT topic if enabled.
## Dependencies
- Libraries
- `claws/BH1750 @^1.2.0`
- This must be added under `lib_deps` in your `platformio.ini` (or `platformio_override.ini`).
- Data is published over MQTT - make sure you've enabled the MQTT sync interface.
## Compiliation
To enable, compile with `USERMOD_BH1750` defined (e.g. in `platformio_override.ini`)
```ini
[env:usermod_BH1750_d1_mini]
extends = env:d1_mini
build_flags =
${common.build_flags_esp8266}
-D USERMOD_BH1750
lib_deps =
${esp8266.lib_deps}
claws/BH1750 @ ^1.2.0
```
### Configuration Options
The following settings can be set at compile-time but are configurable on the usermod menu (except First Measurement time):
* `USERMOD_BH1750_MAX_MEASUREMENT_INTERVAL` - the max number of milliseconds between measurements, defaults to 10000ms
* `USERMOD_BH1750_MIN_MEASUREMENT_INTERVAL` - the min number of milliseconds between measurements, defaults to 500ms
* `USERMOD_BH1750_OFFSET_VALUE` - the offset value to report on, defaults to 1
* `USERMOD_BH1750_FIRST_MEASUREMENT_AT` - the number of milliseconds after boot to take first measurement, defaults to 10000 ms
In addition, the Usermod screen allows you to:
- enable/disable the usermod
- Enable Home Assistant Discovery of usermod
- Configure the SCL/SDA pins
## API
The following method is available to interact with the usermod from other code modules:
- `getIlluminance` read the brightness from the sensor
## Change Log
Jul 2022
- Added Home Assistant Discovery
- Implemented PinManager to register pins
- Made pins configurable in usermod menu
- Added API call to read luminance from other modules
- Enhanced info-screen outputs
- Updated `readme.md`

View File

@ -0,0 +1,252 @@
// force the compiler to show a warning to confirm that this file is included
#warning **** Included USERMOD_BH1750 ****
#ifndef WLED_ENABLE_MQTT
#error "This user mod requires MQTT to be enabled."
#endif
#pragma once
#include "wled.h"
#include <BH1750.h>
// the max frequency to check photoresistor, 10 seconds
#ifndef USERMOD_BH1750_MAX_MEASUREMENT_INTERVAL
#define USERMOD_BH1750_MAX_MEASUREMENT_INTERVAL 10000
#endif
// the min frequency to check photoresistor, 500 ms
#ifndef USERMOD_BH1750_MIN_MEASUREMENT_INTERVAL
#define USERMOD_BH1750_MIN_MEASUREMENT_INTERVAL 500
#endif
// how many seconds after boot to take first measurement, 10 seconds
#ifndef USERMOD_BH1750_FIRST_MEASUREMENT_AT
#define USERMOD_BH1750_FIRST_MEASUREMENT_AT 10000
#endif
// only report if differance grater than offset value
#ifndef USERMOD_BH1750_OFFSET_VALUE
#define USERMOD_BH1750_OFFSET_VALUE 1
#endif
class Usermod_BH1750 : public Usermod
{
private:
int8_t offset = USERMOD_BH1750_OFFSET_VALUE;
unsigned long maxReadingInterval = USERMOD_BH1750_MAX_MEASUREMENT_INTERVAL;
unsigned long minReadingInterval = USERMOD_BH1750_MIN_MEASUREMENT_INTERVAL;
unsigned long lastMeasurement = UINT32_MAX - (USERMOD_BH1750_MAX_MEASUREMENT_INTERVAL - USERMOD_BH1750_FIRST_MEASUREMENT_AT);
unsigned long lastSend = UINT32_MAX - (USERMOD_BH1750_MAX_MEASUREMENT_INTERVAL - USERMOD_BH1750_FIRST_MEASUREMENT_AT);
// flag to indicate we have finished the first readLightLevel call
// allows this library to report to the user how long until the first
// measurement
bool getLuminanceComplete = false;
// flag set at startup
bool enabled = true;
// strings to reduce flash memory usage (used more than twice)
static const char _name[];
static const char _enabled[];
static const char _maxReadInterval[];
static const char _minReadInterval[];
static const char _offset[];
static const char _HomeAssistantDiscovery[];
bool initDone = false;
bool sensorFound = false;
// Home Assistant and MQTT
String mqttLuminanceTopic = F("");
bool mqttInitialized = false;
bool HomeAssistantDiscovery = true; // Publish Home Assistant Discovery messages
BH1750 lightMeter;
float lastLux = -1000;
bool checkBoundSensor(float newValue, float prevValue, float maxDiff)
{
return isnan(prevValue) || newValue <= prevValue - maxDiff || newValue >= prevValue + maxDiff || (newValue == 0.0 && prevValue > 0.0);
}
// set up Home Assistant discovery entries
void _mqttInitialize()
{
mqttLuminanceTopic = String(mqttDeviceTopic) + F("/brightness");
if (HomeAssistantDiscovery) _createMqttSensor(F("Brightness"), mqttLuminanceTopic, F("Illuminance"), F(" lx"));
}
// Create an MQTT Sensor for Home Assistant Discovery purposes, this includes a pointer to the topic that is published to in the Loop.
void _createMqttSensor(const String &name, const String &topic, const String &deviceClass, const String &unitOfMeasurement)
{
String t = String(F("homeassistant/sensor/")) + mqttClientID + F("/") + name + F("/config");
StaticJsonDocument<600> doc;
doc[F("name")] = String(serverDescription) + F(" ") + name;
doc[F("state_topic")] = topic;
doc[F("unique_id")] = String(mqttClientID) + name;
if (unitOfMeasurement != "")
doc[F("unit_of_measurement")] = unitOfMeasurement;
if (deviceClass != "")
doc[F("device_class")] = deviceClass;
doc[F("expire_after")] = 1800;
JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device
device[F("name")] = serverDescription;
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
device[F("manufacturer")] = F("WLED");
device[F("model")] = F("FOSS");
device[F("sw_version")] = versionString;
String temp;
serializeJson(doc, temp);
DEBUG_PRINTLN(t);
DEBUG_PRINTLN(temp);
mqtt->publish(t.c_str(), 0, true, temp.c_str());
}
public:
void setup()
{
if (i2c_scl<0 || i2c_sda<0) { enabled = false; return; }
sensorFound = lightMeter.begin();
initDone = true;
}
void loop()
{
if ((!enabled) || strip.isUpdating())
return;
unsigned long now = millis();
// check to see if we are due for taking a measurement
// lastMeasurement will not be updated until the conversion
// is complete the the reading is finished
if (now - lastMeasurement < minReadingInterval)
{
return;
}
bool shouldUpdate = now - lastSend > maxReadingInterval;
float lux = lightMeter.readLightLevel();
lastMeasurement = millis();
getLuminanceComplete = true;
if (shouldUpdate || checkBoundSensor(lux, lastLux, offset))
{
lastLux = lux;
lastSend = millis();
#ifndef WLED_DISABLE_MQTT
if (WLED_MQTT_CONNECTED)
{
if (!mqttInitialized)
{
_mqttInitialize();
mqttInitialized = true;
}
mqtt->publish(mqttLuminanceTopic.c_str(), 0, true, String(lux).c_str());
DEBUG_PRINTLN(F("Brightness: ") + String(lux) + F("lx"));
}
else
{
DEBUG_PRINTLN(F("Missing MQTT connection. Not publishing data"));
}
#endif
}
}
inline float getIlluminance() {
return (float)lastLux;
}
void addToJsonInfo(JsonObject &root)
{
JsonObject user = root[F("u")];
if (user.isNull())
user = root.createNestedObject(F("u"));
JsonArray lux_json = user.createNestedArray(F("Luminance"));
if (!enabled) {
lux_json.add(F("disabled"));
} else if (!sensorFound) {
// if no sensor
lux_json.add(F("BH1750 "));
lux_json.add(F("Not Found"));
} else if (!getLuminanceComplete) {
// if we haven't read the sensor yet, let the user know
// that we are still waiting for the first measurement
lux_json.add((USERMOD_BH1750_FIRST_MEASUREMENT_AT - millis()) / 1000);
lux_json.add(F(" sec until read"));
return;
} else {
lux_json.add(lastLux);
lux_json.add(F(" lx"));
}
}
// (called from set.cpp) stores persistent properties to cfg.json
void addToConfig(JsonObject &root)
{
// we add JSON object.
JsonObject top = root.createNestedObject(FPSTR(_name)); // usermodname
top[FPSTR(_enabled)] = enabled;
top[FPSTR(_maxReadInterval)] = maxReadingInterval;
top[FPSTR(_minReadInterval)] = minReadingInterval;
top[FPSTR(_HomeAssistantDiscovery)] = HomeAssistantDiscovery;
top[FPSTR(_offset)] = offset;
DEBUG_PRINTLN(F("BH1750 config saved."));
}
// called before setup() to populate properties from values stored in cfg.json
bool readFromConfig(JsonObject &root)
{
// we look for JSON object.
JsonObject top = root[FPSTR(_name)];
if (top.isNull())
{
DEBUG_PRINT(FPSTR(_name));
DEBUG_PRINT(F("BH1750"));
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
return false;
}
bool configComplete = !top.isNull();
configComplete &= getJsonValue(top[FPSTR(_enabled)], enabled, false);
configComplete &= getJsonValue(top[FPSTR(_maxReadInterval)], maxReadingInterval, 10000); //ms
configComplete &= getJsonValue(top[FPSTR(_minReadInterval)], minReadingInterval, 500); //ms
configComplete &= getJsonValue(top[FPSTR(_HomeAssistantDiscovery)], HomeAssistantDiscovery, false);
configComplete &= getJsonValue(top[FPSTR(_offset)], offset, 1);
DEBUG_PRINT(FPSTR(_name));
if (!initDone) {
DEBUG_PRINTLN(F(" config loaded."));
} else {
DEBUG_PRINTLN(F(" config (re)loaded."));
}
return configComplete;
}
uint16_t getId()
{
return USERMOD_ID_BH1750;
}
};
// strings to reduce flash memory usage (used more than twice)
const char Usermod_BH1750::_name[] PROGMEM = "BH1750";
const char Usermod_BH1750::_enabled[] PROGMEM = "enabled";
const char Usermod_BH1750::_maxReadInterval[] PROGMEM = "max-read-interval-ms";
const char Usermod_BH1750::_minReadInterval[] PROGMEM = "min-read-interval-ms";
const char Usermod_BH1750::_HomeAssistantDiscovery[] PROGMEM = "HomeAssistantDiscoveryLux";
const char Usermod_BH1750::_offset[] PROGMEM = "offset-lx";

View File

@ -0,0 +1,90 @@
# Usermod BME280
This Usermod is designed to read a `BME280` or `BMP280` sensor and output the following:
- Temperature
- Humidity (`BME280` only)
- Pressure
- Heat Index (`BME280` only)
- Dew Point (`BME280` only)
Configuration is performed via the Usermod menu. There are no parameters to set in code! The following settings can be configured in the Usermod Menu:
- Temperature Decimals (number of decimal places to output)
- Humidity Decimals
- Pressure Decimals
- Temperature Interval (how many seconds between temperature and humidity measurements)
- Pressure Interval
- Publish Always (turn off to only publish changes, on to publish whether or not value changed)
- Use Celsius (turn off to use Fahrenheit)
- Home Assistant Discovery (turn on to sent MQTT Discovery entries for Home Assistant)
- SCL/SDA GPIO Pins
Dependencies
- Libraries
- `BME280@~3.0.0` (by [finitespace](https://github.com/finitespace/BME280))
- `Wire`
- These must be added under `lib_deps` in your `platform.ini` (or `platform_override.ini`).
- Data is published over MQTT - make sure you've enabled the MQTT sync interface.
- This usermod also writes to serial (GPIO1 on ESP8266). Please make sure nothing else is listening to the serial TX pin or your board will get confused by log messages!
In addition to outputting via MQTT, you can read the values from the Info Screen on the dashboard page of the device's web interface.
Methods also exist to read the read/calculated values from other WLED modules through code.
- `getTemperatureC()`
- `getTemperatureF()`
- `getHumidity()`
- `getPressure()`
- `getDewPointC()`
- `getDewPointF()`
- `getHeatIndexC()`
- `getHeatIndexF()`
# Compiling
To enable, compile with `USERMOD_BME280` defined (e.g. in `platformio_override.ini`)
```ini
[env:usermod_bme280_d1_mini]
extends = env:d1_mini
build_flags =
${common.build_flags_esp8266}
-D USERMOD_BME280
lib_deps =
${esp8266.lib_deps}
BME280@~3.0.0
Wire
```
# MQTT
MQTT topics are as follows (`<deviceTopic>` is set in MQTT section of Sync Setup menu):
Measurement type | MQTT topic
--- | ---
Temperature | `<deviceTopic>/temperature`
Humidity | `<deviceTopic>/humidity`
Pressure | `<deviceTopic>/pressure`
Heat index | `<deviceTopic>/heat_index`
Dew point | `<deviceTopic>/dew_point`
If you are using Home Assistant, and `Home Assistant Discovery` is turned on, Home Assistant should automatically detect a new device, provided you have the MQTT integration installed. The device is separate from the main WLED device and will contain sensors for Pressure, Humidity, Temperature, Dew Point and Heat Index.
# Revision History
Jul 2022
- Added Home Assistant Discovery
- Added API interface to output data
- Removed compile-time variables
- Added usermod menu interface
- Added value outputs to info screen
- Updated `readme.md`
- Registered usermod
- Implemented PinManager for usermod
- Implemented reallocation of pins without reboot
Apr 2021
- Added `Publish Always` option
Dec 2020
- Ported to V2 Usermod format
- Customizable `measure intervals`
- Customizable number of `decimal places` in published sensor values
- Pressure measured in units of hPa instead of Pa
- Calculation of heat index (apparent temperature) and dew point
- `16x oversampling` of sensor during measurement
- Values only published if they are different from the previous value

View File

@ -0,0 +1,456 @@
// force the compiler to show a warning to confirm that this file is included
#warning **** Included USERMOD_BME280 version 2.0 ****
#ifndef WLED_ENABLE_MQTT
#error "This user mod requires MQTT to be enabled."
#endif
#pragma once
#include "wled.h"
#include <Arduino.h>
#include <BME280I2C.h> // BME280 sensor
#include <EnvironmentCalculations.h> // BME280 extended measurements
class UsermodBME280 : public Usermod
{
private:
// NOTE: Do not implement any compile-time variables, anything the user needs to configure
// should be configurable from the Usermod menu using the methods below
// key settings set via usermod menu
uint8_t TemperatureDecimals = 0; // Number of decimal places in published temperaure values
uint8_t HumidityDecimals = 0; // Number of decimal places in published humidity values
uint8_t PressureDecimals = 0; // Number of decimal places in published pressure values
uint16_t TemperatureInterval = 5; // Interval to measure temperature (and humidity, dew point if available) in seconds
uint16_t PressureInterval = 300; // Interval to measure pressure in seconds
bool PublishAlways = false; // Publish values even when they have not changed
bool UseCelsius = true; // Use Celsius for Reporting
bool HomeAssistantDiscovery = false; // Publish Home Assistant Device Information
bool enabled = true;
// set the default pins based on the architecture, these get overridden by Usermod menu settings
#ifdef ESP8266
//uint8_t RST_PIN = 16; // Uncoment for Heltec WiFi-Kit-8
#endif
bool initDone = false;
// BME280 sensor settings
BME280I2C::Settings settings{
BME280::OSR_X16, // Temperature oversampling x16
BME280::OSR_X16, // Humidity oversampling x16
BME280::OSR_X16, // Pressure oversampling x16
// Defaults
BME280::Mode_Forced,
BME280::StandbyTime_1000ms,
BME280::Filter_Off,
BME280::SpiEnable_False,
BME280I2C::I2CAddr_0x76 // I2C address. I2C specific. Default 0x76
};
BME280I2C bme{settings};
uint8_t sensorType;
// Measurement timers
long timer;
long lastTemperatureMeasure = 0;
long lastPressureMeasure = 0;
// Current sensor values
float sensorTemperature;
float sensorHumidity;
float sensorHeatIndex;
float sensorDewPoint;
float sensorPressure;
String tempScale;
// Track previous sensor values
float lastTemperature;
float lastHumidity;
float lastHeatIndex;
float lastDewPoint;
float lastPressure;
// MQTT topic strings for publishing Home Assistant discovery topics
bool mqttInitialized = false;
// strings to reduce flash memory usage (used more than twice)
static const char _name[];
static const char _enabled[];
// Read the BME280/BMP280 Sensor (which one runs depends on whether Celsius or Farenheit being set in Usermod Menu)
void UpdateBME280Data(int SensorType)
{
float _temperature, _humidity, _pressure;
if (UseCelsius) {
BME280::TempUnit tempUnit(BME280::TempUnit_Celsius);
EnvironmentCalculations::TempUnit envTempUnit(EnvironmentCalculations::TempUnit_Celsius);
BME280::PresUnit presUnit(BME280::PresUnit_hPa);
bme.read(_pressure, _temperature, _humidity, tempUnit, presUnit);
sensorTemperature = _temperature;
sensorHumidity = _humidity;
sensorPressure = _pressure;
tempScale = F("°C");
if (sensorType == 1)
{
sensorHeatIndex = EnvironmentCalculations::HeatIndex(_temperature, _humidity, envTempUnit);
sensorDewPoint = EnvironmentCalculations::DewPoint(_temperature, _humidity, envTempUnit);
}
} else {
BME280::TempUnit tempUnit(BME280::TempUnit_Fahrenheit);
EnvironmentCalculations::TempUnit envTempUnit(EnvironmentCalculations::TempUnit_Fahrenheit);
BME280::PresUnit presUnit(BME280::PresUnit_hPa);
bme.read(_pressure, _temperature, _humidity, tempUnit, presUnit);
sensorTemperature = _temperature;
sensorHumidity = _humidity;
sensorPressure = _pressure;
tempScale = F("°F");
if (sensorType == 1)
{
sensorHeatIndex = EnvironmentCalculations::HeatIndex(_temperature, _humidity, envTempUnit);
sensorDewPoint = EnvironmentCalculations::DewPoint(_temperature, _humidity, envTempUnit);
}
}
}
// Procedure to define all MQTT discovery Topics
void _mqttInitialize()
{
char mqttTemperatureTopic[128];
char mqttHumidityTopic[128];
char mqttPressureTopic[128];
char mqttHeatIndexTopic[128];
char mqttDewPointTopic[128];
snprintf_P(mqttTemperatureTopic, 127, PSTR("%s/temperature"), mqttDeviceTopic);
snprintf_P(mqttPressureTopic, 127, PSTR("%s/pressure"), mqttDeviceTopic);
snprintf_P(mqttHumidityTopic, 127, PSTR("%s/humidity"), mqttDeviceTopic);
snprintf_P(mqttHeatIndexTopic, 127, PSTR("%s/heat_index"), mqttDeviceTopic);
snprintf_P(mqttDewPointTopic, 127, PSTR("%s/dew_point"), mqttDeviceTopic);
if (HomeAssistantDiscovery) {
_createMqttSensor(F("Temperature"), mqttTemperatureTopic, "temperature", tempScale);
_createMqttSensor(F("Pressure"), mqttPressureTopic, "pressure", F("hPa"));
_createMqttSensor(F("Humidity"), mqttHumidityTopic, "humidity", F("%"));
_createMqttSensor(F("HeatIndex"), mqttHeatIndexTopic, "temperature", tempScale);
_createMqttSensor(F("DewPoint"), mqttDewPointTopic, "temperature", tempScale);
}
}
// Create an MQTT Sensor for Home Assistant Discovery purposes, this includes a pointer to the topic that is published to in the Loop.
void _createMqttSensor(const String &name, const String &topic, const String &deviceClass, const String &unitOfMeasurement)
{
String t = String(F("homeassistant/sensor/")) + mqttClientID + F("/") + name + F("/config");
StaticJsonDocument<600> doc;
doc[F("name")] = String(serverDescription) + " " + name;
doc[F("state_topic")] = topic;
doc[F("unique_id")] = String(mqttClientID) + name;
if (unitOfMeasurement != "")
doc[F("unit_of_measurement")] = unitOfMeasurement;
if (deviceClass != "")
doc[F("device_class")] = deviceClass;
doc[F("expire_after")] = 1800;
JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device
device[F("name")] = serverDescription;
device[F("identifiers")] = "wled-sensor-" + String(mqttClientID);
device[F("manufacturer")] = F("WLED");
device[F("model")] = F("FOSS");
device[F("sw_version")] = versionString;
String temp;
serializeJson(doc, temp);
DEBUG_PRINTLN(t);
DEBUG_PRINTLN(temp);
mqtt->publish(t.c_str(), 0, true, temp.c_str());
}
void publishMqtt(const char *topic, const char* state) {
//Check if MQTT Connected, otherwise it will crash the 8266
if (WLED_MQTT_CONNECTED){
char subuf[128];
snprintf_P(subuf, 127, PSTR("%s/%s"), mqttDeviceTopic, topic);
mqtt->publish(subuf, 0, false, state);
}
}
public:
void setup()
{
if (i2c_scl<0 || i2c_sda<0) { enabled = false; sensorType = 0; return; }
if (!bme.begin())
{
sensorType = 0;
DEBUG_PRINTLN(F("Could not find BME280 I2C sensor!"));
}
else
{
switch (bme.chipModel())
{
case BME280::ChipModel_BME280:
sensorType = 1;
DEBUG_PRINTLN(F("Found BME280 sensor! Success."));
break;
case BME280::ChipModel_BMP280:
sensorType = 2;
DEBUG_PRINTLN(F("Found BMP280 sensor! No Humidity available."));
break;
default:
sensorType = 0;
DEBUG_PRINTLN(F("Found UNKNOWN sensor! Error!"));
}
}
initDone=true;
}
void loop()
{
if (!enabled || strip.isUpdating()) return;
// BME280 sensor MQTT publishing
// Check if sensor present and Connected, otherwise it will crash the MCU
if (sensorType != 0)
{
// Timer to fetch new temperature, humidity and pressure data at intervals
timer = millis();
if (timer - lastTemperatureMeasure >= TemperatureInterval * 1000)
{
lastTemperatureMeasure = timer;
UpdateBME280Data(sensorType);
float temperature = roundf(sensorTemperature * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
float humidity, heatIndex, dewPoint;
// If temperature has changed since last measure, create string populated with device topic
// from the UI and values read from sensor, then publish to broker
if (temperature != lastTemperature || PublishAlways)
{
publishMqtt("temperature", String(temperature, TemperatureDecimals).c_str());
}
lastTemperature = temperature; // Update last sensor temperature for next loop
if (sensorType == 1) // Only if sensor is a BME280
{
humidity = roundf(sensorHumidity * powf(10, HumidityDecimals)) / powf(10, HumidityDecimals);
heatIndex = roundf(sensorHeatIndex * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
dewPoint = roundf(sensorDewPoint * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
if (humidity != lastHumidity || PublishAlways)
{
publishMqtt("humidity", String(humidity, HumidityDecimals).c_str());
}
if (heatIndex != lastHeatIndex || PublishAlways)
{
publishMqtt("heat_index", String(heatIndex, TemperatureDecimals).c_str());
}
if (dewPoint != lastDewPoint || PublishAlways)
{
publishMqtt("dew_point", String(dewPoint, TemperatureDecimals).c_str());
}
lastHumidity = humidity;
lastHeatIndex = heatIndex;
lastDewPoint = dewPoint;
}
}
if (timer - lastPressureMeasure >= PressureInterval * 1000)
{
lastPressureMeasure = timer;
float pressure = roundf(sensorPressure * powf(10, PressureDecimals)) / powf(10, PressureDecimals);
if (pressure != lastPressure || PublishAlways)
{
publishMqtt("pressure", String(pressure, PressureDecimals).c_str());
}
lastPressure = pressure;
}
}
}
void onMqttConnect(bool sessionPresent)
{
if (WLED_MQTT_CONNECTED && !mqttInitialized)
{
_mqttInitialize();
mqttInitialized = true;
}
}
/*
* API calls te enable data exchange between WLED modules
*/
inline float getTemperatureC() {
if (UseCelsius) {
return (float)roundf(sensorTemperature * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
} else {
return (float)roundf(sensorTemperature * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals) * 1.8f + 32;
}
}
inline float getTemperatureF() {
if (UseCelsius) {
return ((float)roundf(sensorTemperature * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals) -32) * 0.56f;
} else {
return (float)roundf(sensorTemperature * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
}
}
inline float getHumidity() {
return (float)roundf(sensorHumidity * powf(10, HumidityDecimals));
}
inline float getPressure() {
return (float)roundf(sensorPressure * powf(10, PressureDecimals));
}
inline float getDewPointC() {
if (UseCelsius) {
return (float)roundf(sensorDewPoint * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
} else {
return (float)roundf(sensorDewPoint * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals) * 1.8f + 32;
}
}
inline float getDewPointF() {
if (UseCelsius) {
return ((float)roundf(sensorDewPoint * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals) -32) * 0.56f;
} else {
return (float)roundf(sensorDewPoint * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
}
}
inline float getHeatIndexC() {
if (UseCelsius) {
return (float)roundf(sensorHeatIndex * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
} else {
return (float)roundf(sensorHeatIndex * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals) * 1.8f + 32;
}
}
inline float getHeatIndexF() {
if (UseCelsius) {
return ((float)roundf(sensorHeatIndex * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals) -32) * 0.56f;
} else {
return (float)roundf(sensorHeatIndex * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals);
}
}
// Publish Sensor Information to Info Page
void addToJsonInfo(JsonObject &root)
{
JsonObject user = root[F("u")];
if (user.isNull()) user = root.createNestedObject(F("u"));
if (sensorType==0) //No Sensor
{
// if we sensor not detected, let the user know
JsonArray temperature_json = user.createNestedArray(F("BME/BMP280 Sensor"));
temperature_json.add(F("Not Found"));
}
else if (sensorType==2) //BMP280
{
JsonArray temperature_json = user.createNestedArray(F("Temperature"));
JsonArray pressure_json = user.createNestedArray(F("Pressure"));
temperature_json.add(roundf(sensorTemperature * powf(10, TemperatureDecimals)));
temperature_json.add(tempScale);
pressure_json.add(roundf(sensorPressure * powf(10, PressureDecimals)));
pressure_json.add(F("hPa"));
}
else if (sensorType==1) //BME280
{
JsonArray temperature_json = user.createNestedArray(F("Temperature"));
JsonArray humidity_json = user.createNestedArray(F("Humidity"));
JsonArray pressure_json = user.createNestedArray(F("Pressure"));
JsonArray heatindex_json = user.createNestedArray(F("Heat Index"));
JsonArray dewpoint_json = user.createNestedArray(F("Dew Point"));
temperature_json.add(roundf(sensorTemperature * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals));
temperature_json.add(tempScale);
humidity_json.add(roundf(sensorHumidity * powf(10, HumidityDecimals)));
humidity_json.add(F("%"));
pressure_json.add(roundf(sensorPressure * powf(10, PressureDecimals)));
pressure_json.add(F("hPa"));
heatindex_json.add(roundf(sensorHeatIndex * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals));
heatindex_json.add(tempScale);
dewpoint_json.add(roundf(sensorDewPoint * powf(10, TemperatureDecimals)) / powf(10, TemperatureDecimals));
dewpoint_json.add(tempScale);
}
return;
}
// Save Usermod Config Settings
void addToConfig(JsonObject& root)
{
JsonObject top = root.createNestedObject(FPSTR(_name));
top[FPSTR(_enabled)] = enabled;
top[F("TemperatureDecimals")] = TemperatureDecimals;
top[F("HumidityDecimals")] = HumidityDecimals;
top[F("PressureDecimals")] = PressureDecimals;
top[F("TemperatureInterval")] = TemperatureInterval;
top[F("PressureInterval")] = PressureInterval;
top[F("PublishAlways")] = PublishAlways;
top[F("UseCelsius")] = UseCelsius;
top[F("HomeAssistantDiscovery")] = HomeAssistantDiscovery;
DEBUG_PRINTLN(F("BME280 config saved."));
}
// Read Usermod Config Settings
bool readFromConfig(JsonObject& root)
{
// default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor
// setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed)
JsonObject top = root[FPSTR(_name)];
if (top.isNull()) {
DEBUG_PRINT(F(_name));
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
return false;
}
bool configComplete = !top.isNull();
configComplete &= getJsonValue(top[FPSTR(_enabled)], enabled);
// A 3-argument getJsonValue() assigns the 3rd argument as a default value if the Json value is missing
configComplete &= getJsonValue(top[F("TemperatureDecimals")], TemperatureDecimals, 1);
configComplete &= getJsonValue(top[F("HumidityDecimals")], HumidityDecimals, 0);
configComplete &= getJsonValue(top[F("PressureDecimals")], PressureDecimals, 0);
configComplete &= getJsonValue(top[F("TemperatureInterval")], TemperatureInterval, 30);
configComplete &= getJsonValue(top[F("PressureInterval")], PressureInterval, 30);
configComplete &= getJsonValue(top[F("PublishAlways")], PublishAlways, false);
configComplete &= getJsonValue(top[F("UseCelsius")], UseCelsius, true);
configComplete &= getJsonValue(top[F("HomeAssistantDiscovery")], HomeAssistantDiscovery, false);
DEBUG_PRINT(FPSTR(_name));
if (!initDone) {
// first run: reading from cfg.json
DEBUG_PRINTLN(F(" config loaded."));
} else {
DEBUG_PRINTLN(F(" config (re)loaded."));
// changing parameters from settings page
}
return configComplete;
}
uint16_t getId() {
return USERMOD_ID_BME280;
}
};
const char UsermodBME280::_name[] PROGMEM = "BME280/BMP280";
const char UsermodBME280::_enabled[] PROGMEM = "enabled";

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -0,0 +1,81 @@
// pin defaults
// for the esp32 it is best to use the ADC1: GPIO32 - GPIO39
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html
#ifndef USERMOD_BATTERY_MEASUREMENT_PIN
#ifdef ARDUINO_ARCH_ESP32
#define USERMOD_BATTERY_MEASUREMENT_PIN 35
#else //ESP8266 boards
#define USERMOD_BATTERY_MEASUREMENT_PIN A0
#endif
#endif
// the frequency to check the battery, 30 sec
#ifndef USERMOD_BATTERY_MEASUREMENT_INTERVAL
#define USERMOD_BATTERY_MEASUREMENT_INTERVAL 30000
#endif
// default for 18650 battery
// https://batterybro.com/blogs/18650-wholesale-battery-reviews/18852515-when-to-recycle-18650-batteries-and-how-to-start-a-collection-center-in-your-vape-shop
// Discharge voltage: 2.5 volt + .1 for personal safety
#ifndef USERMOD_BATTERY_MIN_VOLTAGE
#ifdef USERMOD_BATTERY_USE_LIPO
// LiPo "1S" Batteries should not be dischared below 3V !!
#define USERMOD_BATTERY_MIN_VOLTAGE 3.2f
#else
#define USERMOD_BATTERY_MIN_VOLTAGE 2.6f
#endif
#endif
//the default ratio for the voltage divider
#ifndef USERMOD_BATTERY_VOLTAGE_MULTIPLIER
#ifdef ARDUINO_ARCH_ESP32
#define USERMOD_BATTERY_VOLTAGE_MULTIPLIER 2.0f
#else //ESP8266 boards
#define USERMOD_BATTERY_VOLTAGE_MULTIPLIER 4.2f
#endif
#endif
#ifndef USERMOD_BATTERY_MAX_VOLTAGE
#define USERMOD_BATTERY_MAX_VOLTAGE 4.2f
#endif
// a common capacity for single 18650 battery cells is between 2500 and 3600 mAh
#ifndef USERMOD_BATTERY_TOTAL_CAPACITY
#define USERMOD_BATTERY_TOTAL_CAPACITY 3100
#endif
// offset or calibration value to fine tune the calculated voltage
#ifndef USERMOD_BATTERY_CALIBRATION
#define USERMOD_BATTERY_CALIBRATION 0
#endif
// calculate remaining time / the time that is left before the battery runs out of power
// #ifndef USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED
// #define USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED false
// #endif
// auto-off feature
#ifndef USERMOD_BATTERY_AUTO_OFF_ENABLED
#define USERMOD_BATTERY_AUTO_OFF_ENABLED true
#endif
#ifndef USERMOD_BATTERY_AUTO_OFF_THRESHOLD
#define USERMOD_BATTERY_AUTO_OFF_THRESHOLD 10
#endif
// low power indication feature
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED true
#endif
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET 0
#endif
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD 20
#endif
#ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION
#define USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION 5
#endif

112
usermods/Battery/readme.md Normal file
View File

@ -0,0 +1,112 @@
<p align="center">
<img width="700" src="assets/battery_usermod_logo.png">
</p>
# Welcome to the battery usermod! 🔋
Enables battery level monitoring of your project.
For this to work, the positive side of the (18650) battery must be connected to pin `A0` of the d1 mini/esp8266 with a 100k Ohm resistor (see [Useful Links](#useful-links)).
If you have an ESP32 board, connect the positive side of the battery to ADC1 (GPIO32 - GPIO39)
<p align="center">
<img width="500" src="assets/battery_info_screen.png">
</p>
## ⚙️ Features
- 💯 Displays current battery voltage
- 🚥 Displays battery level
- 🚫 Auto-off with configurable Threshold
- 🚨 Low power indicator with many configuration posibilities
## 🎈 Installation
define `USERMOD_BATTERY` in `wled00/my_config.h`
### Example wiring
<p align="center">
<img width="300" src="assets/battery_connection_schematic_01.png">
</p>
### Define Your Options
| Name | Unit | Description |
| ----------------------------------------------- | ----------- |-------------------------------------------------------------------------------------- |
| `USERMOD_BATTERY` | | define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp |
| `USERMOD_BATTERY_USE_LIPO` | | define this (in `my_config.h`) if you use LiPo rechargeables (1S) |
| `USERMOD_BATTERY_MEASUREMENT_PIN` | | defaults to A0 on ESP8266 and GPIO35 on ESP32 |
| `USERMOD_BATTERY_MEASUREMENT_INTERVAL` | ms | battery check interval. defaults to 30 seconds |
| `USERMOD_BATTERY_MIN_VOLTAGE` | v | minimum battery voltage. default is 2.6 (18650 battery standard) |
| `USERMOD_BATTERY_MAX_VOLTAGE` | v | maximum battery voltage. default is 4.2 (18650 battery standard) |
| `USERMOD_BATTERY_TOTAL_CAPACITY` | mAh | the capacity of all cells in parralel sumed up |
| `USERMOD_BATTERY_CALIBRATION` | | offset / calibration number, fine tune the measured voltage by the microcontroller |
| Auto-Off | --- | --- |
| `USERMOD_BATTERY_AUTO_OFF_ENABLED` | true/false | enables auto-off |
| `USERMOD_BATTERY_AUTO_OFF_THRESHOLD` | % (0-100) | when this threshold is reached master power turns off |
| Low-Power-Indicator | --- | --- |
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED` | true/false | enables low power indication |
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET` | preset id | when low power is detected then use this preset to indicate low power |
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD` | % (0-100) | when this threshold is reached low power gets indicated |
| `USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION` | seconds | for this long the configured preset is played |
All parameters can be configured at runtime via the Usermods settings page.
## ⚠️ Important
- Make sure you know your battery specifications! All batteries are **NOT** the same!
- Example:
| Your battery specification table | | Options you can define |
| :-------------------------------- |:--------------- | :---------------------------- |
| Capacity | 3500mAh 12,5 Wh | |
| Minimum capacity | 3350mAh 11,9 Wh | |
| Rated voltage | 3.6V - 3.7V | |
| **Charging end voltage** | **4,2V ± 0,05** | `USERMOD_BATTERY_MAX_VOLTAGE` |
| **Discharge voltage** | **2,5V** | `USERMOD_BATTERY_MIN_VOLTAGE` |
| Max. discharge current (constant) | 10A (10000mA) | |
| max. charging current | 1.7A (1700mA) | |
| ... | ... | ... |
| .. | .. | .. |
Specification from: [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833)
## 🌐 Useful Links
- https://lazyzero.de/elektronik/esp8266/wemos_d1_mini_a0/start
- https://arduinodiy.wordpress.com/2016/12/25/monitoring-lipo-battery-voltage-with-wemos-d1-minibattery-shield-and-thingspeak/
## 📝 Change Log
2023-01-04
- basic support for LiPo rechargeable batteries ( `-D USERMOD_BATTERY_USE_LIPO`)
- improved support for esp32 (read calibrated voltage)
- corrected config saving (measurement pin, and battery min/max were lost)
- various bugfixes
2022-12-25
- added "auto-off" feature
- added "low-power-indication" feature
- added "calibration/offset" field to configuration page
- added getter and setter, so that user usermods could interact with this one
- update readme (added new options, made it markdownlint compliant)
2021-09-02
- added "Battery voltage" to info
- added circuit diagram to readme
- added MQTT support, sending battery voltage
- minor fixes
2021-08-15
- changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries
- Updated readme, added specification table
2021-08-10
- Created

View File

@ -0,0 +1,787 @@
#pragma once
#include "wled.h"
#include "battery_defaults.h"
/*
* Usermod by Maximilian Mewes
* Mail: mewes.maximilian@gmx.de
* GitHub: itCarl
* Date: 25.12.2022
* If you have any questions, please feel free to contact me.
*/
class UsermodBattery : public Usermod
{
private:
// battery pin can be defined in my_config.h
int8_t batteryPin = USERMOD_BATTERY_MEASUREMENT_PIN;
// how often to read the battery voltage
unsigned long readingInterval = USERMOD_BATTERY_MEASUREMENT_INTERVAL;
unsigned long nextReadTime = 0;
unsigned long lastReadTime = 0;
// battery min. voltage
float minBatteryVoltage = USERMOD_BATTERY_MIN_VOLTAGE;
// battery max. voltage
float maxBatteryVoltage = USERMOD_BATTERY_MAX_VOLTAGE;
// all battery cells summed up
unsigned int totalBatteryCapacity = USERMOD_BATTERY_TOTAL_CAPACITY;
// raw analog reading
float rawValue = 0.0f;
// calculated voltage
float voltage = maxBatteryVoltage;
// between 0 and 1, to control strength of voltage smoothing filter
float alpha = 0.05f;
// multiplier for the voltage divider that is in place between ADC pin and battery, default will be 2 but might be adapted to readout voltages over ~5v ESP32 or ~6.6v ESP8266
float voltageMultiplier = USERMOD_BATTERY_VOLTAGE_MULTIPLIER;
// mapped battery level based on voltage
int8_t batteryLevel = 100;
// offset or calibration value to fine tune the calculated voltage
float calibration = USERMOD_BATTERY_CALIBRATION;
// time left estimation feature
// bool calculateTimeLeftEnabled = USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED;
// float estimatedTimeLeft = 0.0;
// auto shutdown/shutoff/master off feature
bool autoOffEnabled = USERMOD_BATTERY_AUTO_OFF_ENABLED;
int8_t autoOffThreshold = USERMOD_BATTERY_AUTO_OFF_THRESHOLD;
// low power indicator feature
bool lowPowerIndicatorEnabled = USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED;
int8_t lowPowerIndicatorPreset = USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET;
int8_t lowPowerIndicatorThreshold = USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD;
int8_t lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10;
int8_t lowPowerIndicatorDuration = USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION;
bool lowPowerIndicationDone = false;
unsigned long lowPowerActivationTime = 0; // used temporary during active time
int8_t lastPreset = 0;
bool initDone = false;
bool initializing = true;
// strings to reduce flash memory usage (used more than twice)
static const char _name[];
static const char _readInterval[];
static const char _enabled[];
static const char _threshold[];
static const char _preset[];
static const char _duration[];
static const char _init[];
// custom map function
// https://forum.arduino.cc/t/floating-point-using-map-function/348113/2
double mapf(double x, double in_min, double in_max, double out_min, double out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
float dot2round(float x)
{
float nx = (int)(x * 100 + .5);
return (float)(nx / 100);
}
/*
* Turn off all leds
*/
void turnOff()
{
bri = 0;
stateUpdated(CALL_MODE_DIRECT_CHANGE);
}
/*
* Indicate low power by activating a configured preset for a given time and then switching back to the preset that was selected previously
*/
void lowPowerIndicator()
{
if (!lowPowerIndicatorEnabled) return;
if (batteryPin < 0) return; // no measurement
if (lowPowerIndicationDone && lowPowerIndicatorReactivationThreshold <= batteryLevel) lowPowerIndicationDone = false;
if (lowPowerIndicatorThreshold <= batteryLevel) return;
if (lowPowerIndicationDone) return;
if (lowPowerActivationTime <= 1) {
lowPowerActivationTime = millis();
lastPreset = currentPreset;
applyPreset(lowPowerIndicatorPreset);
}
if (lowPowerActivationTime+(lowPowerIndicatorDuration*1000) <= millis()) {
lowPowerIndicationDone = true;
lowPowerActivationTime = 0;
applyPreset(lastPreset);
}
}
float readVoltage()
{
#ifdef ARDUINO_ARCH_ESP32
// use calibrated millivolts analogread on esp32 (150 mV ~ 2450 mV default attentuation) and divide by 1000 to get from milivolts to volts and multiply by voltage multiplier and apply calibration value
return (analogReadMilliVolts(batteryPin) / 1000.0f) * voltageMultiplier + calibration;
#else
// use analog read on esp8266 ( 0V ~ 1V no attenuation options) and divide by ADC precision 1023 and multiply by voltage multiplier and apply calibration value
return (analogRead(batteryPin) / 1023.0f) * voltageMultiplier + calibration;
#endif
}
public:
//Functions called by WLED
/*
* setup() is called once at boot. WiFi is not yet connected at this point.
* You can use it to initialize variables, sensors or similar.
*/
void setup()
{
#ifdef ARDUINO_ARCH_ESP32
bool success = false;
DEBUG_PRINTLN(F("Allocating battery pin..."));
if (batteryPin >= 0 && digitalPinToAnalogChannel(batteryPin) >= 0)
if (pinManager.allocatePin(batteryPin, false, PinOwner::UM_Battery)) {
DEBUG_PRINTLN(F("Battery pin allocation succeeded."));
success = true;
voltage = readVoltage();
}
if (!success) {
DEBUG_PRINTLN(F("Battery pin allocation failed."));
batteryPin = -1; // allocation failed
} else {
pinMode(batteryPin, INPUT);
}
#else //ESP8266 boards have only one analog input pin A0
pinMode(batteryPin, INPUT);
voltage = readVoltage();
#endif
nextReadTime = millis() + readingInterval;
lastReadTime = millis();
initDone = true;
}
/*
* connected() is called every time the WiFi is (re)connected
* Use it to initialize network interfaces
*/
void connected()
{
//Serial.println("Connected to WiFi!");
}
/*
* loop() is called continuously. Here you can check for events, read sensors, etc.
*
*/
void loop()
{
if(strip.isUpdating()) return;
lowPowerIndicator();
// check the battery level every USERMOD_BATTERY_MEASUREMENT_INTERVAL (ms)
if (millis() < nextReadTime) return;
nextReadTime = millis() + readingInterval;
lastReadTime = millis();
if (batteryPin < 0) return; // nothing to read
initializing = false;
rawValue = readVoltage();
// filter with exponential smoothing because ADC in esp32 is fluctuating too much for a good single readout
voltage = voltage + alpha * (rawValue - voltage);
// check if voltage is within specified voltage range, allow 10% over/under voltage - removed cause this just makes it hard for people to troubleshoot as the voltage in the web gui will say invalid instead of displaying a voltage
//voltage = ((voltage < minBatteryVoltage * 0.85f) || (voltage > maxBatteryVoltage * 1.1f)) ? -1.0f : voltage;
// translate battery voltage into percentage
/*
the standard "map" function doesn't work
https://www.arduino.cc/reference/en/language/functions/math/map/ notes and warnings at the bottom
*/
#ifdef USERMOD_BATTERY_USE_LIPO
batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100); // basic mapping
// LiPo batteries have a differnt dischargin curve, see
// https://blog.ampow.com/lipo-voltage-chart/
if (batteryLevel < 40.0f)
batteryLevel = mapf(batteryLevel, 0, 40, 0, 12); // last 45% -> drops very quickly
else {
if (batteryLevel < 90.0f)
batteryLevel = mapf(batteryLevel, 40, 90, 12, 95); // 90% ... 40% -> almost linear drop
else // level > 90%
batteryLevel = mapf(batteryLevel, 90, 105, 95, 100); // highest 15% -> drop slowly
}
#else
batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100);
#endif
if (voltage > -1.0f) batteryLevel = constrain(batteryLevel, 0.0f, 110.0f);
// if (calculateTimeLeftEnabled) {
// float currentBatteryCapacity = totalBatteryCapacity;
// estimatedTimeLeft = (currentBatteryCapacity/strip.currentMilliamps)*60;
// }
// Auto off -- Master power off
if (autoOffEnabled && (autoOffThreshold >= batteryLevel))
turnOff();
#ifndef WLED_DISABLE_MQTT
// SmartHome stuff
// still don't know much about MQTT and/or HA
if (WLED_MQTT_CONNECTED) {
char buf[64]; // buffer for snprintf()
snprintf_P(buf, 63, PSTR("%s/voltage"), mqttDeviceTopic);
mqtt->publish(buf, 0, false, String(voltage).c_str());
}
#endif
}
/*
* addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API.
* Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI.
* Below it is shown how this could be used for e.g. a light sensor
*/
void addToJsonInfo(JsonObject& root)
{
JsonObject user = root["u"];
if (user.isNull()) user = root.createNestedObject("u");
if (batteryPin < 0) {
JsonArray infoVoltage = user.createNestedArray(F("Battery voltage"));
infoVoltage.add(F("n/a"));
infoVoltage.add(F(" invalid GPIO"));
return; // no GPIO - nothing to report
}
// info modal display names
JsonArray infoPercentage = user.createNestedArray(F("Battery level"));
JsonArray infoVoltage = user.createNestedArray(F("Battery voltage"));
// if (calculateTimeLeftEnabled)
// {
// JsonArray infoEstimatedTimeLeft = user.createNestedArray(F("Estimated time left"));
// if (initializing) {
// infoEstimatedTimeLeft.add(FPSTR(_init));
// } else {
// infoEstimatedTimeLeft.add(estimatedTimeLeft);
// infoEstimatedTimeLeft.add(F(" min"));
// }
// }
JsonArray infoNextUpdate = user.createNestedArray(F("Next update"));
infoNextUpdate.add((nextReadTime - millis()) / 1000);
infoNextUpdate.add(F(" sec"));
if (initializing) {
infoPercentage.add(FPSTR(_init));
infoVoltage.add(FPSTR(_init));
return;
}
if (batteryLevel < 0) {
infoPercentage.add(F("invalid"));
} else {
infoPercentage.add(batteryLevel);
}
infoPercentage.add(F(" %"));
if (voltage < 0) {
infoVoltage.add(F("invalid"));
} else {
infoVoltage.add(dot2round(voltage));
}
infoVoltage.add(F(" V"));
}
/*
* addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object).
* Values in the state object may be modified by connected clients
*/
/*
void addToJsonState(JsonObject& root)
{
}
*/
/*
* readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object).
* Values in the state object may be modified by connected clients
*/
/*
void readFromJsonState(JsonObject& root)
{
}
*/
/*
* addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object.
* It will be called by WLED when settings are actually saved (for example, LED settings are saved)
* If you want to force saving the current state, use serializeConfig() in your loop().
*
* CAUTION: serializeConfig() will initiate a filesystem write operation.
* It might cause the LEDs to stutter and will cause flash wear if called too often.
* Use it sparingly and always in the loop, never in network callbacks!
*
* addToConfig() will make your settings editable through the Usermod Settings page automatically.
*
* Usermod Settings Overview:
* - Numeric values are treated as floats in the browser.
* - If the numeric value entered into the browser contains a decimal point, it will be parsed as a C float
* before being returned to the Usermod. The float data type has only 6-7 decimal digits of precision, and
* doubles are not supported, numbers will be rounded to the nearest float value when being parsed.
* The range accepted by the input field is +/- 1.175494351e-38 to +/- 3.402823466e+38.
* - If the numeric value entered into the browser doesn't contain a decimal point, it will be parsed as a
* C int32_t (range: -2147483648 to 2147483647) before being returned to the usermod.
* Overflows or underflows are truncated to the max/min value for an int32_t, and again truncated to the type
* used in the Usermod when reading the value from ArduinoJson.
* - Pin values can be treated differently from an integer value by using the key name "pin"
* - "pin" can contain a single or array of integer values
* - On the Usermod Settings page there is simple checking for pin conflicts and warnings for special pins
* - Red color indicates a conflict. Yellow color indicates a pin with a warning (e.g. an input-only pin)
* - Tip: use int8_t to store the pin value in the Usermod, so a -1 value (pin not set) can be used
*
* See usermod_v2_auto_save.h for an example that saves Flash space by reusing ArduinoJson key name strings
*
* If you need a dedicated settings page with custom layout for your Usermod, that takes a lot more work.
* You will have to add the setting to the HTML, xml.cpp and set.cpp manually.
* See the WLED Soundreactive fork (code and wiki) for reference. https://github.com/atuline/WLED
*
* I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings!
*/
void addToConfig(JsonObject& root)
{
JsonObject battery = root.createNestedObject(FPSTR(_name)); // usermodname
#ifdef ARDUINO_ARCH_ESP32
battery[F("pin")] = batteryPin;
#endif
// battery[F("time-left")] = calculateTimeLeftEnabled;
battery[F("min-voltage")] = minBatteryVoltage;
battery[F("max-voltage")] = maxBatteryVoltage;
battery[F("capacity")] = totalBatteryCapacity;
battery[F("calibration")] = calibration;
battery[F("voltage-multiplier")] = voltageMultiplier;
battery[FPSTR(_readInterval)] = readingInterval;
JsonObject ao = battery.createNestedObject(F("auto-off")); // auto off section
ao[FPSTR(_enabled)] = autoOffEnabled;
ao[FPSTR(_threshold)] = autoOffThreshold;
JsonObject lp = battery.createNestedObject(F("indicator")); // low power section
lp[FPSTR(_enabled)] = lowPowerIndicatorEnabled;
lp[FPSTR(_preset)] = lowPowerIndicatorPreset; // dropdown trickery (String)lowPowerIndicatorPreset;
lp[FPSTR(_threshold)] = lowPowerIndicatorThreshold;
lp[FPSTR(_duration)] = lowPowerIndicatorDuration;
// read voltage in case calibration or voltage multiplier changed to see immediate effect
voltage = readVoltage();
DEBUG_PRINTLN(F("Battery config saved."));
}
void appendConfigData()
{
oappend(SET_F("addInfo('Battery:min-voltage', 1, 'v');"));
oappend(SET_F("addInfo('Battery:max-voltage', 1, 'v');"));
oappend(SET_F("addInfo('Battery:capacity', 1, 'mAh');"));
oappend(SET_F("addInfo('Battery:interval', 1, 'ms');"));
oappend(SET_F("addInfo('Battery:auto-off:threshold', 1, '%');"));
oappend(SET_F("addInfo('Battery:indicator:threshold', 1, '%');"));
oappend(SET_F("addInfo('Battery:indicator:duration', 1, 's');"));
// cannot quite get this mf to work. its exeeding some buffer limit i think
// what i wanted is a list of all presets to select one from
// oappend(SET_F("bd=addDropdown('Battery:low-power-indicator', 'preset');"));
// the loop generates: oappend(SET_F("addOption(bd, 'preset name', preset id);"));
// for(int8_t i=1; i < 42; i++) {
// oappend(SET_F("addOption(bd, 'Preset#"));
// oappendi(i);
// oappend(SET_F("',"));
// oappendi(i);
// oappend(SET_F(");"));
// }
}
/*
* readFromConfig() can be used to read back the custom settings you added with addToConfig().
* This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page)
*
* readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes),
* but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup.
* If you don't know what that is, don't fret. It most likely doesn't affect your use case :)
*
* Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings)
*
* getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present
* The configComplete variable is true only if the "exampleUsermod" object and all values are present. If any values are missing, WLED will know to call addToConfig() to save them
*
* This function is guaranteed to be called on boot, but could also be called every time settings are updated
*/
bool readFromConfig(JsonObject& root)
{
#ifdef ARDUINO_ARCH_ESP32
int8_t newBatteryPin = batteryPin;
#endif
JsonObject battery = root[FPSTR(_name)];
if (battery.isNull())
{
DEBUG_PRINT(FPSTR(_name));
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
return false;
}
#ifdef ARDUINO_ARCH_ESP32
newBatteryPin = battery[F("pin")] | newBatteryPin;
#endif
// calculateTimeLeftEnabled = battery[F("time-left")] | calculateTimeLeftEnabled;
setMinBatteryVoltage(battery[F("min-voltage")] | minBatteryVoltage);
setMaxBatteryVoltage(battery[F("max-voltage")] | maxBatteryVoltage);
setTotalBatteryCapacity(battery[F("capacity")] | totalBatteryCapacity);
setCalibration(battery[F("calibration")] | calibration);
setVoltageMultiplier(battery[F("voltage-multiplier")] | voltageMultiplier);
setReadingInterval(battery[FPSTR(_readInterval)] | readingInterval);
JsonObject ao = battery[F("auto-off")];
setAutoOffEnabled(ao[FPSTR(_enabled)] | autoOffEnabled);
setAutoOffThreshold(ao[FPSTR(_threshold)] | autoOffThreshold);
JsonObject lp = battery[F("indicator")];
setLowPowerIndicatorEnabled(lp[FPSTR(_enabled)] | lowPowerIndicatorEnabled);
setLowPowerIndicatorPreset(lp[FPSTR(_preset)] | lowPowerIndicatorPreset); // dropdown trickery (int)lp["preset"]
setLowPowerIndicatorThreshold(lp[FPSTR(_threshold)] | lowPowerIndicatorThreshold);
lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10;
setLowPowerIndicatorDuration(lp[FPSTR(_duration)] | lowPowerIndicatorDuration);
DEBUG_PRINT(FPSTR(_name));
#ifdef ARDUINO_ARCH_ESP32
if (!initDone)
{
// first run: reading from cfg.json
batteryPin = newBatteryPin;
DEBUG_PRINTLN(F(" config loaded."));
}
else
{
DEBUG_PRINTLN(F(" config (re)loaded."));
// changing parameters from settings page
if (newBatteryPin != batteryPin)
{
// deallocate pin
pinManager.deallocatePin(batteryPin, PinOwner::UM_Battery);
batteryPin = newBatteryPin;
// initialise
setup();
}
}
#endif
return !battery[FPSTR(_readInterval)].isNull();
}
/*
* Generate a preset sample for low power indication
*/
void generateExamplePreset()
{
// StaticJsonDocument<300> j;
// JsonObject preset = j.createNestedObject();
// preset["mainseg"] = 0;
// JsonArray seg = preset.createNestedArray("seg");
// JsonObject seg0 = seg.createNestedObject();
// seg0["id"] = 0;
// seg0["start"] = 0;
// seg0["stop"] = 60;
// seg0["grp"] = 0;
// seg0["spc"] = 0;
// seg0["on"] = true;
// seg0["bri"] = 255;
// JsonArray col0 = seg0.createNestedArray("col");
// JsonArray col00 = col0.createNestedArray();
// col00.add(255);
// col00.add(0);
// col00.add(0);
// seg0["fx"] = 1;
// seg0["sx"] = 128;
// seg0["ix"] = 128;
// savePreset(199, "Low power Indicator", preset);
}
/*
*
* Getter and Setter. Just in case some other usermod wants to interact with this in the future
*
*/
/*
* getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!).
* This could be used in the future for the system to determine whether your usermod is installed.
*/
uint16_t getId()
{
return USERMOD_ID_BATTERY;
}
unsigned long getReadingInterval()
{
return readingInterval;
}
/*
* minimum repetition is 3000ms (3s)
*/
void setReadingInterval(unsigned long newReadingInterval)
{
readingInterval = max((unsigned long)3000, newReadingInterval);
}
/*
* Get lowest configured battery voltage
*/
float getMinBatteryVoltage()
{
return minBatteryVoltage;
}
/*
* Set lowest battery voltage
* can't be below 0 volt
*/
void setMinBatteryVoltage(float voltage)
{
minBatteryVoltage = max(0.0f, voltage);
}
/*
* Get highest configured battery voltage
*/
float getMaxBatteryVoltage()
{
return maxBatteryVoltage;
}
/*
* Set highest battery voltage
* can't be below minBatteryVoltage
*/
void setMaxBatteryVoltage(float voltage)
{
#ifdef USERMOD_BATTERY_USE_LIPO
maxBatteryVoltage = max(getMinBatteryVoltage()+0.7f, voltage);
#else
maxBatteryVoltage = max(getMinBatteryVoltage()+1.0f, voltage);
#endif
}
/*
* Get the capacity of all cells in parralel sumed up
* unit: mAh
*/
unsigned int getTotalBatteryCapacity()
{
return totalBatteryCapacity;
}
void setTotalBatteryCapacity(unsigned int capacity)
{
totalBatteryCapacity = capacity;
}
/*
* Get the calculated voltage
* formula: (adc pin value / adc precision * max voltage) + calibration
*/
float getVoltage()
{
return voltage;
}
/*
* Get the mapped battery level (0 - 100) based on voltage
* important: voltage can drop when a load is applied, so its only an estimate
*/
int8_t getBatteryLevel()
{
return batteryLevel;
}
/*
* Get the configured calibration value
* a offset value to fine-tune the calculated voltage.
*/
float getCalibration()
{
return calibration;
}
/*
* Set the voltage calibration offset value
* a offset value to fine-tune the calculated voltage.
*/
void setCalibration(float offset)
{
calibration = offset;
}
/*
* Set the voltage multiplier value
* A multiplier that may need adjusting for different voltage divider setups
*/
void setVoltageMultiplier(float multiplier)
{
voltageMultiplier = multiplier;
}
/*
* Get the voltage multiplier value
* A multiplier that may need adjusting for different voltage divider setups
*/
float getVoltageMultiplier()
{
return voltageMultiplier;
}
/*
* Get auto-off feature enabled status
* is auto-off enabled, true/false
*/
bool getAutoOffEnabled()
{
return autoOffEnabled;
}
/*
* Set auto-off feature status
*/
void setAutoOffEnabled(bool enabled)
{
autoOffEnabled = enabled;
}
/*
* Get auto-off threshold in percent (0-100)
*/
int8_t getAutoOffThreshold()
{
return autoOffThreshold;
}
/*
* Set auto-off threshold in percent (0-100)
*/
void setAutoOffThreshold(int8_t threshold)
{
autoOffThreshold = min((int8_t)100, max((int8_t)0, threshold));
// when low power indicator is enabled the auto-off threshold cannot be above indicator threshold
autoOffThreshold = lowPowerIndicatorEnabled /*&& autoOffEnabled*/ ? min(lowPowerIndicatorThreshold-1, (int)autoOffThreshold) : autoOffThreshold;
}
/*
* Get low-power-indicator feature enabled status
* is the low-power-indicator enabled, true/false
*/
bool getLowPowerIndicatorEnabled()
{
return lowPowerIndicatorEnabled;
}
/*
* Set low-power-indicator feature status
*/
void setLowPowerIndicatorEnabled(bool enabled)
{
lowPowerIndicatorEnabled = enabled;
}
/*
* Get low-power-indicator preset to activate when low power is detected
*/
int8_t getLowPowerIndicatorPreset()
{
return lowPowerIndicatorPreset;
}
/*
* Set low-power-indicator preset to activate when low power is detected
*/
void setLowPowerIndicatorPreset(int8_t presetId)
{
// String tmp = ""; For what ever reason this doesn't work :(
// lowPowerIndicatorPreset = getPresetName(presetId, tmp) ? presetId : lowPowerIndicatorPreset;
lowPowerIndicatorPreset = presetId;
}
/*
* Get low-power-indicator threshold in percent (0-100)
*/
int8_t getLowPowerIndicatorThreshold()
{
return lowPowerIndicatorThreshold;
}
/*
* Set low-power-indicator threshold in percent (0-100)
*/
void setLowPowerIndicatorThreshold(int8_t threshold)
{
lowPowerIndicatorThreshold = threshold;
// when auto-off is enabled the indicator threshold cannot be below auto-off threshold
lowPowerIndicatorThreshold = autoOffEnabled /*&& lowPowerIndicatorEnabled*/ ? max(autoOffThreshold+1, (int)lowPowerIndicatorThreshold) : max(5, (int)lowPowerIndicatorThreshold);
}
/*
* Get low-power-indicator duration in seconds
*/
int8_t getLowPowerIndicatorDuration()
{
return lowPowerIndicatorDuration;
}
/*
* Set low-power-indicator duration in seconds
*/
void setLowPowerIndicatorDuration(int8_t duration)
{
lowPowerIndicatorDuration = duration;
}
/*
* Get low-power-indicator status when the indication is done thsi returns true
*/
bool getLowPowerIndicatorDone()
{
return lowPowerIndicationDone;
}
};
// strings to reduce flash memory usage (used more than twice)
const char UsermodBattery::_name[] PROGMEM = "Battery";
const char UsermodBattery::_readInterval[] PROGMEM = "interval";
const char UsermodBattery::_enabled[] PROGMEM = "enabled";
const char UsermodBattery::_threshold[] PROGMEM = "threshold";
const char UsermodBattery::_preset[] PROGMEM = "preset";
const char UsermodBattery::_duration[] PROGMEM = "duration";
const char UsermodBattery::_init[] PROGMEM = "init";

View File

@ -0,0 +1,8 @@
# Cronixie clock usermod
This usermod supports driving the Cronixie M and L clock kits by Diamex.
## Installation
Compile and upload after adding `-D USERMOD_CRONIXIE` to `build_flags` of your PlatformIO environment.
Make sure the Auto Brightness Limiter is enabled at 420mA (!) and configure 60 WS281x LEDs.

View File

@ -0,0 +1,302 @@
#pragma once
#include "wled.h"
class UsermodCronixie : public Usermod {
private:
unsigned long lastTime = 0;
char cronixieDisplay[7] = "HHMMSS";
byte _digitOut[6] = {10,10,10,10,10,10};
byte dP[6] = {255, 255, 255, 255, 255, 255};
// set your config variables to their boot default value (this can also be done in readFromConfig() or a constructor if you prefer)
bool backlight = true;
public:
void initCronixie()
{
if (dP[0] == 255) // if dP[0] is 255, cronixie is not yet init'ed
{
setCronixie();
strip.getSegment(0).grouping = 10; // 10 LEDs per digit
}
}
void setup() {
}
void loop() {
if (!toki.isTick()) return;
initCronixie();
_overlayCronixie();
strip.trigger();
}
byte getSameCodeLength(char code, int index, char const cronixieDisplay[])
{
byte counter = 0;
for (int i = index+1; i < 6; i++)
{
if (cronixieDisplay[i] == code)
{
counter++;
} else {
return counter;
}
}
return counter;
}
void setCronixie()
{
/*
* digit purpose index
* 0-9 | 0-9 (incl. random)
* 10 | blank
* 11 | blank, bg off
* 12 | test upw.
* 13 | test dnw.
* 14 | binary AM/PM
* 15 | BB upper +50 for no trailing 0
* 16 | BBB
* 17 | BBBB
* 18 | BBBBB
* 19 | BBBBBB
* 20 | H
* 21 | HH
* 22 | HHH
* 23 | HHHH
* 24 | M
* 25 | MM
* 26 | MMM
* 27 | MMMM
* 28 | MMMMM
* 29 | MMMMMM
* 30 | S
* 31 | SS
* 32 | SSS
* 33 | SSSS
* 34 | SSSSS
* 35 | SSSSSS
* 36 | Y
* 37 | YY
* 38 | YYYY
* 39 | I
* 40 | II
* 41 | W
* 42 | WW
* 43 | D
* 44 | DD
* 45 | DDD
* 46 | V
* 47 | VV
* 48 | VVV
* 49 | VVVV
* 50 | VVVVV
* 51 | VVVVVV
* 52 | v
* 53 | vv
* 54 | vvv
* 55 | vvvv
* 56 | vvvvv
* 57 | vvvvvv
*/
//H HourLower | HH - Hour 24. | AH - Hour 12. | HHH Hour of Month | HHHH Hour of Year
//M MinuteUpper | MM Minute of Hour | MMM Minute of 12h | MMMM Minute of Day | MMMMM Minute of Month | MMMMMM Minute of Year
//S SecondUpper | SS Second of Minute | SSS Second of 10 Minute | SSSS Second of Hour | SSSSS Second of Day | SSSSSS Second of Week
//B AM/PM | BB 0-6/6-12/12-18/18-24 | BBB 0-3... | BBBB 0-1.5... | BBBBB 0-1 | BBBBBB 0-0.5
//Y YearLower | YY - Year LU | YYYY - Std.
//I MonthLower | II - Month of Year
//W Week of Month | WW Week of Year
//D Day of Week | DD Day Of Month | DDD Day Of Year
DEBUG_PRINT("cset ");
DEBUG_PRINTLN(cronixieDisplay);
for (int i = 0; i < 6; i++)
{
dP[i] = 10;
switch (cronixieDisplay[i])
{
case '_': dP[i] = 10; break;
case '-': dP[i] = 11; break;
case 'r': dP[i] = random(1,7); break; //random btw. 1-6
case 'R': dP[i] = random(0,10); break; //random btw. 0-9
//case 't': break; //Test upw.
//case 'T': break; //Test dnw.
case 'b': dP[i] = 14 + getSameCodeLength('b',i,cronixieDisplay); i = i+dP[i]-14; break;
case 'B': dP[i] = 14 + getSameCodeLength('B',i,cronixieDisplay); i = i+dP[i]-14; break;
case 'h': dP[i] = 70 + getSameCodeLength('h',i,cronixieDisplay); i = i+dP[i]-70; break;
case 'H': dP[i] = 20 + getSameCodeLength('H',i,cronixieDisplay); i = i+dP[i]-20; break;
case 'A': dP[i] = 108; i++; break;
case 'a': dP[i] = 58; i++; break;
case 'm': dP[i] = 74 + getSameCodeLength('m',i,cronixieDisplay); i = i+dP[i]-74; break;
case 'M': dP[i] = 24 + getSameCodeLength('M',i,cronixieDisplay); i = i+dP[i]-24; break;
case 's': dP[i] = 80 + getSameCodeLength('s',i,cronixieDisplay); i = i+dP[i]-80; break; //refresh more often bc. of secs
case 'S': dP[i] = 30 + getSameCodeLength('S',i,cronixieDisplay); i = i+dP[i]-30; break;
case 'Y': dP[i] = 36 + getSameCodeLength('Y',i,cronixieDisplay); i = i+dP[i]-36; break;
case 'y': dP[i] = 86 + getSameCodeLength('y',i,cronixieDisplay); i = i+dP[i]-86; break;
case 'I': dP[i] = 39 + getSameCodeLength('I',i,cronixieDisplay); i = i+dP[i]-39; break; //Month. Don't ask me why month and minute both start with M.
case 'i': dP[i] = 89 + getSameCodeLength('i',i,cronixieDisplay); i = i+dP[i]-89; break;
//case 'W': break;
//case 'w': break;
case 'D': dP[i] = 43 + getSameCodeLength('D',i,cronixieDisplay); i = i+dP[i]-43; break;
case 'd': dP[i] = 93 + getSameCodeLength('d',i,cronixieDisplay); i = i+dP[i]-93; break;
case '0': dP[i] = 0; break;
case '1': dP[i] = 1; break;
case '2': dP[i] = 2; break;
case '3': dP[i] = 3; break;
case '4': dP[i] = 4; break;
case '5': dP[i] = 5; break;
case '6': dP[i] = 6; break;
case '7': dP[i] = 7; break;
case '8': dP[i] = 8; break;
case '9': dP[i] = 9; break;
//case 'V': break; //user var0
//case 'v': break; //user var1
}
}
DEBUG_PRINT("result ");
for (int i = 0; i < 5; i++)
{
DEBUG_PRINT((int)dP[i]);
DEBUG_PRINT(" ");
}
DEBUG_PRINTLN((int)dP[5]);
_overlayCronixie(); // refresh
}
void _overlayCronixie()
{
byte h = hour(localTime);
byte h0 = h;
byte m = minute(localTime);
byte s = second(localTime);
byte d = day(localTime);
byte mi = month(localTime);
int y = year(localTime);
//this has to be changed in time for 22nd century
y -= 2000; if (y<0) y += 30; //makes countdown work
if (useAMPM && !countdownMode)
{
if (h>12) h-=12;
else if (h==0) h+=12;
}
for (int i = 0; i < 6; i++)
{
if (dP[i] < 12) _digitOut[i] = dP[i];
else {
if (dP[i] < 65)
{
switch(dP[i])
{
case 21: _digitOut[i] = h/10; _digitOut[i+1] = h- _digitOut[i]*10; i++; break; //HH
case 25: _digitOut[i] = m/10; _digitOut[i+1] = m- _digitOut[i]*10; i++; break; //MM
case 31: _digitOut[i] = s/10; _digitOut[i+1] = s- _digitOut[i]*10; i++; break; //SS
case 20: _digitOut[i] = h- (h/10)*10; break; //H
case 24: _digitOut[i] = m/10; break; //M
case 30: _digitOut[i] = s/10; break; //S
case 43: _digitOut[i] = weekday(localTime); _digitOut[i]--; if (_digitOut[i]<1) _digitOut[i]= 7; break; //D
case 44: _digitOut[i] = d/10; _digitOut[i+1] = d- _digitOut[i]*10; i++; break; //DD
case 40: _digitOut[i] = mi/10; _digitOut[i+1] = mi- _digitOut[i]*10; i++; break; //II
case 37: _digitOut[i] = y/10; _digitOut[i+1] = y- _digitOut[i]*10; i++; break; //YY
case 39: _digitOut[i] = 2; _digitOut[i+1] = 0; _digitOut[i+2] = y/10; _digitOut[i+3] = y- _digitOut[i+2]*10; i+=3; break; //YYYY
//case 16: _digitOut[i+2] = ((h0/3)&1)?1:0; i++; //BBB (BBBB NI)
//case 15: _digitOut[i+1] = (h0>17 || (h0>5 && h0<12))?1:0; i++; //BB
case 14: _digitOut[i] = (h0>11)?1:0; break; //B
}
} else
{
switch(dP[i])
{
case 71: _digitOut[i] = h/10; _digitOut[i+1] = h- _digitOut[i]*10; if(_digitOut[i] == 0) _digitOut[i]=10; i++; break; //hh
case 75: _digitOut[i] = m/10; _digitOut[i+1] = m- _digitOut[i]*10; if(_digitOut[i] == 0) _digitOut[i]=10; i++; break; //mm
case 81: _digitOut[i] = s/10; _digitOut[i+1] = s- _digitOut[i]*10; if(_digitOut[i] == 0) _digitOut[i]=10; i++; break; //ss
//case 66: _digitOut[i+2] = ((h0/3)&1)?1:10; i++; //bbb (bbbb NI)
//case 65: _digitOut[i+1] = (h0>17 || (h0>5 && h0<12))?1:10; i++; //bb
case 64: _digitOut[i] = (h0>11)?1:10; break; //b
case 93: _digitOut[i] = weekday(localTime); _digitOut[i]--; if (_digitOut[i]<1) _digitOut[i]= 7; break; //d
case 94: _digitOut[i] = d/10; _digitOut[i+1] = d- _digitOut[i]*10; if(_digitOut[i] == 0) _digitOut[i]=10; i++; break; //dd
case 90: _digitOut[i] = mi/10; _digitOut[i+1] = mi- _digitOut[i]*10; if(_digitOut[i] == 0) _digitOut[i]=10; i++; break; //ii
case 87: _digitOut[i] = y/10; _digitOut[i+1] = y- _digitOut[i]*10; i++; break; //yy
case 89: _digitOut[i] = 2; _digitOut[i+1] = 0; _digitOut[i+2] = y/10; _digitOut[i+3] = y- _digitOut[i+2]*10; i+=3; break; //yyyy
}
}
}
}
}
void handleOverlayDraw()
{
byte offsets[] = {5, 0, 6, 1, 7, 2, 8, 3, 9, 4};
for (uint16_t i = 0; i < 6; i++)
{
byte o = 10*i;
byte excl = 10;
if(_digitOut[i] < 10) excl = offsets[_digitOut[i]];
excl += o;
if (backlight && _digitOut[i] <11)
{
uint32_t col = gamma32(strip.getSegment(0).colors[1]);
for (uint16_t j=o; j< o+10; j++) {
if (j != excl) strip.setPixelColor(j, col);
}
} else
{
for (uint16_t j=o; j< o+10; j++) {
if (j != excl) strip.setPixelColor(j, 0);
}
}
}
}
void addToJsonState(JsonObject& root)
{
root["nx"] = cronixieDisplay;
}
void readFromJsonState(JsonObject& root)
{
if (root["nx"].is<const char*>()) {
strncpy(cronixieDisplay, root["nx"], 6);
setCronixie();
}
}
void addToConfig(JsonObject& root)
{
JsonObject top = root.createNestedObject(F("Cronixie"));
top["backlight"] = backlight;
}
bool readFromConfig(JsonObject& root)
{
// default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor
// setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed)
JsonObject top = root[F("Cronixie")];
bool configComplete = !top.isNull();
configComplete &= getJsonValue(top["backlight"], backlight);
return configComplete;
}
uint16_t getId()
{
return USERMOD_ID_CRONIXIE;
}
};

View File

@ -0,0 +1,23 @@
; Options
; -------
; USERMOD_DHT - define this to have this user mod included wled00\usermods_list.cpp
; USERMOD_DHT_DHTTYPE - DHT model: 11, 21, 22 for DHT11, DHT21, or DHT22, defaults to 22/DHT22
; USERMOD_DHT_PIN - pin to which DTH is connected, defaults to Q2 pin on QuinLed Dig-Uno's board
; USERMOD_DHT_CELSIUS - define this to report temperatures in degrees celsious, otherwise fahrenheit will be reported
; USERMOD_DHT_MEASUREMENT_INTERVAL - the number of milliseconds between measurements, defaults to 60 seconds
; USERMOD_DHT_FIRST_MEASUREMENT_AT - the number of milliseconds after boot to take first measurement, defaults to 90 seconds
; USERMOD_DHT_MQTT - publish measurements to the MQTT broker
; USERMOD_DHT_STATS - For debug, report delay stats
[env:d1_mini_usermod_dht_C]
extends = env:d1_mini
build_flags = ${env:d1_mini.build_flags} -D USERMOD_DHT -D USERMOD_DHT_CELSIUS
lib_deps = ${env:d1_mini.lib_deps}
https://github.com/alwynallan/DHT_nonblocking
[env:custom32_LEDPIN_16_usermod_dht_C]
extends = env:custom32_LEDPIN_16
build_flags = ${env:custom32_LEDPIN_16.build_flags} -D USERMOD_DHT -D USERMOD_DHT_CELSIUS -D USERMOD_DHT_STATS
lib_deps = ${env.lib_deps}
https://github.com/alwynallan/DHT_nonblocking

48
usermods/DHT/readme.md Normal file
View File

@ -0,0 +1,48 @@
# DHT Temperature/Humidity sensor usermod
This usermod will read from an attached DHT22 or DHT11 humidity and temperature sensor.
The sensor readings are displayed in the Info section of the web UI (and optionally sent to an MQTT broker).
If sensor is not detected after 10 update intervals, the usermod will be disabled.
If enabled, measured temperature and humidity will be published to the following MQTT topics
* `{devceTopic}/dht/temperature`
* `{devceTopic}/dht/humidity`
## Installation
Copy the example `platformio_override.ini` to the root directory. This file should be placed in the same directory as `platformio.ini`.
### Define Your Options
* `USERMOD_DHT` - define this to include this user mod wled00\usermods_list.cpp
* `USERMOD_DHT_DHTTYPE` - DHT model: 11, 21, 22 for DHT11, DHT21, or DHT22, defaults to 22/DHT22
* `USERMOD_DHT_PIN` - pin to which DTH is connected, defaults to Q2 pin on QuinLed Dig-Uno's board
* `USERMOD_DHT_CELSIUS` - define this to report temperatures in degrees Celsius, otherwise Fahrenheit will be reported
* `USERMOD_DHT_MEASUREMENT_INTERVAL` - the number of milliseconds between measurements, defaults to 60000 ms
* `USERMOD_DHT_FIRST_MEASUREMENT_AT` - the number of milliseconds after boot to take first measurement, defaults to 90000 ms
* `USERMOD_DHT_MQTT` - publish measurements to an MQTT broker
* `USERMOD_DHT_STATS` - For debug, report delay stats
## Project link
* [QuinLED-Dig-Uno](https://quinled.info/2018/09/15/quinled-dig-uno/) - Project link
### PlatformIO requirements
If you are using `platformio_override.ini`, you should be able to refresh the task list and see your custom task, for example `env:d1_mini_usermod_dht_C`. If not, you can add the libraries and dependencies into `platformio.ini` as you see fit.
## Change Log
2022-10-15
* Add ability to publish sensor readings to an MQTT broker
* fix compilation error for sample [env:d1_mini_usermod_dht_C] task
2020-02-04
* Change default QuinLed pin to Q2
* Instead of trying to keep updates at constant cadence, space out readings by measurement interval. Hopefully, this helps eliminate occasional bursts of readings with errors
* Add some more (optional) stats
2020-02-03
* Due to poor readouts on ESP32 with previous DHT library, rewrote to use https://github.com/alwynallan/DHT_nonblocking
* The new library serializes/delays up to 5ms for the sensor readout
2020-02-02
* Created

247
usermods/DHT/usermod_dht.h Normal file
View File

@ -0,0 +1,247 @@
#pragma once
#include "wled.h"
#ifndef WLED_ENABLE_MQTT
#error "This user mod requires MQTT to be enabled."
#endif
#include <dht_nonblocking.h>
// USERMOD_DHT_DHTTYPE:
// 11 // DHT 11
// 21 // DHT 21
// 22 // DHT 22 (AM2302), AM2321 *** default
#ifndef USERMOD_DHT_DHTTYPE
#define USERMOD_DHT_DHTTYPE 22
#endif
#if USERMOD_DHT_DHTTYPE == 11
#define DHTTYPE DHT_TYPE_11
#elif USERMOD_DHT_DHTTYPE == 21
#define DHTTYPE DHT_TYPE_21
#elif USERMOD_DHT_DHTTYPE == 22
#define DHTTYPE DHT_TYPE_22
#endif
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// NOTE: Pin defaults below are for QuinLed Dig-Uno's Q2 on the board
// Connect pin 4 (on the right) of the sensor to GROUND
// NOTE: If using a bare sensor (AM*), Connect a 10K resistor from pin 2
// (data) to pin 1 (power) of the sensor. DHT* boards have the pullup already
#ifdef USERMOD_DHT_PIN
#define DHTPIN USERMOD_DHT_PIN
#else
#ifdef ARDUINO_ARCH_ESP32
#define DHTPIN 21
#else //ESP8266 boards
#define DHTPIN 4
#endif
#endif
// the frequency to check sensor, 1 minute
#ifndef USERMOD_DHT_MEASUREMENT_INTERVAL
#define USERMOD_DHT_MEASUREMENT_INTERVAL 60000
#endif
// how many seconds after boot to take first measurement, 90 seconds
// 90 gives enough time to OTA update firmware if this crashses
#ifndef USERMOD_DHT_FIRST_MEASUREMENT_AT
#define USERMOD_DHT_FIRST_MEASUREMENT_AT 90000
#endif
// from COOLDOWN_TIME in dht_nonblocking.cpp
#define DHT_TIMEOUT_TIME 10000
DHT_nonblocking dht_sensor(DHTPIN, DHTTYPE);
class UsermodDHT : public Usermod {
private:
unsigned long nextReadTime = 0;
unsigned long lastReadTime = 0;
float humidity, temperature = 0;
bool initializing = true;
bool disabled = false;
#ifdef USERMOD_DHT_MQTT
char dhtMqttTopic[64];
size_t dhtMqttTopicLen;
#endif
#ifdef USERMOD_DHT_STATS
unsigned long nextResetStatsTime = 0;
uint16_t updates = 0;
uint16_t clean_updates = 0;
uint16_t errors = 0;
unsigned long maxDelay = 0;
unsigned long currentIteration = 0;
unsigned long maxIteration = 0;
#endif
public:
void setup() {
nextReadTime = millis() + USERMOD_DHT_FIRST_MEASUREMENT_AT;
lastReadTime = millis();
#ifdef USERMOD_DHT_MQTT
sprintf(dhtMqttTopic, "%s/dht", mqttDeviceTopic);
dhtMqttTopicLen = strlen(dhtMqttTopic);
#endif
#ifdef USERMOD_DHT_STATS
nextResetStatsTime = millis() + 60*60*1000;
#endif
}
void loop() {
if (disabled) {
return;
}
if (millis() < nextReadTime) {
return;
}
#ifdef USERMOD_DHT_STATS
if (millis() >= nextResetStatsTime) {
nextResetStatsTime += 60*60*1000;
errors = 0;
updates = 0;
clean_updates = 0;
}
unsigned long dcalc = millis();
if (currentIteration == 0) {
currentIteration = millis();
}
#endif
float tempC;
if (dht_sensor.measure(&tempC, &humidity)) {
#ifdef USERMOD_DHT_CELSIUS
temperature = tempC;
#else
temperature = tempC * 9 / 5 + 32;
#endif
#ifdef USERMOD_DHT_MQTT
// 10^n where n is number of decimal places to display in mqtt message. Please adjust buff size together with this constant
#define FLOAT_PREC 100
if (WLED_MQTT_CONNECTED) {
char buff[10];
strcpy(dhtMqttTopic + dhtMqttTopicLen, "/temperature");
sprintf(buff, "%d.%d", (int)temperature, ((int)(temperature * FLOAT_PREC)) % FLOAT_PREC);
mqtt->publish(dhtMqttTopic, 0, false, buff);
sprintf(buff, "%d.%d", (int)humidity, ((int)(humidity * FLOAT_PREC)) % FLOAT_PREC);
strcpy(dhtMqttTopic + dhtMqttTopicLen, "/humidity");
mqtt->publish(dhtMqttTopic, 0, false, buff);
dhtMqttTopic[dhtMqttTopicLen] = '\0';
}
#undef FLOAT_PREC
#endif
nextReadTime = millis() + USERMOD_DHT_MEASUREMENT_INTERVAL;
lastReadTime = millis();
initializing = false;
#ifdef USERMOD_DHT_STATS
unsigned long icalc = millis() - currentIteration;
if (icalc > maxIteration) {
maxIteration = icalc;
}
if (icalc > DHT_TIMEOUT_TIME) {
errors += icalc/DHT_TIMEOUT_TIME;
} else {
clean_updates += 1;
}
updates += 1;
currentIteration = 0;
#endif
}
#ifdef USERMOD_DHT_STATS
dcalc = millis() - dcalc;
if (dcalc > maxDelay) {
maxDelay = dcalc;
}
#endif
if (((millis() - lastReadTime) > 10*USERMOD_DHT_MEASUREMENT_INTERVAL)) {
disabled = true;
}
}
void addToJsonInfo(JsonObject& root) {
if (disabled) {
return;
}
JsonObject user = root["u"];
if (user.isNull()) user = root.createNestedObject("u");
JsonArray temp = user.createNestedArray("Temperature");
JsonArray hum = user.createNestedArray("Humidity");
#ifdef USERMOD_DHT_STATS
JsonArray next = user.createNestedArray("next");
if (nextReadTime >= millis()) {
next.add((nextReadTime - millis()) / 1000);
next.add(" sec until read");
} else {
next.add((millis() - nextReadTime) / 1000);
next.add(" sec active reading");
}
JsonArray last = user.createNestedArray("last");
last.add((millis() - lastReadTime) / 60000);
last.add(" min since read");
JsonArray err = user.createNestedArray("errors");
err.add(errors);
err.add(" Errors");
JsonArray upd = user.createNestedArray("updates");
upd.add(updates);
upd.add(" Updates");
JsonArray cupd = user.createNestedArray("cleanUpdates");
cupd.add(clean_updates);
cupd.add(" Updates");
JsonArray iter = user.createNestedArray("maxIter");
iter.add(maxIteration);
iter.add(" ms");
JsonArray delay = user.createNestedArray("maxDelay");
delay.add(maxDelay);
delay.add(" ms");
#endif
if (initializing) {
// if we haven't read the sensor yet, let the user know
// that we are still waiting for the first measurement
temp.add((nextReadTime - millis()) / 1000);
temp.add(" sec until read");
hum.add((nextReadTime - millis()) / 1000);
hum.add(" sec until read");
return;
}
hum.add(humidity);
hum.add("%");
temp.add(temperature);
#ifdef USERMOD_DHT_CELSIUS
temp.add("°C");
#else
temp.add("°F");
#endif
}
uint16_t getId()
{
return USERMOD_ID_DHT;
}
};

View File

@ -5,6 +5,6 @@ In this usermod file you can find the documentation on how to take advantage of
## Installation
Copy `usermod_v2_example.h` to the wled00 directory.
Uncomment the corresponding lines in `usermods_list.h` and compile!
Uncomment the corresponding lines in `usermods_list.cpp` and compile!
_(You shouldn't need to actually install this, it does nothing useful)_

View File

@ -22,18 +22,75 @@
//class name. Use something descriptive and leave the ": public Usermod" part :)
class MyExampleUsermod : public Usermod {
private:
//Private class members. You can declare variables and functions only accessible to your usermod here
// Private class members. You can declare variables and functions only accessible to your usermod here
bool enabled = false;
bool initDone = false;
unsigned long lastTime = 0;
// set your config variables to their boot default value (this can also be done in readFromConfig() or a constructor if you prefer)
bool testBool = false;
unsigned long testULong = 42424242;
float testFloat = 42.42;
String testString = "Forty-Two";
// These config variables have defaults set inside readFromConfig()
int testInt;
long testLong;
int8_t testPins[2];
// string that are used multiple time (this will save some flash memory)
static const char _name[];
static const char _enabled[];
// any private methods should go here (non-inline methosd should be defined out of class)
void publishMqtt(const char* state, bool retain = false); // example for publishing MQTT message
public:
//Functions called by WLED
// non WLED related methods, may be used for data exchange between usermods (non-inline methods should be defined out of class)
/**
* Enable/Disable the usermod
*/
inline void enable(bool enable) { enabled = enable; }
/**
* Get usermod enabled/disabled state
*/
inline bool isEnabled() { return enabled; }
// in such case add the following to another usermod:
// in private vars:
// #ifdef USERMOD_EXAMPLE
// MyExampleUsermod* UM;
// #endif
// in setup()
// #ifdef USERMOD_EXAMPLE
// UM = (MyExampleUsermod*) usermods.lookup(USERMOD_ID_EXAMPLE);
// #endif
// somewhere in loop() or other member method
// #ifdef USERMOD_EXAMPLE
// if (UM != nullptr) isExampleEnabled = UM->isEnabled();
// if (!isExampleEnabled) UM->enable(true);
// #endif
// methods called by WLED (can be inlined as they are called only once but if you call them explicitly define them out of class)
/*
* setup() is called once at boot. WiFi is not yet connected at this point.
* readFromConfig() is called prior to setup()
* You can use it to initialize variables, sensors or similar.
*/
void setup() {
// do your set-up here
//Serial.println("Hello from my usermod!");
initDone = true;
}
@ -57,6 +114,11 @@ class MyExampleUsermod : public Usermod {
* Instead, use a timer check as shown here.
*/
void loop() {
// if usermod is disabled or called during strip updating just exit
// NOTE: on very long strips strip.isUpdating() may always return true so update accordingly
if (!enabled || strip.isUpdating()) return;
// do your magic here
if (millis() - lastTime > 1000) {
//Serial.println("I'm alive!");
lastTime = millis();
@ -69,19 +131,25 @@ class MyExampleUsermod : public Usermod {
* Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI.
* Below it is shown how this could be used for e.g. a light sensor
*/
/*
void addToJsonInfo(JsonObject& root)
{
int reading = 20;
//this code adds "u":{"Light":[20," lux"]} to the info object
// if "u" object does not exist yet wee need to create it
JsonObject user = root["u"];
if (user.isNull()) user = root.createNestedObject("u");
JsonArray lightArr = user.createNestedArray("Light"); //name
lightArr.add(reading); //value
lightArr.add(" lux"); //unit
//this code adds "u":{"ExampleUsermod":[20," lux"]} to the info object
//int reading = 20;
//JsonArray lightArr = user.createNestedArray(FPSTR(_name))); //name
//lightArr.add(reading); //value
//lightArr.add(F(" lux")); //unit
// if you are implementing a sensor usermod, you may publish sensor data
//JsonObject sensor = root[F("sensor")];
//if (sensor.isNull()) sensor = root.createNestedObject(F("sensor"));
//temp = sensor.createNestedArray(F("light"));
//temp.add(reading);
//temp.add(F("lux"));
}
*/
/*
@ -90,7 +158,12 @@ class MyExampleUsermod : public Usermod {
*/
void addToJsonState(JsonObject& root)
{
//root["user0"] = userVar0;
if (!initDone || !enabled) return; // prevent crash on boot applyPreset()
JsonObject usermod = root[FPSTR(_name)];
if (usermod.isNull()) usermod = root.createNestedObject(FPSTR(_name));
//usermod["user0"] = userVar0;
}
@ -100,11 +173,204 @@ class MyExampleUsermod : public Usermod {
*/
void readFromJsonState(JsonObject& root)
{
userVar0 = root["user0"] | userVar0; //if "user0" key exists in JSON, update, else keep old value
if (!initDone) return; // prevent crash on boot applyPreset()
JsonObject usermod = root[FPSTR(_name)];
if (!usermod.isNull()) {
// expect JSON usermod data in usermod name object: {"ExampleUsermod:{"user0":10}"}
userVar0 = usermod["user0"] | userVar0; //if "user0" key exists in JSON, update, else keep old value
}
// you can as well check WLED state JSON keys
//if (root["bri"] == 255) Serial.println(F("Don't burn down your garage!"));
}
/*
* addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object.
* It will be called by WLED when settings are actually saved (for example, LED settings are saved)
* If you want to force saving the current state, use serializeConfig() in your loop().
*
* CAUTION: serializeConfig() will initiate a filesystem write operation.
* It might cause the LEDs to stutter and will cause flash wear if called too often.
* Use it sparingly and always in the loop, never in network callbacks!
*
* addToConfig() will make your settings editable through the Usermod Settings page automatically.
*
* Usermod Settings Overview:
* - Numeric values are treated as floats in the browser.
* - If the numeric value entered into the browser contains a decimal point, it will be parsed as a C float
* before being returned to the Usermod. The float data type has only 6-7 decimal digits of precision, and
* doubles are not supported, numbers will be rounded to the nearest float value when being parsed.
* The range accepted by the input field is +/- 1.175494351e-38 to +/- 3.402823466e+38.
* - If the numeric value entered into the browser doesn't contain a decimal point, it will be parsed as a
* C int32_t (range: -2147483648 to 2147483647) before being returned to the usermod.
* Overflows or underflows are truncated to the max/min value for an int32_t, and again truncated to the type
* used in the Usermod when reading the value from ArduinoJson.
* - Pin values can be treated differently from an integer value by using the key name "pin"
* - "pin" can contain a single or array of integer values
* - On the Usermod Settings page there is simple checking for pin conflicts and warnings for special pins
* - Red color indicates a conflict. Yellow color indicates a pin with a warning (e.g. an input-only pin)
* - Tip: use int8_t to store the pin value in the Usermod, so a -1 value (pin not set) can be used
*
* See usermod_v2_auto_save.h for an example that saves Flash space by reusing ArduinoJson key name strings
*
* If you need a dedicated settings page with custom layout for your Usermod, that takes a lot more work.
* You will have to add the setting to the HTML, xml.cpp and set.cpp manually.
* See the WLED Soundreactive fork (code and wiki) for reference. https://github.com/atuline/WLED
*
* I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings!
*/
void addToConfig(JsonObject& root)
{
JsonObject top = root.createNestedObject(FPSTR(_name));
top[FPSTR(_enabled)] = enabled;
//save these vars persistently whenever settings are saved
top["great"] = userVar0;
top["testBool"] = testBool;
top["testInt"] = testInt;
top["testLong"] = testLong;
top["testULong"] = testULong;
top["testFloat"] = testFloat;
top["testString"] = testString;
JsonArray pinArray = top.createNestedArray("pin");
pinArray.add(testPins[0]);
pinArray.add(testPins[1]);
}
/*
* readFromConfig() can be used to read back the custom settings you added with addToConfig().
* This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page)
*
* readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes),
* but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup.
* If you don't know what that is, don't fret. It most likely doesn't affect your use case :)
*
* Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings)
*
* getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present
* The configComplete variable is true only if the "exampleUsermod" object and all values are present. If any values are missing, WLED will know to call addToConfig() to save them
*
* This function is guaranteed to be called on boot, but could also be called every time settings are updated
*/
bool readFromConfig(JsonObject& root)
{
// default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor
// setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed)
JsonObject top = root[FPSTR(_name)];
bool configComplete = !top.isNull();
configComplete &= getJsonValue(top["great"], userVar0);
configComplete &= getJsonValue(top["testBool"], testBool);
configComplete &= getJsonValue(top["testULong"], testULong);
configComplete &= getJsonValue(top["testFloat"], testFloat);
configComplete &= getJsonValue(top["testString"], testString);
// A 3-argument getJsonValue() assigns the 3rd argument as a default value if the Json value is missing
configComplete &= getJsonValue(top["testInt"], testInt, 42);
configComplete &= getJsonValue(top["testLong"], testLong, -42424242);
// "pin" fields have special handling in settings page (or some_pin as well)
configComplete &= getJsonValue(top["pin"][0], testPins[0], -1);
configComplete &= getJsonValue(top["pin"][1], testPins[1], -1);
return configComplete;
}
/*
* appendConfigData() is called when user enters usermod settings page
* it may add additional metadata for certain entry fields (adding drop down is possible)
* be careful not to add too much as oappend() buffer is limited to 3k
*/
void appendConfigData()
{
oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":great")); oappend(SET_F("',1,'<i>(this is a great config value)</i>');"));
oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":testString")); oappend(SET_F("',1,'enter any string you want');"));
oappend(SET_F("dd=addDropdown('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F("','testInt');"));
oappend(SET_F("addOption(dd,'Nothing',0);"));
oappend(SET_F("addOption(dd,'Everything',42);"));
}
/*
* handleOverlayDraw() is called just before every show() (LED strip update frame) after effects have set the colors.
* Use this to blank out some LEDs or set them to a different color regardless of the set effect mode.
* Commonly used for custom clocks (Cronixie, 7 segment)
*/
void handleOverlayDraw()
{
//strip.setPixelColor(0, RGBW32(0,0,0,0)) // set the first pixel to black
}
/**
* handleButton() can be used to override default button behaviour. Returning true
* will prevent button working in a default way.
* Replicating button.cpp
*/
bool handleButton(uint8_t b) {
yield();
// ignore certain button types as they may have other consequences
if (!enabled
|| buttonType[b] == BTN_TYPE_NONE
|| buttonType[b] == BTN_TYPE_RESERVED
|| buttonType[b] == BTN_TYPE_PIR_SENSOR
|| buttonType[b] == BTN_TYPE_ANALOG
|| buttonType[b] == BTN_TYPE_ANALOG_INVERTED) {
return false;
}
bool handled = false;
// do your button handling here
return handled;
}
#ifndef WLED_DISABLE_MQTT
/**
* handling of MQTT message
* topic only contains stripped topic (part after /wled/MAC)
*/
bool onMqttMessage(char* topic, char* payload) {
// check if we received a command
//if (strlen(topic) == 8 && strncmp_P(topic, PSTR("/command"), 8) == 0) {
// String action = payload;
// if (action == "on") {
// enabled = true;
// return true;
// } else if (action == "off") {
// enabled = false;
// return true;
// } else if (action == "toggle") {
// enabled = !enabled;
// return true;
// }
//}
return false;
}
/**
* onMqttConnect() is called when MQTT connection is established
*/
void onMqttConnect(bool sessionPresent) {
// do any MQTT related initialisation here
//publishMqtt("I am alive!");
}
#endif
/**
* onStateChanged() is used to detect WLED state change
* @mode parameter is CALL_MODE_... parameter used for notifications
*/
void onStateChange(uint8_t mode) {
// do something if WLED state changed (color, brightness, effect, preset, etc)
}
/*
* getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!).
* This could be used in the future for the system to determine whether your usermod is installed.
@ -117,3 +383,24 @@ class MyExampleUsermod : public Usermod {
//More methods can be added in the future, this example will then be extended.
//Your usermod will remain compatible as it does not need to implement all methods from the Usermod base class!
};
// add more strings here to reduce flash memory usage
const char MyExampleUsermod::_name[] PROGMEM = "ExampleUsermod";
const char MyExampleUsermod::_enabled[] PROGMEM = "enabled";
// implementation of non-inline member methods
void MyExampleUsermod::publishMqtt(const char* state, bool retain)
{
#ifndef WLED_DISABLE_MQTT
//Check if MQTT Connected, otherwise it will crash the 8266
if (WLED_MQTT_CONNECTED) {
char subuf[64];
strcpy(subuf, mqttDeviceTopic);
strcat_P(subuf, PSTR("/example"));
mqtt->publish(subuf, 0, retain, state);
}
#endif
}

View File

@ -0,0 +1,70 @@
#ifndef CHIP_SELECT_H
#define CHIP_SELECT_H
#include "Hardware.h"
/*
* `digit`s are as defined in Hardware.h, 0 == seconds ones, 5 == hours tens.
*/
class ChipSelect {
private:
uint8_t digits_map;
const uint8_t all_on = 0x3F;
const uint8_t all_off = 0x00;
public:
ChipSelect() : digits_map(all_off) {}
void update() {
// Documented in README.md. Q7 and Q6 are unused. Q5 is Seconds Ones, Q0 is Hours Tens.
// Q7 is the first bit written, Q0 is the last. So we push two dummy bits, then start with
// Seconds Ones and end with Hours Tens.
// CS is Active Low, but digits_map is 1 for enable, 0 for disable. So we bit-wise NOT first.
uint8_t to_shift = (~digits_map) << 2;
digitalWrite(CSSR_LATCH_PIN, LOW);
shiftOut(CSSR_DATA_PIN, CSSR_CLOCK_PIN, LSBFIRST, to_shift);
digitalWrite(CSSR_LATCH_PIN, HIGH);
}
void begin()
{
pinMode(CSSR_LATCH_PIN, OUTPUT);
pinMode(CSSR_DATA_PIN, OUTPUT);
pinMode(CSSR_CLOCK_PIN, OUTPUT);
digitalWrite(CSSR_DATA_PIN, LOW);
digitalWrite(CSSR_CLOCK_PIN, LOW);
digitalWrite(CSSR_LATCH_PIN, LOW);
update();
}
// These speak the indexes defined in Hardware.h.
// So 0 is disabled, 1 is enabled (even though CS is active low, this gets mapped.)
// So bit 0 (LSB), is index 0, is SECONDS_ONES
// Translation to what the 74HC595 uses is done in update()
void setDigitMap(uint8_t map, bool update_=true) { digits_map = map; if (update_) update(); }
uint8_t getDigitMap() { return digits_map; }
// Helper functions
// Sets just the one digit by digit number
void setDigit(uint8_t digit, bool update_=true) { setDigitMap(0x01 << digit, update_); }
void setAll(bool update_=true) { setDigitMap(all_on, update_); }
void clear(bool update_=true) { setDigitMap(all_off, update_); }
void setSecondsOnes() { setDigit(SECONDS_ONES); }
void setSecondsTens() { setDigit(SECONDS_TENS); }
void setMinutesOnes() { setDigit(MINUTES_ONES); }
void setMinutesTens() { setDigit(MINUTES_TENS); }
void setHoursOnes() { setDigit(HOURS_ONES); }
void setHoursTens() { setDigit(HOURS_TENS); }
bool isSecondsOnes() { return ((digits_map & SECONDS_ONES_MAP) > 0); }
bool isSecondsTens() { return ((digits_map & SECONDS_TENS_MAP) > 0); }
bool isMinutesOnes() { return ((digits_map & MINUTES_ONES_MAP) > 0); }
bool isMinutesTens() { return ((digits_map & MINUTES_TENS_MAP) > 0); }
bool isHoursOnes() { return ((digits_map & HOURS_ONES_MAP) > 0); }
bool isHoursTens() { return ((digits_map & HOURS_TENS_MAP) > 0); }
};
#endif // CHIP_SELECT_H

View File

@ -0,0 +1,52 @@
/*
* Define the hardware for the EleksTube IPS clock. Mostly pin definitions
*/
#ifndef ELEKSTUBEHAX_HARDWARE_H
#define ELEKSTUBEHAX_HARDWARE_H
#include <stdint.h>
#include <Arduino.h> // for HIGH and LOW
// Common indexing scheme, used to identify the digit
#define SECONDS_ONES (0)
#define SECONDS_TENS (1)
#define MINUTES_ONES (2)
#define MINUTES_TENS (3)
#define HOURS_ONES (4)
#define HOURS_TENS (5)
#define NUM_DIGITS (6)
#define SECONDS_ONES_MAP (0x01 << SECONDS_ONES)
#define SECONDS_TENS_MAP (0x01 << SECONDS_TENS)
#define MINUTES_ONES_MAP (0x01 << MINUTES_ONES)
#define MINUTES_TENS_MAP (0x01 << MINUTES_TENS)
#define HOURS_ONES_MAP (0x01 << HOURS_ONES)
#define HOURS_TENS_MAP (0x01 << HOURS_TENS)
// WS2812 (or compatible) LEDs on the back of the display modules.
#define BACKLIGHTS_PIN (12)
// Buttons, active low, externally pulled up (with actual resistors!)
#define BUTTON_LEFT_PIN (33)
#define BUTTON_MODE_PIN (32)
#define BUTTON_RIGHT_PIN (35)
#define BUTTON_POWER_PIN (34)
// I2C to DS3231 RTC.
#define RTC_SCL_PIN (22)
#define RTC_SDA_PIN (21)
// Chip Select shift register, to select the display
#define CSSR_DATA_PIN (14)
#define CSSR_CLOCK_PIN (16)
#define CSSR_LATCH_PIN (17)
// SPI to displays
// DEFINED IN User_Setup.h
// Look for: TFT_MOSI, TFT_SCLK, TFT_CS, TFT_DC, and TFT_RST
// Power for all TFT displays are grounded through a MOSFET so they can all be turned off.
// Active HIGH.
#define TFT_ENABLE_PIN (27)
#endif // ELEKSTUBEHAX_HARDWARE_H

View File

@ -0,0 +1,379 @@
#ifndef TFTS_H
#define TFTS_H
#include "wled.h"
#include <FS.h>
#include <TFT_eSPI.h>
#include "Hardware.h"
#include "ChipSelect.h"
class TFTs : public TFT_eSPI {
private:
uint8_t digits[NUM_DIGITS];
// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.
uint16_t read16(fs::File &f) {
uint16_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read(); // MSB
return result;
}
uint32_t read32(fs::File &f) {
uint32_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read();
((uint8_t *)&result)[2] = f.read();
((uint8_t *)&result)[3] = f.read(); // MSB
return result;
}
uint16_t output_buffer[TFT_HEIGHT][TFT_WIDTH];
int16_t w = 135, h = 240, x = 0, y = 0, bufferedDigit = 255;
uint16_t digitR, digitG, digitB, dimming = 255;
uint32_t digitColor = 0;
void drawBuffer() {
bool oldSwapBytes = getSwapBytes();
setSwapBytes(true);
pushImage(x, y, w, h, (uint16_t *)output_buffer);
setSwapBytes(oldSwapBytes);
}
// These BMP functions are stolen directly from the TFT_SPIFFS_BMP example in the TFT_eSPI library.
// Unfortunately, they aren't part of the library itself, so I had to copy them.
// I've modified drawBmp to buffer the whole image at once instead of doing it line-by-line.
//// BEGIN STOLEN CODE
// Draw directly from file stored in RGB565 format. Fastest
bool drawBin(const char *filename) {
fs::File bmpFS;
// Open requested file on SD card
bmpFS = WLED_FS.open(filename, "r");
size_t sz = bmpFS.size();
if (sz > 64800) {
bmpFS.close();
return false;
}
uint16_t r, g, b, dimming = 255;
int16_t row, col;
//draw img that is shorter than 240pix into the center
w = 135;
h = sz / (w * 2);
x = 0;
y = (height() - h) /2;
uint8_t lineBuffer[w * 2];
if (!realtimeMode || realtimeOverride || (realtimeMode && useMainSegmentOnly)) strip.service();
// 0,0 coordinates are top left
for (row = 0; row < h; row++) {
bmpFS.read(lineBuffer, sizeof(lineBuffer));
uint8_t PixM, PixL;
// Colors are already in 16-bit R5, G6, B5 format
for (col = 0; col < w; col++)
{
if (dimming == 255 && !digitColor) { // not needed, copy directly
output_buffer[row][col] = (lineBuffer[col*2+1] << 8) | (lineBuffer[col*2]);
} else {
// 16 BPP pixel format: R5, G6, B5 ; bin: RRRR RGGG GGGB BBBB
PixM = lineBuffer[col*2+1];
PixL = lineBuffer[col*2];
// align to 8-bit value (MSB left aligned)
r = (PixM) & 0xF8;
g = ((PixM << 5) | (PixL >> 3)) & 0xFC;
b = (PixL << 3) & 0xF8;
r *= dimming; g *= dimming; b *= dimming;
r = r >> 8; g = g >> 8; b = b >> 8;
if (digitColor) { // grayscale pixel coloring
uint8_t l = (r > g) ? ((r > b) ? r:b) : ((g > b) ? g:b);
r = g = b = l;
r *= digitR; g *= digitG; b *= digitB;
r = r >> 8; g = g >> 8; b = b >> 8;
}
output_buffer[row][col] = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}
}
}
drawBuffer();
bmpFS.close();
return true;
}
bool drawBmp(const char *filename) {
fs::File bmpFS;
// Open requested file on SD card
bmpFS = WLED_FS.open(filename, "r");
uint32_t seekOffset, headerSize, paletteSize = 0;
int16_t row;
uint16_t r, g, b, dimming = 255, bitDepth;
uint16_t magic = read16(bmpFS);
if (magic != ('B' | ('M' << 8))) { // File not found or not a BMP
Serial.println(F("BMP not found!"));
bmpFS.close();
return false;
}
(void) read32(bmpFS); // filesize in bytes
(void) read32(bmpFS); // reserved
seekOffset = read32(bmpFS); // start of bitmap
headerSize = read32(bmpFS); // header size
w = read32(bmpFS); // width
h = read32(bmpFS); // height
(void) read16(bmpFS); // color planes (must be 1)
bitDepth = read16(bmpFS);
if (read32(bmpFS) != 0 || (bitDepth != 24 && bitDepth != 1 && bitDepth != 4 && bitDepth != 8)) {
Serial.println(F("BMP format not recognized."));
bmpFS.close();
return false;
}
uint32_t palette[256];
if (bitDepth <= 8) // 1,4,8 bit bitmap: read color palette
{
(void) read32(bmpFS); (void) read32(bmpFS); (void) read32(bmpFS); // size, w resolution, h resolution
paletteSize = read32(bmpFS);
if (paletteSize == 0) paletteSize = 1 << bitDepth; //if 0, size is 2^bitDepth
bmpFS.seek(14 + headerSize); // start of color palette
for (uint16_t i = 0; i < paletteSize; i++) {
palette[i] = read32(bmpFS);
}
}
// draw img that is shorter than 240pix into the center
x = (width() - w) /2;
y = (height() - h) /2;
bmpFS.seek(seekOffset);
uint32_t lineSize = ((bitDepth * w +31) >> 5) * 4;
uint8_t lineBuffer[lineSize];
uint8_t serviceStrip = (!realtimeMode || realtimeOverride || (realtimeMode && useMainSegmentOnly)) ? 7 : 0;
// row is decremented as the BMP image is drawn bottom up
for (row = h-1; row >= 0; row--) {
if ((row & 0b00000111) == serviceStrip) strip.service(); //still refresh backlight to mitigate stutter every few rows
bmpFS.read(lineBuffer, sizeof(lineBuffer));
uint8_t* bptr = lineBuffer;
// Convert 24 to 16 bit colors while copying to output buffer.
for (uint16_t col = 0; col < w; col++)
{
if (bitDepth == 24) {
b = *bptr++;
g = *bptr++;
r = *bptr++;
} else {
uint32_t c = 0;
if (bitDepth == 8) {
c = palette[*bptr++];
}
else if (bitDepth == 4) {
c = palette[(*bptr >> ((col & 0x01)?0:4)) & 0x0F];
if (col & 0x01) bptr++;
}
else { // bitDepth == 1
c = palette[(*bptr >> (7 - (col & 0x07))) & 0x01];
if ((col & 0x07) == 0x07) bptr++;
}
b = c; g = c >> 8; r = c >> 16;
}
if (dimming != 255) { // only dim when needed
r *= dimming; g *= dimming; b *= dimming;
r = r >> 8; g = g >> 8; b = b >> 8;
}
if (digitColor) { // grayscale pixel coloring
uint8_t l = (r > g) ? ((r > b) ? r:b) : ((g > b) ? g:b);
r = g = b = l;
r *= digitR; g *= digitG; b *= digitB;
r = r >> 8; g = g >> 8; b = b >> 8;
}
output_buffer[row][col] = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | ((b & 0xFF) >> 3);
}
}
drawBuffer();
bmpFS.close();
return true;
}
bool drawClk(const char *filename) {
fs::File bmpFS;
// Open requested file on SD card
bmpFS = WLED_FS.open(filename, "r");
if (!bmpFS)
{
Serial.print("File not found: ");
Serial.println(filename);
return false;
}
uint16_t r, g, b, dimming = 255, magic;
int16_t row, col;
magic = read16(bmpFS);
if (magic != 0x4B43) { // look for "CK" header
Serial.print(F("File not a CLK. Magic: "));
Serial.println(magic);
bmpFS.close();
return false;
}
w = read16(bmpFS);
h = read16(bmpFS);
x = (width() - w) / 2;
y = (height() - h) / 2;
uint8_t lineBuffer[w * 2];
if (!realtimeMode || realtimeOverride || (realtimeMode && useMainSegmentOnly)) strip.service();
// 0,0 coordinates are top left
for (row = 0; row < h; row++) {
bmpFS.read(lineBuffer, sizeof(lineBuffer));
uint8_t PixM, PixL;
// Colors are already in 16-bit R5, G6, B5 format
for (col = 0; col < w; col++)
{
if (dimming == 255 && !digitColor) { // not needed, copy directly
output_buffer[row][col+x] = (lineBuffer[col*2+1] << 8) | (lineBuffer[col*2]);
} else {
// 16 BPP pixel format: R5, G6, B5 ; bin: RRRR RGGG GGGB BBBB
PixM = lineBuffer[col*2+1];
PixL = lineBuffer[col*2];
// align to 8-bit value (MSB left aligned)
r = (PixM) & 0xF8;
g = ((PixM << 5) | (PixL >> 3)) & 0xFC;
b = (PixL << 3) & 0xF8;
r *= dimming; g *= dimming; b *= dimming;
r = r >> 8; g = g >> 8; b = b >> 8;
if (digitColor) { // grayscale pixel coloring
uint8_t l = (r > g) ? ((r > b) ? r:b) : ((g > b) ? g:b);
r = g = b = l;
r *= digitR; g *= digitG; b *= digitB;
r = r >> 8; g = g >> 8; b = b >> 8;
}
output_buffer[row][col+x] = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}
}
}
drawBuffer();
bmpFS.close();
return true;
}
public:
TFTs() : TFT_eSPI(), chip_select()
{ for (uint8_t digit=0; digit < NUM_DIGITS; digit++) digits[digit] = 0; }
// no == Do not send to TFT. yes == Send to TFT if changed. force == Send to TFT.
enum show_t { no, yes, force };
// A digit of 0xFF means blank the screen.
const static uint8_t blanked = 255;
uint8_t tubeSegment = 1;
uint8_t digitOffset = 0;
void begin() {
pinMode(TFT_ENABLE_PIN, OUTPUT);
digitalWrite(TFT_ENABLE_PIN, HIGH); //enable displays on boot
// Start with all displays selected.
chip_select.begin();
chip_select.setAll();
// Initialize the super class.
init();
}
void showDigit(uint8_t digit) {
chip_select.setDigit(digit);
uint8_t digitToDraw = digits[digit];
if (digitToDraw < 10) digitToDraw += digitOffset;
if (digitToDraw == blanked) {
fillScreen(TFT_BLACK); return;
}
// if last digit was the same, skip loading from FS to buffer
if (!digitColor && digitToDraw == bufferedDigit) drawBuffer();
digitR = R(digitColor); digitG = G(digitColor); digitB = B(digitColor);
// Filenames are no bigger than "254.bmp\0"
char file_name[10];
// Fastest, raw RGB565
sprintf(file_name, "/%d.bin", digitToDraw);
if (WLED_FS.exists(file_name)) {
if (drawBin(file_name)) bufferedDigit = digitToDraw;
return;
}
// Fast, raw RGB565, see https://github.com/aly-fly/EleksTubeHAX on how to create this clk format
sprintf(file_name, "/%d.clk", digitToDraw);
if (WLED_FS.exists(file_name)) {
if (drawClk(file_name)) bufferedDigit = digitToDraw;
return;
}
// Slow, regular RGB888 or 1,4,8 bit palette BMP
sprintf(file_name, "/%d.bmp", digitToDraw);
if (drawBmp(file_name)) bufferedDigit = digitToDraw;
return;
}
void setDigit(uint8_t digit, uint8_t value, show_t show=yes) {
uint8_t old_value = digits[digit];
digits[digit] = value;
// Color in grayscale bitmaps if Segment 1 exists
// TODO If secondary and tertiary are black, color all in primary,
// else color first three from Seg 1 color slots and last three from Seg 2 color slots
Segment& seg1 = strip.getSegment(tubeSegment);
if (seg1.isActive()) {
digitColor = strip.getPixelColor(seg1.start + digit);
dimming = seg1.opacity;
} else {
digitColor = 0;
dimming = 255;
}
if (show != no && (old_value != value || show == force)) {
showDigit(digit);
}
}
uint8_t getDigit(uint8_t digit) {return digits[digit];}
void showAllDigits() {for (uint8_t digit=0; digit < NUM_DIGITS; digit++) showDigit(digit);}
// Making chip_select public so we don't have to proxy all methods, and the caller can just use it directly.
ChipSelect chip_select;
};
#endif // TFTS_H

View File

@ -0,0 +1,47 @@
/*
* This is intended to over-ride `User_Setup.h` that comes with the TFT_eSPI library.
* I hate having to modify the library code.
*/
// ST7789 135 x 240 display with no chip select line
#define ST7789_DRIVER // Configure all registers
#define TFT_WIDTH 135
#define TFT_HEIGHT 240
#define CGRAM_OFFSET // Library will add offsets required
//#define TFT_RGB_ORDER TFT_RGB // Colour order Red-Green-Blue
//#define TFT_RGB_ORDER TFT_BGR // Colour order Blue-Green-Red
//#define TFT_INVERSION_ON
//#define TFT_INVERSION_OFF
// EleksTube IPS
#define TFT_SDA_READ // Read and write on the MOSI/SDA pin, no separate MISO pin
#define TFT_MOSI 23
#define TFT_SCLK 18
//#define TFT_CS -1 // Not connected
#define TFT_DC 25 // Data Command, aka Register Select or RS
#define TFT_RST 26 // Connect reset to ensure display initialises
#define LOAD_GLCD // Font 1. Original Adafruit 8 pixel font needs ~1820 bytes in FLASH
//#define LOAD_FONT2 // Font 2. Small 16 pixel high font, needs ~3534 bytes in FLASH, 96 characters
//#define LOAD_FONT4 // Font 4. Medium 26 pixel high font, needs ~5848 bytes in FLASH, 96 characters
//#define LOAD_FONT6 // Font 6. Large 48 pixel font, needs ~2666 bytes in FLASH, only characters 1234567890:-.apm
//#define LOAD_FONT7 // Font 7. 7 segment 48 pixel font, needs ~2438 bytes in FLASH, only characters 1234567890:.
//#define LOAD_FONT8 // Font 8. Large 75 pixel font needs ~3256 bytes in FLASH, only characters 1234567890:-.
//#define LOAD_FONT8N // Font 8. Alternative to Font 8 above, slightly narrower, so 3 digits fit a 160 pixel TFT
//#define LOAD_GFXFF // FreeFonts. Include access to the 48 Adafruit_GFX free fonts FF1 to FF48 and custom fonts
//#define SMOOTH_FONT
//#define SPI_FREQUENCY 27000000
#define SPI_FREQUENCY 40000000
/*
* To make the Library not over-write all this:
*/
#define USER_SETUP_LOADED

View File

@ -0,0 +1,45 @@
# EleksTube IPS Clock usermod
This usermod allows WLED to run on the EleksTube IPS clock.
It enables running all WLED effects on the background SK6812 lighting, while displaying digit bitmaps on the 6 IPS screens.
Code is largely based on https://github.com/SmittyHalibut/EleksTubeHAX by Mark Smith!
Supported:
- Display with custom bitmaps (.bmp) or raw RGB565 images (.bin) from filesystem
- Background lighting
- All 4 hardware buttons
- RTC (with RTC usermod)
- Standard WLED time features (NTP, DST, timezones)
Not supported:
- On-device setup with buttons (WiFi setup only)
Your images must be 1-135 pixels wide and 1-240 pixels high.
BMP 1, 4, 8, and 24 bits per pixel formats are supported.
## Installation
Compile and upload to clock using the `elekstube_ips` PlatformIO environment
Once uploaded (the clock can be flashed like any ESP32 module), go to `[WLED-IP]/edit` and upload the 0-9.bin files from [here](https://github.com/Aircoookie/NixieThemes/tree/master/themes/RealisticNixie/bin).
You can find more clockfaces in the [NixieThemes](https://github.com/Aircoookie/NixieThemes/) repo.
Use LED pin 12, relay pin 27 and button pin 34.
## Use of RGB565 images
Binary 16-bit per pixel RGB565 format `.bin` and `.clk` images are now supported. This has the benefit of using only 2/3rds of the file space a 24 BPP `.bmp` occupies.
The drawback is this format cannot be handled by common image programs and an extra conversion step is needed.
You can use https://lvgl.io/tools/imageconverter to convert your .bmp to a .bin file (settings `True color` and `Binary RGB565`).
Thank you to @RedNax67 for adding .bin and .clk support.
For most clockface designs, using 4 or 8 BPP BMP format will reduce file size even more:
| Bits per pixel | File size in kB (for 135x240 img) | % of 24 BPP BMP | Max unique colors
| --- | --- | --- | --- |
24 | 98 | 100% | 16M (66K)
16 (.clk) | 64.8 | 66% | 66K
8 | 33.7 | 34% | 256
4 | 16.4 | 17% | 16
1 | 4.9 | 5% | 2
Comparison 1 vs. 4 vs. 8 vs. 24 BPP. With this clockface on the actual clock, 4 bit looks good, and 8 bit is almost indistinguishable from 24 bit.
![comparison](https://user-images.githubusercontent.com/21045690/156899667-5b55ed9f-6e03-4066-b2aa-1260e9570369.png)

View File

@ -0,0 +1,158 @@
#pragma once
#include "TFTs.h"
#include "wled.h"
//Large parts of the code are from https://github.com/SmittyHalibut/EleksTubeHAX
class ElekstubeIPSUsermod : public Usermod {
private:
// strings to reduce flash memory usage (used more than twice)
static const char _name[];
static const char _tubeSeg[];
static const char _digitOffset[];
char cronixieDisplay[7] = "HHMMSS";
TFTs tfts;
void updateClockDisplay(TFTs::show_t show=TFTs::yes) {
bool set[6] = {false};
for (uint8_t i = 0; i<6; i++) {
char c = cronixieDisplay[i];
if (c >= '0' && c <= '9') {
tfts.setDigit(5-i, c - '0', show); set[i] = true;
} else if (c >= 'A' && c <= 'G') {
tfts.setDigit(5-i, c - 'A' + 10, show); set[i] = true; //10.bmp to 16.bmp static display
} else if (c == '-' || c == '_' || c == ' ') {
tfts.setDigit(5-i, 255, show); set[i] = true; //blank
} else {
set[i] = false; //display HHMMSS time
}
}
uint8_t hr = hour(localTime);
uint8_t hrTens = hr/10;
uint8_t mi = minute(localTime);
uint8_t mittens = mi/10;
uint8_t s = second(localTime);
uint8_t sTens = s/10;
if (!set[0]) tfts.setDigit(HOURS_TENS, hrTens, show);
if (!set[1]) tfts.setDigit(HOURS_ONES, hr - hrTens*10, show);
if (!set[2]) tfts.setDigit(MINUTES_TENS, mittens, show);
if (!set[3]) tfts.setDigit(MINUTES_ONES, mi - mittens*10, show);
if (!set[4]) tfts.setDigit(SECONDS_TENS, sTens, show);
if (!set[5]) tfts.setDigit(SECONDS_ONES, s - sTens*10, show);
}
unsigned long lastTime = 0;
public:
uint8_t lastBri;
uint32_t lastCols[6];
TFTs::show_t fshow=TFTs::yes;
void setup() {
tfts.begin();
tfts.fillScreen(TFT_BLACK);
for (int8_t i = 5; i >= 0; i--) {
tfts.setDigit(i, 255, TFTs::force); //turn all off
}
}
void loop() {
if (!toki.isTick()) return;
updateLocalTime();
Segment& seg1 = strip.getSegment(tfts.tubeSegment);
if (seg1.isActive()) {
bool update = false;
if (seg1.opacity != lastBri) update = true;
lastBri = seg1.opacity;
for (uint8_t i = 0; i < 6; i++) {
uint32_t c = strip.getPixelColor(seg1.start + i);
if (c != lastCols[i]) update = true;
lastCols[i] = c;
}
if (update) fshow=TFTs::force;
} else if (lastCols[0] != 0) { // Segment 1 deleted
fshow=TFTs::force;
lastCols[0] = 0;
}
updateClockDisplay(fshow);
fshow=TFTs::yes;
}
/**
* addToConfig() (called from set.cpp) stores persistent properties to cfg.json
*/
void addToConfig(JsonObject &root) {
// we add JSON object: {"EleksTubeIPS": {"tubeSegment": 1, "digitOffset": 0}}
JsonObject top = root.createNestedObject(FPSTR(_name)); // usermodname
top[FPSTR(_tubeSeg)] = tfts.tubeSegment;
top[FPSTR(_digitOffset)] = tfts.digitOffset;
DEBUG_PRINTLN(F("EleksTube config saved."));
}
/**
* readFromConfig() is called before setup() to populate properties from values stored in cfg.json
*
* The function should return true if configuration was successfully loaded or false if there was no configuration.
*/
bool readFromConfig(JsonObject &root) {
// we look for JSON object: {"EleksTubeIPS": {"tubeSegment": 1, "digitOffset": 0}}
DEBUG_PRINT(FPSTR(_name));
JsonObject top = root[FPSTR(_name)];
if (top.isNull()) {
DEBUG_PRINTLN(F(": No config found. (Using defaults.)"));
return false;
}
tfts.tubeSegment = top[FPSTR(_tubeSeg)] | tfts.tubeSegment;
uint8_t digitOffsetPrev = tfts.digitOffset;
tfts.digitOffset = top[FPSTR(_digitOffset)] | tfts.digitOffset;
if (tfts.digitOffset > 240) tfts.digitOffset = 240;
if (tfts.digitOffset != digitOffsetPrev) fshow=TFTs::force;
// use "return !top["newestParameter"].isNull();" when updating Usermod with new features
return !top[FPSTR(_digitOffset)].isNull();
}
/*
* addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object).
* Values in the state object may be modified by connected clients
*/
void addToJsonState(JsonObject& root)
{
root["nx"] = cronixieDisplay;
root[FPSTR(_digitOffset)] = tfts.digitOffset;
}
/*
* readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object).
* Values in the state object may be modified by connected clients
*/
void readFromJsonState(JsonObject& root)
{
if (root["nx"].is<const char*>()) {
strncpy(cronixieDisplay, root["nx"], 6);
}
uint8_t digitOffsetPrev = tfts.digitOffset;
tfts.digitOffset = root[FPSTR(_digitOffset)] | tfts.digitOffset;
if (tfts.digitOffset > 240) tfts.digitOffset = 240;
if (tfts.digitOffset != digitOffsetPrev) fshow=TFTs::force;
}
uint16_t getId()
{
return USERMOD_ID_ELEKSTUBE_IPS;
}
};
// strings to reduce flash memory usage (used more than twice)
const char ElekstubeIPSUsermod::_name[] PROGMEM = "EleksTubeIPS";
const char ElekstubeIPSUsermod::_tubeSeg[] PROGMEM = "tubeSegment";
const char ElekstubeIPSUsermod::_digitOffset[] PROGMEM = "digitOffset";

Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 235 KiB

After

Width:  |  Height:  |  Size: 201 KiB

View File

@ -10,7 +10,7 @@ For BME280 sensor use usermod_bme280.cpp. Copy to wled00 and rename to usermod.c
## Features
- SSD1306 128x32 and 128x64 I2C OLED display
- On screen IP address, SSID and controller status (e.g. ON or OFF, recent effect)
- Auto display shutoff for saving display lifetime
- Auto display shutoff for extending display lifetime
- Dallas temperature sensor
- Reporting temperature to MQTT broker
@ -39,15 +39,15 @@ default_envs = esp07
...
lib_deps_external =
...
#For use SSD1306 OLED display uncomment following
#To use the SSD1306 OLED display, uncomment following
U8g2@~2.27.3
#For Dallas sensor uncomment following 2 lines
#For Dallas sensor, uncomment the following 2 lines
DallasTemperature@~3.8.0
OneWire@~2.3.5
...
```
For BME280 sensor uncomment `U8g2@~2.27.3`,`BME280@~3.0.0 under` `[common]` section in `platformio.ini`:
For BME280 sensor, uncomment `U8g2@~2.27.3`,`BME280@~3.0.0 under` `[common]` section in `platformio.ini`:
```ini
# platformio.ini
...
@ -60,7 +60,7 @@ default_envs = esp07
...
lib_deps_external =
...
#For use SSD1306 OLED display uncomment following
#To use the SSD1306 OLED display, uncomment following
U8g2@~2.27.3
#For BME280 sensor uncomment following
BME280@~3.0.0

View File

@ -1,3 +1,7 @@
#ifndef WLED_ENABLE_MQTT
#error "This user mod requires MQTT to be enabled."
#endif
#include "wled.h"
#include <Arduino.h>
#include <U8x8lib.h> // from https://github.com/olikraus/u8g2/
@ -100,9 +104,9 @@ void userLoop() {
needRedraw = true;
} else if (knownBrightness != bri) {
needRedraw = true;
} else if (knownMode != strip.getMode()) {
} else if (knownMode != strip.getMainSegment().mode) {
needRedraw = true;
} else if (knownPalette != strip.getSegment(0).palette) {
} else if (knownPalette != strip.getMainSegment().palette) {
needRedraw = true;
}
@ -126,8 +130,8 @@ void userLoop() {
#endif
knownIp = apActive ? IPAddress(4, 3, 2, 1) : WiFi.localIP();
knownBrightness = bri;
knownMode = strip.getMode();
knownPalette = strip.getSegment(0).palette;
knownMode = strip.getMainSegment().mode;
knownPalette = strip.getMainSegment().palette;
u8x8.clear();
u8x8.setFont(u8x8_font_chroma48medium8_r);
@ -148,58 +152,14 @@ void userLoop() {
// Third row with mode name
u8x8.setCursor(2, 2);
uint8_t qComma = 0;
bool insideQuotes = false;
uint8_t printedChars = 0;
char singleJsonSymbol;
char lineBuffer[17];
extractModeName(knownMode, JSON_mode_names, lineBuffer, 16);
u8x8.print(lineBuffer);
// Find the mode name in JSON
for (size_t i = 0; i < strlen_P(JSON_mode_names); i++) {
singleJsonSymbol = pgm_read_byte_near(JSON_mode_names + i);
switch (singleJsonSymbol) {
case '"':
insideQuotes = !insideQuotes;
break;
case '[':
case ']':
break;
case ',':
qComma++;
default:
if (!insideQuotes || (qComma != knownMode))
break;
u8x8.print(singleJsonSymbol);
printedChars++;
}
if ((qComma > knownMode) || (printedChars > u8x8.getCols() - 2))
break;
}
// Fourth row with palette name
u8x8.setCursor(2, 3);
qComma = 0;
insideQuotes = false;
printedChars = 0;
// Looking for palette name in JSON.
for (size_t i = 0; i < strlen_P(JSON_palette_names); i++) {
singleJsonSymbol = pgm_read_byte_near(JSON_palette_names + i);
switch (singleJsonSymbol) {
case '"':
insideQuotes = !insideQuotes;
break;
case '[':
case ']':
break;
case ',':
qComma++;
default:
if (!insideQuotes || (qComma != knownPalette))
break;
u8x8.print(singleJsonSymbol);
printedChars++;
}
if ((qComma > knownMode) || (printedChars > u8x8.getCols() - 2))
break;
}
extractModeName(knownPalette, JSON_palette_names, lineBuffer, 16);
u8x8.print(lineBuffer);
u8x8.setFont(u8x8_font_open_iconic_embedded_1x1);
u8x8.drawGlyph(0, 0, 80); // wifi icon

View File

@ -1,3 +1,7 @@
#ifndef WLED_ENABLE_MQTT
#error "This user mod requires MQTT to be enabled."
#endif
#include "wled.h"
#include <Arduino.h>
#include <U8x8lib.h> // from https://github.com/olikraus/u8g2/
@ -143,9 +147,9 @@ void userLoop() {
needRedraw = true;
} else if (knownBrightness != bri) {
needRedraw = true;
} else if (knownMode != strip.getMode()) {
} else if (knownMode != strip.getMainSegment().mode) {
needRedraw = true;
} else if (knownPalette != strip.getSegment(0).palette) {
} else if (knownPalette != strip.getMainSegment().palette) {
needRedraw = true;
}
@ -169,8 +173,8 @@ void userLoop() {
#endif
knownIp = apActive ? IPAddress(4, 3, 2, 1) : WiFi.localIP();
knownBrightness = bri;
knownMode = strip.getMode();
knownPalette = strip.getSegment(0).palette;
knownMode = strip.getMainSegment().mode;
knownPalette = strip.getMainSegment().palette;
u8x8.clear();
u8x8.setFont(u8x8_font_chroma48medium8_r);
@ -191,58 +195,14 @@ void userLoop() {
// Third row with mode name
u8x8.setCursor(2, 2);
uint8_t qComma = 0;
bool insideQuotes = false;
uint8_t printedChars = 0;
char singleJsonSymbol;
char lineBuffer[17];
extractModeName(knownMode, JSON_mode_names, lineBuffer, 16);
u8x8.print(lineBuffer);
// Find the mode name in JSON
for (size_t i = 0; i < strlen_P(JSON_mode_names); i++) {
singleJsonSymbol = pgm_read_byte_near(JSON_mode_names + i);
switch (singleJsonSymbol) {
case '"':
insideQuotes = !insideQuotes;
break;
case '[':
case ']':
break;
case ',':
qComma++;
default:
if (!insideQuotes || (qComma != knownMode))
break;
u8x8.print(singleJsonSymbol);
printedChars++;
}
if ((qComma > knownMode) || (printedChars > u8x8.getCols() - 2))
break;
}
// Fourth row with palette name
u8x8.setCursor(2, 3);
qComma = 0;
insideQuotes = false;
printedChars = 0;
// Looking for palette name in JSON.
for (size_t i = 0; i < strlen_P(JSON_palette_names); i++) {
singleJsonSymbol = pgm_read_byte_near(JSON_palette_names + i);
switch (singleJsonSymbol) {
case '"':
insideQuotes = !insideQuotes;
break;
case '[':
case ']':
break;
case ',':
qComma++;
default:
if (!insideQuotes || (qComma != knownPalette))
break;
u8x8.print(singleJsonSymbol);
printedChars++;
}
if ((qComma > knownMode) || (printedChars > u8x8.getCols() - 2))
break;
}
extractModeName(knownPalette, JSON_palette_names, lineBuffer, 16);
u8x8.print(lineBuffer);
u8x8.setFont(u8x8_font_open_iconic_embedded_1x1);
u8x8.drawGlyph(0, 0, 80); // wifi icon

View File

@ -1,16 +1,32 @@
# Fix unreachable net services V2
This usermod-v2 modification performs a ping request to the local IP address every 60 seconds. By this procedure the net services of WLED remains accessible in some problematic WLAN environments.
**Attention: This usermod compiles only for ESP8266**
This usermod-v2 modification performs a ping request to a local IP address every 60 seconds. This ensures WLED net services remain accessible in some problematic WLAN environments.
The modification works with static or DHCP IP address configuration.
**Webinterface**: The number of pings and reconnects is displayed on the info page in the web interface.
_Story:_
Unfortunately, with all ESP projects where a web server or other network services are running, I have the problem that after some time the web server is no longer accessible. Now I found out that the connection is at least reestablished when a ping request is executed by the device.
Unfortunately, with many ESP projects where a web server or other network services are running, after some time, the connecton to the web server is lost.
The connection can be reestablished with a ping request from the device.
With this modification, in the worst case, the network functions are not available for 60 seconds until the next ping request.
With this modification, in the worst case, the network functions are not available until the next ping request. (60 seconds)
## Webinterface
The number of pings and reconnects is displayed on the info page in the web interface.
The ping delay can be changed. Changes persist after a reboot.
## JSON API
The usermod supports the following state changes:
| JSON key | Value range | Description |
|-------------|------------------|---------------------------------|
| PingDelayMs | 5000 to 18000000 | Deactivdate/activate the sensor |
Changes also persist after a reboot.
## Installation

View File

@ -1,6 +1,14 @@
#pragma once
#include "wled.h"
#if defined(ESP32)
#warning "Usermod FixUnreachableNetServices works only with ESP8266 builds"
class FixUnreachableNetServices : public Usermod
{
};
#endif
#if defined(ESP8266)
#include <ping.h>
/*
@ -23,34 +31,37 @@
* 2. Register the usermod by adding #include "usermod_filename.h" in the top and registerUsermod(new MyUsermodClass()) in the bottom of usermods_list.cpp
*/
class FixUnreachableNetServices : public Usermod {
private:
class FixUnreachableNetServices : public Usermod
{
private:
//Private class members. You can declare variables and functions only accessible to your usermod here
unsigned long m_lastTime = 0;
// desclare required variables
const unsigned int PingDelayMs = 60000;
// declare required variables
unsigned long m_pingDelayMs = 60000;
unsigned long m_connectedWiFi = 0;
ping_option m_pingOpt;
unsigned int m_pingCount = 0;
bool m_updateConfig = false;
public:
public:
//Functions called by WLED
/*
/**
* setup() is called once at boot. WiFi is not yet connected at this point.
* You can use it to initialize variables, sensors or similar.
*/
void setup() {
void setup()
{
//Serial.println("Hello from my usermod!");
}
/*
/**
* connected() is called every time the WiFi is (re)connected
* Use it to initialize network interfaces
*/
void connected() {
void connected()
{
//Serial.println("Connected to WiFi!");
++m_connectedWiFi;
@ -59,42 +70,44 @@ class FixUnreachableNetServices : public Usermod {
memset(&m_pingOpt, 0, sizeof(struct ping_option));
m_pingOpt.count = 1;
m_pingOpt.ip = WiFi.localIP();
}
/*
* loop() is called continuously. Here you can check for events, read sensors, etc.
*
* Tips:
* 1. You can use "if (WLED_CONNECTED)" to check for a successful network connection.
* Additionally, "if (WLED_MQTT_CONNECTED)" is available to check for a connection to an MQTT broker.
*
* 2. Try to avoid using the delay() function. NEVER use delays longer than 10 milliseconds.
* Instead, use a timer check as shown here.
/**
* loop
*/
void loop() {
if (m_connectedWiFi > 0 && millis()-m_lastTime > PingDelayMs)
void loop()
{
if (m_connectedWiFi > 0 && millis() - m_lastTime > m_pingDelayMs)
{
ping_start(&m_pingOpt);
m_lastTime = millis();
++m_pingCount;
}
if (m_updateConfig)
{
serializeConfig();
m_updateConfig = false;
}
}
/*
/**
* addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API.
* Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI.
* Below it is shown how this could be used for e.g. a light sensor
*/
void addToJsonInfo(JsonObject& root)
void addToJsonInfo(JsonObject &root)
{
//this code adds "u":{"&#x26A1; Ping fix pings": m_pingCount} to the info object
JsonObject user = root["u"];
if (user.isNull()) user = root.createNestedObject("u");
if (user.isNull())
user = root.createNestedObject("u");
JsonArray infoArr = user.createNestedArray("&#x26A1; Ping fix pings"); //name
String uiDomString = "&#x26A1; Ping fix pings<span style=\"display:block;padding-left:25px;\">\
Delay <input type=\"number\" min=\"5\" max=\"300\" value=\"";
uiDomString += (unsigned long)(m_pingDelayMs / 1000);
uiDomString += "\" onchange=\"requestJson({PingDelay:parseInt(this.value)});\">sec</span>";
JsonArray infoArr = user.createNestedArray(uiDomString); //name
infoArr.add(m_pingCount); //value
//this code adds "u":{"&#x26A1; Reconnects": m_connectedWiFi - 1} to the info object
@ -102,29 +115,51 @@ class FixUnreachableNetServices : public Usermod {
infoArr.add(m_connectedWiFi - 1); //value
}
/*
/**
* addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object).
* Values in the state object may be modified by connected clients
*/
void addToJsonState(JsonObject& root)
void addToJsonState(JsonObject &root)
{
//root["user0"] = userVar0;
root["PingDelay"] = (m_pingDelayMs/1000);
}
/*
/**
* readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object).
* Values in the state object may be modified by connected clients
*/
void readFromJsonState(JsonObject& root)
void readFromJsonState(JsonObject &root)
{
//userVar0 = root["user0"] | userVar0; //if "user0" key exists in JSON, update, else keep old value
//if (root["bri"] == 255) Serial.println(F("Don't burn down your garage!"));
if (root["PingDelay"] != nullptr)
{
m_pingDelayMs = (1000 * max(1UL, min(300UL, root["PingDelay"].as<unsigned long>())));
m_updateConfig = true;
}
}
/**
* provide the changeable values
*/
void addToConfig(JsonObject &root)
{
JsonObject top = root.createNestedObject("FixUnreachableNetServices");
top["PingDelayMs"] = m_pingDelayMs;
}
/*
/**
* restore the changeable values
*/
bool readFromConfig(JsonObject &root)
{
JsonObject top = root["FixUnreachableNetServices"];
if (top.isNull()) return false;
m_pingDelayMs = top["PingDelayMs"] | m_pingDelayMs;
m_pingDelayMs = max(5000UL, min(18000000UL, m_pingDelayMs));
// use "return !top["newestParameter"].isNull();" when updating Usermod with new features
return true;
}
/**
* getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!).
* This could be used in the future for the system to determine whether your usermod is installed.
*/
@ -132,7 +167,5 @@ class FixUnreachableNetServices : public Usermod {
{
return USERMOD_ID_FIXNETSERVICES;
}
//More methods can be added in the future, this example will then be extended.
//Your usermod will remain compatible as it does not need to implement all methods from the Usermod base class!
};
#endif

View File

@ -1,17 +0,0 @@
# Fix unreachable Webserver
This modification performs a ping request to the local IP address every 60 seconds. By this procedure the web server remains accessible in some problematic WLAN environments.
The modification works with static or DHCP IP address configuration
_Story:_
Unfortunately, with all ESP projects where a web server or other network services are running, I have the problem that after some time the web server is no longer accessible. Now I found out that the connection is at least reestablished when a ping request is executed by the device.
With this modification, in the worst case, the network functions are not available for 60 seconds until the next ping request.
## Installation
Copy and replace the file `usermod.cpp` in wled00 directory.

View File

@ -1,43 +0,0 @@
#include "wled.h"
/*
* This file allows you to add own functionality to WLED more easily
* See: https://github.com/Aircoookie/WLED/wiki/Add-own-functionality
* EEPROM bytes 2750+ are reserved for your custom use case. (if you extend #define EEPSIZE in const.h)
* bytes 2400+ are currently ununsed, but might be used for future wled features
*/
#include <ping.h>
const int PingDelayMs = 60000;
long lastCheckTime = 0;
bool connectedWiFi = false;
ping_option pingOpt;
//Use userVar0 and userVar1 (API calls &U0=,&U1=, uint16_t)
//gets called once at boot. Do all initialization that doesn't depend on network here
void userSetup()
{
}
//gets called every time WiFi is (re-)connected. Initialize own network interfaces here
void userConnected()
{
connectedWiFi = true;
// initialize ping_options structure
memset(&pingOpt, 0, sizeof(struct ping_option));
pingOpt.count = 1;
pingOpt.ip = WiFi.localIP();
}
//loop. You can use "if (WLED_CONNECTED)" to check for successful connection
void userLoop()
{
if (connectedWiFi && millis()-lastCheckTime > PingDelayMs)
{
ping_start(&pingOpt);
lastCheckTime = millis();
}
}

View File

@ -0,0 +1,119 @@
{
"desc": "21-key",
"0xFFA25D": {
"label": "On",
"pos": "1x1",
"cmd": "T=1"
},
"0xFF629D": {
"label": "Off",
"pos": "1x2",
"cmd": "T=0"
},
"0xFFE21D": {
"label": "Flash",
"pos": "1x3",
"cmnt": "Cycle Effects",
"cmd": "CY=0&FX=~"
},
"0xFF22DD": {
"label": "Strobe",
"pos": "2x1",
"cmnt": "Sinelon Dual",
"cmd": "CY=0&FX=93"
},
"0xFF02FD": {
"label": "Fade",
"pos": "2x2",
"cmnt": "Rain",
"cmd": "CY=0&FX=43"
},
"0xFFC23D": {
"label": "Smooth",
"pos": "2x3",
"cmnt": "Aurora",
"cmd": "CY=0&FX=38"
},
"0xFFE01F": {
"label": "Bright +",
"pos": "3x1",
"cmd": "A=~16"
},
"0xFFA857": {
"label": "Bright -",
"pos": "3x2",
"cmd": "A=~-16"
},
"0xFF906F": {
"label": "White",
"pos": "3x3",
"cmd": "FP=5&CL=hFFFFFF&C2=hFFFFFF&C3=hA8A8A8"
},
"0xFF6897": {
"label": "Red",
"pos": "4x1",
"cmnt": "Lava",
"cmd": "FP=8"
},
"0xFF9867": {
"label": "Green",
"pos": "4x2",
"cmnt": "Forest",
"cmd": "FP=10"
},
"0xFFB04F": {
"label": "Blue",
"pos": "4x3",
"cmnt": "Breeze",
"cmd": "FP=15"
},
"0xFF30CF": {
"label": "Tomato",
"pos": "5x1",
"cmd": "FP=5&CL=hFF6347&C2=hFFBF47&C3=hA85859"
},
"0xFF18E7": {
"label": "LightGreen",
"pos": "5x2",
"cmnt": "Rivendale",
"cmd": "FP=14"
},
"0xFF7A85": {
"label": "SkyBlue",
"pos": "5x3",
"cmnt": "Ocean",
"cmd": "FP=9"
},
"0xFF10EF": {
"label": "Orange",
"pos": "6x1",
"cmnt": "Orangery",
"cmd": "FP=47"
},
"0xFF38C7": {
"label": "Aqua",
"pos": "6x2",
"cmd": "FP=5&CL=hFFFF&C2=h7FFF&C3=h39A895"
},
"0xFF5AA5": {
"label": "Purple",
"pos": "6x3",
"cmd": "FP=5&CL=h663399&C2=h993399&C3=h473864"
},
"0xFF42BD": {
"label": "Yellow",
"pos": "7x1",
"cmd": "FP=5&CL=hFFFF00&C2=hFFC800&C3=hFDFFDE"
},
"0xFF4AB5": {
"label": "Cyan",
"pos": "7x2",
"cmnt": "Beech",
"cmd": "FP=22"
},
"0xFF52AD": {
"label": "Pink",
"pos": "7x3",
"cmd": "FP=5&CL=hFFC0CB&C2=hFFD4C0&C3=hA88C96"
}
}

View File

@ -0,0 +1,147 @@
{
"desc": "24-key",
"0xF700FF": {
"label": "+",
"pos": "1x1",
"cmnt": "Speed +",
"cmd": "SX=~16"
},
"0xF7807F": {
"label": "-",
"pos": "1x2",
"cmnt": "Speed -",
"cmd": "SX=~-16"
},
"0xF740BF": {
"label": "On/Off",
"pos": "1x3",
"cmnt": "Toggle On/Off",
"cmd": "T=2"
},
"0xF7C03F": {
"label": "W",
"pos": "1x4",
"cmnt": "Cycle color palette",
"cmd": "FP=~"
},
"0xF720DF": {
"label": "R",
"pos": "2x1",
"cmnt": "Lava",
"cmd": "FP=8"
},
"0xF7A05F": {
"label": "G",
"pos": "2x2",
"cmnt": "Forest",
"cmd": "FP=10"
},
"0xF7609F": {
"label": "B",
"pos": "2x3",
"cmnt": "Breeze",
"cmd": "FP=15"
},
"0xF7E01F": {
"label": "Bright -",
"pos": "2x4",
"cmnt": "Bright -",
"cmd": "A=~-16"
},
"0xF710EF": {
"label": "Timer1H",
"pos": "3x1",
"cmnt": "Timer 60 min",
"cmd": "NL=60&NT=0"
},
"0xF7906F": {
"label": "Timer4H",
"pos": "3x2",
"cmnt": "Timer 30 min",
"cmd": "NL=30&NT=0"
},
"0xF750AF": {
"label": "Timer8H",
"pos": "3x3",
"cmnt": "Timer 15 min",
"cmd": "NL=15&NT=0"
},
"0xF7D02F": {
"label": "Bright128",
"pos": "3x4",
"cmnt": "Bright 128",
"cmd": "A=128"
},
"0xF730CF": {
"label": "Music1",
"pos": "4x1",
"cmnt": "Cycle FX +",
"cmd": "FX=~"
},
"0xF7B04F": {
"label": "Music2",
"pos": "4x2",
"cmnt": "Cycle FX -",
"cmd": "FX=~-1"
},
"0xF7708F": {
"label": "Music3",
"pos": "4x3",
"cmnt": "Reset FX and FP",
"cmd": "FX=1&PF=6"
},
"0xF7F00F": {
"label": "Bright +",
"pos": "4x4",
"cmnt": "Bright +",
"cmd": "A=~16"
},
"0xF708F7": {
"label": "Mode1",
"pos": "5x1",
"cmnt": "Preset 1",
"cmd": "PL=1"
},
"0xF78877": {
"label": "Mode2",
"pos": "5x2",
"cmnt": "Preset 2",
"cmd": "PL=2"
},
"0xF748B7": {
"label": "Mode3",
"pos": "5x3",
"cmnt": "Preset 3",
"cmd": "PL=3"
},
"0xF7C837": {
"label": "Up",
"pos": "5x4",
"cmnt": "Intensity +",
"cmd": "IX=~16"
},
"0xF728D7": {
"label": "Mode4",
"pos": "6x1",
"cmnt": "Preset 4",
"cmd": "PL=4"
},
"0xF7A857": {
"label": "Mode5",
"pos": "6x2",
"cmnt": "Preset 5",
"cmd": "PL=5"
},
"0xF76897": {
"label": "Cycle",
"pos": "6x3",
"cmnt": "Toggle preset cycle",
"cmd": "CY=1&PT=60000"
},
"0xF7E817": {
"label": "Down",
"pos": "6x4",
"cmnt": "Intensity -",
"cmd": "IX=~-16"
}
}

View File

@ -0,0 +1,185 @@
{
"desc": "32-key",
"0xFF08F7": {
"label": "On",
"pos": "1x1",
"cmd": "T=1"
},
"0xFFC03F": {
"label": "Off",
"pos": "1x2",
"cmd": "T=0"
},
"0xFF807F": {
"label": "Auto",
"pos": "1x3",
"cmnt": "Toggle preset cycle",
"cmd": "CY=2"
},
"0xFF609F": {
"label": "Mode",
"pos": "1x4",
"cmnt": "Cycle effects",
"cmd": "FX=~&CY=0"
},
"0xFF906F": {
"label": "4H",
"pos": "2x1",
"cmnt": "Timer 60min",
"cmd": "NL=60&NT=0"
},
"0xFFB847": {
"label": "6H",
"pos": "2x2",
"cmnt": "Timer 90min",
"cmd": "NL=90&NT=0"
},
"0xFFF807": {
"label": "8H",
"pos": "2x3",
"cmnt": "Timer 120min",
"cmd": "NL=120&NT=0"
},
"0xFFB04F": {
"label": "Timer Off",
"pos": "2x4",
"cmd": "NL=0"
},
"0xFF9867": {
"label": "Red",
"pos": "3x1",
"cmnt": "Lava",
"cmd": "FP=8"
},
"0xFFD827": {
"label": "Green",
"pos": "3x2",
"cmnt": "Forest",
"cmd": "FP=10"
},
"0xFF8877": {
"label": "Blue",
"pos": "3x3",
"cmnt": "Breeze",
"cmd": "FP=15"
},
"0xFFA857": {
"label": "White",
"pos": "3x4",
"cmd": "FP=5&CL=hFFFFFF&C2=hFFE4CD&C3=hE4E4FF"
},
"0xFFE817": {
"label": "OrangeRed",
"pos": "4x1",
"cmnt": "Sakura",
"cmd": "FP=49"
},
"0xFF48B7": {
"label": "SeaGreen",
"pos": "4x2",
"cmnt": "Rivendale",
"cmd": "FP=14"
},
"0xFF6897": {
"label": "RoyalBlue",
"pos": "4x3",
"cmnt": "Ocean",
"cmd": "FP=9"
},
"0xFFB24D": {
"label": "DarkBlue",
"pos": "4x4",
"cmnt": "Breeze",
"cmd": "FP=15"
},
"0xFF02FD": {
"label": "Orange",
"pos": "5x1",
"cmnt": "Orangery",
"cmd": "FP=47"
},
"0xFF32CD": {
"label": "YellowGreen",
"pos": "5x2",
"cmnt": "Aurora",
"cmd": "FP=37"
},
"0xFF20DF": {
"label": "SkyBlue",
"pos": "5x3",
"cmnt": "Beech",
"cmd": "FP=22"
},
"0xFF00FF": {
"label": "Orchid",
"pos": "5x4",
"cmd": "FP=5&CL=hDA70D6&C2=hDA70A0&C3=h89618F"
},
"0xFF50AF": {
"label": "Yellow",
"pos": "6x1",
"cmd": "FP=5&CL=hFFFF00&C2=hFFC800&C3=hFDFFDE"
},
"0xFF7887": {
"label": "DarkGreen",
"pos": "6x2",
"cmnt": "Orange and Teal",
"cmd": "FP=44"
},
"0xFF708F": {
"label": "RebeccaPurple",
"pos": "6x3",
"cmd": "FP=5&CL=h800080&C2=h800040&C3=h4B1C54"
},
"0xFF58A7": {
"label": "Plum",
"pos": "6x4",
"cmd": "FP=5&CL=hDDA0DD&C2=hDDA0BE&C3=h8D7791"
},
"0xFF38C7": {
"label": "Strobe",
"pos": "7x1",
"cmnt": "Dancing Shadows",
"cmd": "FX=112&CY=0"
},
"0xFF28D7": {
"label": "In Waves",
"pos": "7x2",
"cmnt": "Noise 1",
"cmd": "FX=70&CY=0"
},
"0xFFF00F": {
"label": "Speed +",
"pos": "7x3",
"cmd": "SX=~16"
},
"0xFF30CF": {
"label": "Speed -",
"pos": "7x4",
"cmd": "SX=~-16"
},
"0xFF40BF": {
"label": "Jump",
"pos": "8x1",
"cmnt": "Colortwinkles",
"cmd": "FX=74&CY=0"
},
"0xFF12ED": {
"label": "Fade",
"pos": "8x2",
"cmnt": "Sunrise",
"cmd": "FX=104&CY=0"
},
"0xFF2AD5": {
"label": "Flash",
"pos": "8x3",
"cmnt": "Railway",
"cmd": "FX=78&CY=0"
},
"0xFFA05F": {
"label": "Chase Flash",
"pos": "8x4",
"cmnt": "Washing Machine",
"cmd": "FX=113&CY=0"
}
}

View File

@ -0,0 +1,233 @@
{
"desc": "40-key-black",
"0xFF3AC5": {
"label": "Bright +",
"pos": "1x1",
"cmd": "A=~16"
},
"0xFFBA45": {
"label": "Bright -",
"pos": "1x2",
"cmd": "A=~-16"
},
"0xFF827D": {
"label": "Off",
"pos": "1x3",
"cmd": "T=0"
},
"0xFF02FD": {
"label": "On",
"pos": "1x4",
"cmd": "T=1"
},
"0xFF1AE5": {
"label": "Red",
"pos": "2x1",
"cmnt": "Lava",
"cmd": "FP=8"
},
"0xFF9A65": {
"label": "Green",
"pos": "2x2",
"cmnt": "Forest",
"cmd": "FP=10"
},
"0xFFA25D": {
"label": "Blue",
"pos": "2x3",
"cmnt": "Breeze",
"cmd": "FP=15"
},
"0xFF22DD": {
"label": "White",
"pos": "2x4",
"cmd": "FP=5&CL=hFFFFFF&C2=hFFFFFF&C3=hA8A8A8"
},
"0xFF2AD5": {
"label": "Tomato",
"pos": "3x1",
"cmnt": "Yelmag",
"cmd": "FP=5&CL=hFF6347&C2=hFFBF47&C3=hA85859"
},
"0xFFAA55": {
"label": "LightGreen",
"pos": "3x2",
"cmnt": "Rivendale",
"cmd": "FP=14"
},
"0xFF926D": {
"label": "SkyBlue",
"pos": "3x3",
"cmnt": "Ocean",
"cmd": "FP=9"
},
"0xFF12ED": {
"label": "WarmWhite",
"pos": "3x4",
"cmnt": "Warm White",
"cmd": "FP=5&CL=hFFE4CD&C2=hFFFCCD&C3=hA89892"
},
"0xFF0AF5": {
"label": "OrangeRed",
"pos": "4x1",
"cmnt": "Sakura",
"cmd": "FP=49"
},
"0xFF8A75": {
"label": "Cyan",
"pos": "4x2",
"cmnt": "Beech",
"cmd": "FP=22"
},
"0xFFB24D": {
"label": "RebeccaPurple",
"pos": "4x3",
"cmd": "FP=5&CL=h663399&C2=h993399&C3=h473864"
},
"0xFF32CD": {
"label": "CoolWhite",
"pos": "4x4",
"cmnt": "Cool White",
"cmd": "FP=5&CL=hE4E4FF&C2=hF1E4FF&C3=h9C9EA8"
},
"0xFF38C7": {
"label": "Orange",
"pos": "5x1",
"cmnt": "Orangery",
"cmd": "FP=47"
},
"0xFFB847": {
"label": "Turquoise",
"pos": "5x2",
"cmd": "FP=5&CL=h40E0D0&C2=h40A0E0&C3=h4E9381"
},
"0xFF7887": {
"label": "Purple",
"pos": "5x3",
"cmd": "FP=5&CL=h800080&C2=h800040&C3=h4B1C54"
},
"0xFFF807": {
"label": "MedGray",
"pos": "5x4",
"cmnt": "Cycle palette +",
"cmd": "FP=~"
},
"0xFF18E7": {
"label": "Yellow",
"pos": "6x1",
"cmd": "FP=5&CL=hFFFF00&C2=h7FFF00&C3=hA89539"
},
"0xFF9867": {
"label": "DarkCyan",
"pos": "6x2",
"cmd": "FP=5&CL=h8B8B&C2=h458B&C3=h1F5B51"
},
"0xFF58A7": {
"label": "Plum",
"pos": "6x3",
"cmnt": "Magenta",
"cmd": "FP=40"
},
"0xFFD827": {
"label": "DarkGray",
"pos": "6x4",
"cmnt": "Cycle palette -",
"cmd": "FP=~-"
},
"0xFF28D7": {
"label": "Jump3",
"pos": "7x1",
"cmnt": "Colortwinkles",
"cmd": "CY=0&FX=74"
},
"0xFFA857": {
"label": "Fade3",
"pos": "7x2",
"cmnt": "Rain",
"cmd": "CY=0&FX=43"
},
"0xFF6897": {
"label": "Flash",
"pos": "7x3",
"cmnt": "Cycle Effects",
"cmd": "CY=0&FX=~"
},
"0xFFE817": {
"label": "Quick",
"pos": "7x4",
"cmnt": "Fx speed +16",
"cmd": "SX=~16"
},
"0xFF08F7": {
"label": "Jump7",
"pos": "8x1",
"cmnt": "Sinelon Dual",
"cmd": "CY=0&FX=93"
},
"0xFF8877": {
"label": "Fade7",
"pos": "8x2",
"cmnt": "Lighthouse",
"cmd": "CY=0&FX=41"
},
"0xFF48B7": {
"label": "Auto",
"pos": "8x3",
"cmnt": "Toggle preset cycle",
"cmd": "CY=2"
},
"0xFFC837": {
"label": "Slow",
"pos": "8x4",
"cmnt": "FX speed -16",
"cmd": "SX=~-16"
},
"0xFF30CF": {
"label": "Custom1",
"pos": "9x1",
"cmnt": "Noise 1",
"cmd": "CY=0&FX=70"
},
"0xFFB04F": {
"label": "Custom2",
"pos": "9x2",
"cmnt": "Dancing Shadows",
"cmd": "CY=0&FX=112"
},
"0xFF708F": {
"label": "Music +",
"pos": "9x3",
"cmnt": "FX Intensity +16",
"cmd": "IX=~16"
},
"0xFFF00F": {
"label": "Timer60",
"pos": "9x4",
"cmnt": "Timer 60 min",
"cmd": "NL=60&NT=0"
},
"0xFF10EF": {
"label": "Custom3",
"pos": "10x1",
"cmnt": "Twinklefox",
"cmd": "CY=0&FX=80"
},
"0xFF906F": {
"label": "Custom4",
"pos": "10x2",
"cmnt": "Twinklecat",
"cmd": "CY=0&FX=81"
},
"0xFF50AF": {
"label": "Music -",
"pos": "10x3",
"cmnt": "FX Intesity -16",
"cmd": "IX=~-16"
},
"0xFFD02F": {
"label": "Timer120",
"pos": "10x4",
"cmnt": "Timer 120 min",
"cmd": "NL=120&NT=0"
}
}

View File

@ -0,0 +1,217 @@
{
"desc": "40-key-blue",
"0xFF3AC5": {
"label": "Bright +",
"pos": "1x1",
"cmd": "A=~16"
},
"0xFFBA45": {
"label": "Bright -",
"pos": "1x2",
"cmd": "A=~-16"
},
"0xFF827D": {
"label": "Off",
"pos": "1x3",
"cmd": "T=0"
},
"0xFF02FD": {
"label": "On",
"pos": "1x4",
"cmd": "T=1"
},
"0xFF1AE5": {
"label": "Red",
"pos": "2x1",
"cmnt": "Lava",
"cmd": "FP=8"
},
"0xFF9A65": {
"label": "Green",
"pos": "2x2",
"cmnt": "Forest",
"cmd": "FP=10"
},
"0xFFA25D": {
"label": "Blue",
"pos": "2x3",
"cmnt": "Breeze",
"cmd": "FP=15"
},
"0xFF22DD": {
"label": "White",
"pos": "2x4",
"cmd": "FP=5&CL=hFFFFFF&C2=hFFFFFF&C3=hA8A8A8"
},
"0xFF2AD5": {
"label": "Tomato",
"pos": "3x1",
"cmnt": "Yelmag",
"cmd": "FP=5&CL=hFF6347&C2=hFFBF47&C3=hA85859"
},
"0xFFAA55": {
"label": "LightGreen",
"pos": "3x2",
"cmnt": "Rivendale",
"cmd": "FP=14"
},
"0xFF926D": {
"label": "SkyBlue",
"pos": "3x3",
"cmnt": "Ocean",
"cmd": "FP=9"
},
"0xFF12ED": {
"label": "WarmWhite",
"pos": "3x4",
"cmnt": "Warm White",
"cmd": "FP=5&CL=hFFE4CD&C2=hFFFCCD&C3=hA89892"
},
"0xFF0AF5": {
"label": "OrangeRed",
"pos": "4x1",
"cmnt": "Sakura",
"cmd": "FP=49"
},
"0xFF8A75": {
"label": "Cyan",
"pos": "4x2",
"cmnt": "Beech",
"cmd": "FP=22"
},
"0xFFB24D": {
"label": "RebeccaPurple",
"pos": "4x3",
"cmd": "FP=5&CL=h663399&C2=h993399&C3=h473864"
},
"0xFF32CD": {
"label": "CoolWhite",
"pos": "4x4",
"cmnt": "Cool White",
"cmd": "FP=5&CL=hE4E4FF&C2=hF1E4FF&C3=h9C9EA8"
},
"0xFF38C7": {
"label": "Orange",
"pos": "5x1",
"cmnt": "Orangery",
"cmd": "FP=47"
},
"0xFFB847": {
"label": "Turquoise",
"pos": "5x2",
"cmd": "FP=5&CL=h40E0D0&C2=h40A0E0&C3=h4E9381"
},
"0xFF7887": {
"label": "Purple",
"pos": "5x3",
"cmd": "FP=5&CL=h800080&C2=h800040&C3=h4B1C54"
},
"0xFFF807": {
"label": "MedGray",
"pos": "5x4",
"cmnt": "Cycle palette +",
"cmd": "FP=~"
},
"0xFF18E7": {
"label": "Yellow",
"pos": "6x1",
"cmd": "FP=5&CL=hFFFF00&C2=h7FFF00&C3=hA89539"
},
"0xFF9867": {
"label": "DarkCyan",
"pos": "6x2",
"cmd": "FP=5&CL=h8B8B&C2=h458B&C3=h1F5B51"
},
"0xFF58A7": {
"label": "Plum",
"pos": "6x3",
"cmnt": "Magenta",
"cmd": "FP=40"
},
"0xFFD827": {
"label": "DarkGray",
"pos": "6x4",
"cmnt": "Cycle palette -",
"cmd": "FP=~-"
},
"0xFF28D7": {
"label": "W +",
"pos": "7x1"
},
"0xFFA857": {
"label": "W -",
"pos": "7x2"
},
"0xFF6897": {
"label": "W On",
"pos": "7x3"
},
"0xFFE817": {
"label": "W Off",
"pos": "7x4"
},
"0xFF08F7": {
"label": "W25",
"pos": "8x1"
},
"0xFF8877": {
"label": "W50",
"pos": "8x2"
},
"0xFF48B7": {
"label": "W75",
"pos": "8x3"
},
"0xFFC837": {
"label": "W100",
"pos": "8x4"
},
"0xFF30CF": {
"label": "Jump3",
"pos": "9x1",
"cmnt": "Colortwinkles",
"cmd": "CY=0&FX=74"
},
"0xFFB04F": {
"label": "Fade3",
"pos": "9x2",
"cmnt": "Rain",
"cmd": "CY=0&FX=43"
},
"0xFF708F": {
"label": "Jump7",
"pos": "9x3",
"cmnt": "Sinelon Dual",
"cmd": "CY=0&FX=93"
},
"0xFFF00F": {
"label": "Quick",
"pos": "9x4",
"cmnt": "Fx speed +16",
"cmd": "SX=~16"
},
"0xFF10EF": {
"label": "Fade",
"pos": "10x1",
"cmnt": "Lighthouse",
"cmd": "CY=0&FX=41"
},
"0xFF906F": {
"label": "Flash",
"pos": "10x2",
"cmnt": "Cycle Effects",
"cmd": "CY=0&FX=~"
},
"0xFF50AF": {
"label": "Auto",
"pos": "10x3",
"cmnt": "Toggle preset cycle",
"cmd": "CY=2"
},
"0xFFD02F": {
"label": "Slow",
"pos": "10x4",
"cmnt": "Sinelon Dual",
"cmd": "CY=0&FX=93"
}
}

View File

@ -0,0 +1,241 @@
{
"desc": "44-key",
"0xFF3AC5": {
"label": "Bright +",
"pos": "1x1",
"cmd": "A=~16"
},
"0xFFBA45": {
"label": "Bright -",
"pos": "1x2",
"cmd": "A=~-16"
},
"0xFF827D": {
"label": "Off",
"pos": "1x3",
"cmd": "T=0"
},
"0xFF02FD": {
"label": "On",
"pos": "1x4",
"cmd": "T=1"
},
"0xFF1AE5": {
"label": "Red",
"pos": "2x1",
"cmnt": "Lava",
"cmd": "FP=8"
},
"0xFF9A65": {
"label": "Green",
"pos": "2x2",
"cmnt": "Forest",
"cmd": "FP=10"
},
"0xFFA25D": {
"label": "Blue",
"pos": "2x3",
"cmnt": "Breeze",
"cmd": "FP=15"
},
"0xFF22DD": {
"label": "White",
"pos": "2x4",
"cmd": "FP=5&CL=hFFFFFF&C2=hFFFFFF&C3=hA8A8A8"
},
"0xFF2AD5": {
"label": "Tomato",
"pos": "3x1",
"cmd": "FP=5&CL=hFF6347&C2=hFFBF47&C3=hA85859"
},
"0xFFAA55": {
"label": "LightGreen",
"pos": "3x2",
"cmnt": "Rivendale",
"cmd": "FP=14"
},
"0xFF926D": {
"label": "DeepBlue",
"pos": "3x3",
"cmnt": "Ocean",
"cmd": "FP=9"
},
"0xFF12ED": {
"label": "Warmwhite2",
"pos": "3x4",
"cmnt": "Warm White",
"cmd": "FP=5&CL=hFFE4CD&C2=hFFFCCD&C3=hA89892"
},
"0xFF0AF5": {
"label": "Orange",
"pos": "4x1",
"cmnt": "Sakura",
"cmd": "FP=49"
},
"0xFF8A75": {
"label": "Turquoise",
"pos": "4x2",
"cmnt": "Beech",
"cmd": "FP=22"
},
"0xFFB24D": {
"label": "Purple",
"pos": "4x3",
"cmd": "FP=5&CL=h663399&C2=h993399&C3=h473864"
},
"0xFF32CD": {
"label": "WarmWhite",
"pos": "4x4",
"cmd": "FP=5&CL=hE4E4FF&C2=hF1E4FF&C3=h9C9EA8"
},
"0xFF38C7": {
"label": "Yellowish",
"pos": "5x1",
"cmnt": "Orangery",
"cmd": "FP=47"
},
"0xFFB847": {
"label": "Cyan",
"pos": "5x2",
"cmnt": "Beech",
"cmd": "FP=22"
},
"0xFF7887": {
"label": "Magenta",
"pos": "5x3",
"cmd": "FP=5&CL=hFF00FF&C2=hFF007F&C3=h9539A8"
},
"0xFFF807": {
"label": "ColdWhite",
"pos": "5x4",
"cmd": "FP=5&CL=hE4E4FF&C2=hF1E4FF&C3=h9C9EA8"
},
"0xFF18E7": {
"label": "Yellow",
"pos": "6x1",
"cmd": "FP=5&CL=hFFFF00&C2=hFFC800&C3=hFDFFDE"
},
"0xFF9867": {
"label": "Aqua",
"pos": "6x2",
"cmd": "FP=5&CL=hFFFF&C2=h7FFF&C3=h39A895"
},
"0xFF58A7": {
"label": "Pink",
"pos": "6x3",
"cmd": "FP=5&CL=hFFC0CB&C2=hFFD4C0&C3=hA88C96"
},
"0xFFD827": {
"label": "ColdWhite2",
"pos": "6x4",
"cmd": "FP=5&CL=hE4E4FF&C2=hF1E4FF&C3=h9C9EA8"
},
"0xFF28D7": {
"label": "Red +",
"pos": "7x1",
"cmd": "FP=5&R=~16"
},
"0xFFA857": {
"label": "Green +",
"pos": "7x2",
"cmd": "FP=5&G=~16"
},
"0xFF6897": {
"label": "Blue +",
"pos": "7x3",
"cmd": "FP=5&B=~16"
},
"0xFFE817": {
"label": "Quick",
"pos": "7x4",
"cmnt": "Fx speed +16",
"cmd": "SX=~16"
},
"0xFF08F7": {
"label": "Red -",
"pos": "8x1",
"cmd": "FP=5&R=~-16"
},
"0xFF8877": {
"label": "Green -",
"pos": "8x2",
"cmd": "FP=5&G=~-16"
},
"0xFF48B7": {
"label": "Blue -",
"pos": "8x3",
"cmd": "FP=5&B=~-16"
},
"0xFFC837": {
"label": "Slow",
"pos": "8x4",
"cmnt": "FX speed -16",
"cmd": "SX=~-16"
},
"0xFF30CF": {
"label": "Diy1",
"pos": "9x1",
"cmd": "CY=0&PL=1"
},
"0xFFB04F": {
"label": "Diy2",
"pos": "9x2",
"cmd": "CY=0&PL=2"
},
"0xFF708F": {
"label": "Diy3",
"pos": "9x3",
"cmd": "CY=0&PL=3"
},
"0xFFF00F": {
"label": "Auto",
"pos": "9x4",
"cmnt": "Toggle preset cycle",
"cmd": "CY=2"
},
"0xFF10EF": {
"label": "Diy4",
"pos": "10x1",
"cmd": "CY=0&PL=4"
},
"0xFF906F": {
"label": "Diy5",
"pos": "10x2",
"cmd": "CY=0&PL=5"
},
"0xFF50AF": {
"label": "Diy6",
"pos": "10x3",
"cmd": "CY=0&PL=6"
},
"0xFFD02F": {
"label": "Flash",
"pos": "10x4",
"cmnt": "Cycle Effects",
"cmd": "CY=0&FX=~"
},
"0xFF20DF": {
"label": "Jump3",
"pos": "11x1",
"cmnt": "Colortwinkles",
"cmd": "CY=0&FX=74"
},
"0xFFA05F": {
"label": "Jump7",
"pos": "11x2",
"cmnt": "Sinelon Dual",
"cmd": "CY=0&FX=93"
},
"0xFF609F": {
"label": "Fade3",
"pos": "11x3",
"cmnt": "Rain",
"cmd": "CY=0&FX=43"
},
"0xFFE01F": {
"label": "Fade7",
"pos": "11x4",
"cmnt": "Lighthouse",
"cmd": "CY=0&FX=41"
}
}

View File

@ -0,0 +1,38 @@
{
"desc": "6-key",
"0xFF0FF0": {
"label": "Power",
"pos": "1x1",
"cmd": "T=2"
},
"0xFF8F70": {
"label": "Channel +",
"pos": "2x1",
"cmnt": "Cycle palette up",
"cmd": "FP=~"
},
"0xFF4FB0": {
"label": "Channel -",
"pos": "3x1",
"cmnt": "Cycle palette down",
"cmd": "FP=~-"
},
"0xFFCF30": {
"label": "Volume +",
"pos": "4x1",
"cmnt": "Brighten",
"cmd": "A=~16"
},
"0xFF2FD0": {
"label": "Volume -",
"pos": "5x1",
"cmnt": "Dim",
"cmd": "A=~-16"
},
"0xFFAF50": {
"label": "Mute",
"pos": "6x1",
"cmnt": "Cycle effects",
"cmd": "CY=0&FX=~"
}
}

View File

@ -0,0 +1,47 @@
{
"desc": "9-key",
"0xFF629D": {
"label": "Power",
"cmd": "T=2"
},
"0xFF22DD": {
"label": "A",
"cmnt": "Preset 1",
"cmd": "PL=1"
},
"0xFF02FD": {
"label": "B",
"cmnt": "Preset 2",
"cmd": "PL=2"
},
"0xFFC23D": {
"label": "C",
"cmnt": "Preset 3",
"cmd": "PL=3"
},
"0xFF30CF": {
"label": "Left",
"cmnt": "Speed -",
"cmd": "SI=~-16"
},
"0xFF7A85": {
"label": "Right",
"cmnt": "Speed +",
"cmd": "SI=~16"
},
"0xFF9867": {
"label": "Up",
"cmnt": "Bright +",
"cmd": "A=~16"
},
"0xFF38C7": {
"label": "Down",
"cmnt": "Bright -",
"cmd": "A=~-16"
},
"0xFF18E7": {
"label": "Select",
"cmnt": "Cycle effects",
"cmd": "CY=0&FX=~"
}
}

Binary file not shown.

View File

@ -0,0 +1,108 @@
import colorsys
import json
import openpyxl
named_colors = {'AliceBlue': '0xF0F8FF', 'AntiqueWhite': '0xFAEBD7', 'Aqua': '0x00FFFF',
'Aquamarine': '0x7FFFD4', 'Azure': '0xF0FFFF', 'Beige': '0xF5F5DC', 'Bisque': '0xFFE4C4',
'Black': '0x000000', 'BlanchedAlmond': '0xFFEBCD', 'Blue': '0x0000FF',
'BlueViolet': '0x8A2BE2', 'Brown': '0xA52A2A', 'BurlyWood': '0xDEB887',
'CadetBlue': '0x5F9EA0', 'Chartreuse': '0x7FFF00', 'Chocolate': '0xD2691E',
'Coral': '0xFF7F50', 'CornflowerBlue': '0x6495ED', 'Cornsilk': '0xFFF8DC',
'Crimson': '0xDC143C', 'Cyan': '0x00FFFF', 'DarkBlue': '0x00008B', 'DarkCyan': '0x008B8B',
'DarkGoldenRod': '0xB8860B', 'DarkGray': '0xA9A9A9', 'DarkGrey': '0xA9A9A9',
'DarkGreen': '0x006400', 'DarkKhaki': '0xBDB76B', 'DarkMagenta': '0x8B008B',
'DarkOliveGreen': '0x556B2F', 'DarkOrange': '0xFF8C00', 'DarkOrchid': '0x9932CC',
'DarkRed': '0x8B0000', 'DarkSalmon': '0xE9967A', 'DarkSeaGreen': '0x8FBC8F',
'DarkSlateBlue': '0x483D8B', 'DarkSlateGray': '0x2F4F4F', 'DarkSlateGrey': '0x2F4F4F',
'DarkTurquoise': '0x00CED1', 'DarkViolet': '0x9400D3', 'DeepPink': '0xFF1493',
'DeepSkyBlue': '0x00BFFF', 'DimGray': '0x696969', 'DimGrey': '0x696969',
'DodgerBlue': '0x1E90FF', 'FireBrick': '0xB22222', 'FloralWhite': '0xFFFAF0',
'ForestGreen': '0x228B22', 'Fuchsia': '0xFF00FF', 'Gainsboro': '0xDCDCDC',
'GhostWhite': '0xF8F8FF', 'Gold': '0xFFD700', 'GoldenRod': '0xDAA520', 'Gray': '0x808080',
'Grey': '0x808080', 'Green': '0x008000', 'GreenYellow': '0xADFF2F', 'HoneyDew': '0xF0FFF0',
'HotPink': '0xFF69B4', 'IndianRed': '0xCD5C5C', 'Indigo': '0x4B0082', 'Ivory': '0xFFFFF0',
'Khaki': '0xF0E68C', 'Lavender': '0xE6E6FA', 'LavenderBlush': '0xFFF0F5',
'LawnGreen': '0x7CFC00', 'LemonChiffon': '0xFFFACD', 'LightBlue': '0xADD8E6',
'LightCoral': '0xF08080', 'LightCyan': '0xE0FFFF', 'LightGoldenRodYellow': '0xFAFAD2',
'LightGray': '0xD3D3D3', 'LightGrey': '0xD3D3D3', 'LightGreen': '0x90EE90',
'LightPink': '0xFFB6C1', 'LightSalmon': '0xFFA07A', 'LightSeaGreen': '0x20B2AA',
'LightSkyBlue': '0x87CEFA', 'LightSlateGray': '0x778899', 'LightSlateGrey': '0x778899',
'LightSteelBlue': '0xB0C4DE', 'LightYellow': '0xFFFFE0', 'Lime': '0x00FF00',
'LimeGreen': '0x32CD32', 'Linen': '0xFAF0E6', 'Magenta': '0xFF00FF', 'Maroon': '0x800000',
'MediumAquaMarine': '0x66CDAA', 'MediumBlue': '0x0000CD', 'MediumOrchid': '0xBA55D3',
'MediumPurple': '0x9370DB', 'MediumSeaGreen': '0x3CB371', 'MediumSlateBlue': '0x7B68EE',
'MediumSpringGreen': '0x00FA9A', 'MediumTurquoise': '0x48D1CC', 'MediumVioletRed': '0xC71585',
'MidnightBlue': '0x191970', 'MintCream': '0xF5FFFA', 'MistyRose': '0xFFE4E1',
'Moccasin': '0xFFE4B5', 'NavajoWhite': '0xFFDEAD', 'Navy': '0x000080', 'OldLace': '0xFDF5E6',
'Olive': '0x808000', 'OliveDrab': '0x6B8E23', 'Orange': '0xFFA500', 'OrangeRed': '0xFF4500',
'Orchid': '0xDA70D6', 'PaleGoldenRod': '0xEEE8AA', 'PaleGreen': '0x98FB98',
'PaleTurquoise': '0xAFEEEE', 'PaleVioletRed': '0xDB7093', 'PapayaWhip': '0xFFEFD5',
'PeachPuff': '0xFFDAB9', 'Peru': '0xCD853F', 'Pink': '0xFFC0CB', 'Plum': '0xDDA0DD',
'PowderBlue': '0xB0E0E6', 'Purple': '0x800080', 'RebeccaPurple': '0x663399', 'Red': '0xFF0000',
'RosyBrown': '0xBC8F8F', 'RoyalBlue': '0x4169E1', 'SaddleBrown': '0x8B4513', 'Salmon': '0xFA8072',
'SandyBrown': '0xF4A460', 'SeaGreen': '0x2E8B57', 'SeaShell': '0xFFF5EE', 'Sienna': '0xA0522D',
'Silver': '0xC0C0C0', 'SkyBlue': '0x87CEEB', 'SlateBlue': '0x6A5ACD', 'SlateGray': '0x708090',
'SlateGrey': '0x708090', 'Snow': '0xFFFAFA', 'SpringGreen': '0x00FF7F', 'SteelBlue': '0x4682B4',
'Tan': '0xD2B48C', 'Teal': '0x008080', 'Thistle': '0xD8BFD8', 'Tomato': '0xFF6347',
'Turquoise': '0x40E0D0', 'Violet': '0xEE82EE', 'Wheat': '0xF5DEB3', 'White': '0xFFFFFF',
'WhiteSmoke': '0xF5F5F5', 'Yellow': '0xFFFF00', 'YellowGreen': '0x9ACD32'}
def shift_color(col, shift=30, sat=1.0, val=1.0):
r = (col & (255 << 16)) >> 16
g = (col & (255 << 8)) >> 8
b = col & 255
hsv = colorsys.rgb_to_hsv(r, g, b)
h = (((hsv[0] * 360) + shift) % 360) / 360
rgb = colorsys.hsv_to_rgb(h, hsv[1] * sat, hsv[2] * val)
return (int(rgb[0]) << 16) + (int(rgb[1]) << 8) + int(rgb[2])
def parse_sheet(ws):
print(f'Parsing worksheet {ws.title}')
ir = {"desc": ws.title}
rows = ws.rows
keys = [col.value.lower() for col in next(rows)]
for row in rows:
rec = dict(zip(keys, [col.value for col in row]))
if rec.get('code') is None:
continue
cd = {"label": rec.get('label')}
if rec.get('row'):
cd['pos'] = f'{rec["row"]}x{rec["col"]}'
if rec.get('comment'):
cd['cmnt'] = rec.get('comment')
if rec.get('rpt'):
cd['rpt'] = bool(rec['rpt'])
if rec.get('cmd'):
cd['cmd'] = rec['cmd']
elif all((rec.get('primary'), rec.get('secondary'), rec.get('tertiary'))):
c1 = int(rec.get('primary'), 16)
c2 = int(rec.get('secondary'), 16)
c3 = int(rec.get('tertiary'), 16)
cd['cmd'] = f'FP=5&CL=h{c1:X}&C2=h{c2:X}&C3=h{c3:X}'
elif all((rec.get('primary'), rec.get('secondary'))):
c1 = int(rec.get('primary'), 16)
c2 = int(rec.get('secondary'), 16)
c3 = shift_color(c1, -1, sat=0.66, val=0.66)
cd['cmd'] = f'FP=5&CL=h{c1:X}&C2=h{c2:X}&C3=h{c3:X}'
elif rec.get('primary'):
c1 = int(rec.get('primary'), 16)
c2 = shift_color(c1, 30)
c3 = shift_color(c1, -10, sat=0.66, val=0.66)
cd['cmd'] = f'FP=5&CL=h{c1:X}&C2=h{c2:X}&C3=h{c3:X}'
elif rec.get('label') in named_colors:
c1 = int(named_colors[rec.get('label')], 16)
c2 = shift_color(c1, 30)
c3 = shift_color(c1, -10, sat=0.66, val=0.66)
cd['cmd'] = f'FP=5&CL=h{c1:X}&C2=h{c2:X}&C3=h{c3:X}'
else:
print(f'Did not find a command or color for {rec["label"]}. Hint use named CSS colors as labels')
ir[rec['code']] = cd
with open(f'{ws.title}_ir.json', 'w') as fp:
json.dump(ir, fp, indent=2)
if __name__ == '__main__':
wb = openpyxl.load_workbook('IR_Remote_Codes.xlsx')
for ws in wb.worksheets:
parse_sheet(ws)

View File

@ -0,0 +1,33 @@
# JSON IR remote
## Purpose
The JSON IR remote enables users to customize IR remote behavior without writing custom code and compiling.
It also allows using any remote compatible with your IR receiver. Using the JSON IR remote, you can
map buttons from any remote to any HTTP request API or JSON API command.
## Usage
* Upload the IR config file, named _ir.json_ to your board using the [ip address]/edit url. Pick from one of the included files or create your own.
* On the config > LED settings page, set the correct IR pin.
* On the config > Sync Interfaces page, select "JSON Remote" as the Infrared remote.
## Modification
* See if there is a json file with the same number of buttons as your remote. Many remotes will have the same internals and emit the same codes but have different labels.
* In the ir.json file, each key will be the hex encoded IR code.
* The "cmd" property will be the HTTP Request API or JSON API to execute when that button is pressed.
* A limited number of c functions are supported (!incBrightness, !decBrightness, !presetFallback)
* When using !presetFallback, include properties PL (preset to load), FX (effect to fall back to) and FP (palette to fall back to)
* If the command is _repeatable_ and does not contain the "~" character, add a "rpt": true property.
* Other properties are ignored, but having a label property may help when editing.
Sample:
{
"0xFF629D": {"cmd": "T=2", "rpt": true, "label": "Toggle on/off"}, // HTTP command
"0xFF9867": {"cmd": "A=~16", "label": "Inc brightness"}, // HTTP command with incrementing
"0xFF38C7": {"cmd": {"bri": 10}, "label": "Dim to 10"}, // JSON command
"0xFF22DD": {"cmd": "!presetFallback", "PL": 1, "FX": 16, "FP": 6,
"label": "Preset 1 or fallback to Saw - Party"}, // c function
}

321
usermods/MY9291/MY92xx.h Normal file
View File

@ -0,0 +1,321 @@
/*
MY92XX LED Driver for Arduino
Based on the C driver by MaiKe Labs
Copyright (c) 2016 - 2026 MaiKe Labs
Copyright (C) 2017 - 2018 Xose Pérez for the Arduino compatible library
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _my92xx_h
#define _my92xx_h
#include <Arduino.h>
#ifdef DEBUG_MY92XX
#if ARDUINO_ARCH_ESP8266
#define DEBUG_MSG_MY92XX(...) DEBUG_MY92XX.printf( __VA_ARGS__ )
#elif ARDUINO_ARCH_AVR
#define DEBUG_MSG_MY92XX(...) { char buffer[80]; snprintf(buffer, sizeof(buffer), __VA_ARGS__ ); DEBUG_MY92XX.print(buffer); }
#endif
#else
#define DEBUG_MSG_MY92XX(...)
#endif
typedef enum my92xx_model_t {
MY92XX_MODEL_MY9291 = 0X00,
MY92XX_MODEL_MY9231 = 0X01,
} my92xx_model_t;
typedef enum my92xx_cmd_one_shot_t {
MY92XX_CMD_ONE_SHOT_DISABLE = 0X00,
MY92XX_CMD_ONE_SHOT_ENFORCE = 0X01,
} my92xx_cmd_one_shot_t;
typedef enum my92xx_cmd_reaction_t {
MY92XX_CMD_REACTION_FAST = 0X00,
MY92XX_CMD_REACTION_SLOW = 0X01,
} my92xx_cmd_reaction_t;
typedef enum my92xx_cmd_bit_width_t {
MY92XX_CMD_BIT_WIDTH_16 = 0X00,
MY92XX_CMD_BIT_WIDTH_14 = 0X01,
MY92XX_CMD_BIT_WIDTH_12 = 0X02,
MY92XX_CMD_BIT_WIDTH_8 = 0X03,
} my92xx_cmd_bit_width_t;
typedef enum my92xx_cmd_frequency_t {
MY92XX_CMD_FREQUENCY_DIVIDE_1 = 0X00,
MY92XX_CMD_FREQUENCY_DIVIDE_4 = 0X01,
MY92XX_CMD_FREQUENCY_DIVIDE_16 = 0X02,
MY92XX_CMD_FREQUENCY_DIVIDE_64 = 0X03,
} my92xx_cmd_frequency_t;
typedef enum my92xx_cmd_scatter_t {
MY92XX_CMD_SCATTER_APDM = 0X00,
MY92XX_CMD_SCATTER_PWM = 0X01,
} my92xx_cmd_scatter_t;
typedef struct {
my92xx_cmd_scatter_t scatter : 1;
my92xx_cmd_frequency_t frequency : 2;
my92xx_cmd_bit_width_t bit_width : 2;
my92xx_cmd_reaction_t reaction : 1;
my92xx_cmd_one_shot_t one_shot : 1;
unsigned char resv : 1;
} __attribute__((aligned(1), packed)) my92xx_cmd_t;
#define MY92XX_COMMAND_DEFAULT { \
.scatter = MY92XX_CMD_SCATTER_APDM, \
.frequency = MY92XX_CMD_FREQUENCY_DIVIDE_1, \
.bit_width = MY92XX_CMD_BIT_WIDTH_8, \
.reaction = MY92XX_CMD_REACTION_FAST, \
.one_shot = MY92XX_CMD_ONE_SHOT_DISABLE, \
.resv = 0 \
}
class my92xx {
public:
my92xx(my92xx_model_t model, unsigned char chips, unsigned char di, unsigned char dcki, my92xx_cmd_t command);
unsigned char getChannels();
void setChannel(unsigned char channel, unsigned int value);
unsigned int getChannel(unsigned char channel);
void setState(bool state);
bool getState();
void update();
private:
void _di_pulse(unsigned int times);
void _dcki_pulse(unsigned int times);
void _set_cmd(my92xx_cmd_t command);
void _send();
void _write(unsigned int data, unsigned char bit_length);
my92xx_cmd_t _command;
my92xx_model_t _model = MY92XX_MODEL_MY9291;
unsigned char _chips = 1;
unsigned char _channels;
uint16_t* _value;
bool _state = false;
unsigned char _pin_di;
unsigned char _pin_dcki;
};
#if ARDUINO_ARCH_ESP8266
extern "C" {
void os_delay_us(unsigned int);
}
#elif ARDUINO_ARCH_AVR
#define os_delay_us delayMicroseconds
#endif
void my92xx::_di_pulse(unsigned int times) {
for (unsigned int i = 0; i < times; i++) {
digitalWrite(_pin_di, HIGH);
digitalWrite(_pin_di, LOW);
}
}
void my92xx::_dcki_pulse(unsigned int times) {
for (unsigned int i = 0; i < times; i++) {
digitalWrite(_pin_dcki, HIGH);
digitalWrite(_pin_dcki, LOW);
}
}
void my92xx::_write(unsigned int data, unsigned char bit_length) {
unsigned int mask = (0x01 << (bit_length - 1));
for (unsigned int i = 0; i < bit_length / 2; i++) {
digitalWrite(_pin_dcki, LOW);
digitalWrite(_pin_di, (data & mask) ? HIGH : LOW);
digitalWrite(_pin_dcki, HIGH);
data = data << 1;
digitalWrite(_pin_di, (data & mask) ? HIGH : LOW);
digitalWrite(_pin_dcki, LOW);
digitalWrite(_pin_di, LOW);
data = data << 1;
}
}
void my92xx::_set_cmd(my92xx_cmd_t command) {
// ets_intr_lock();
// TStop > 12us.
os_delay_us(12);
// Send 12 DI pulse, after 6 pulse's falling edge store duty data, and 12
// pulse's rising edge convert to command mode.
_di_pulse(12);
// Delay >12us, begin send CMD data
os_delay_us(12);
// Send CMD data
unsigned char command_data = *(unsigned char*)(&command);
for (unsigned char i = 0; i < _chips; i++) {
_write(command_data, 8);
}
// TStart > 12us. Delay 12 us.
os_delay_us(12);
// Send 16 DI pulseat 14 pulse's falling edge store CMD data, and
// at 16 pulse's falling edge convert to duty mode.
_di_pulse(16);
// TStop > 12us.
os_delay_us(12);
// ets_intr_unlock();
}
void my92xx::_send() {
#ifdef DEBUG_MY92XX
DEBUG_MSG_MY92XX("[MY92XX] Refresh: %s (", _state ? "ON" : "OFF");
for (unsigned char channel = 0; channel < _channels; channel++) {
DEBUG_MSG_MY92XX(" %d", _value[channel]);
}
DEBUG_MSG_MY92XX(" )\n");
#endif
unsigned char bit_length = 8;
switch (_command.bit_width) {
case MY92XX_CMD_BIT_WIDTH_16:
bit_length = 16;
break;
case MY92XX_CMD_BIT_WIDTH_14:
bit_length = 14;
break;
case MY92XX_CMD_BIT_WIDTH_12:
bit_length = 12;
break;
case MY92XX_CMD_BIT_WIDTH_8:
bit_length = 8;
break;
default:
bit_length = 8;
break;
}
// ets_intr_lock();
// TStop > 12us.
os_delay_us(12);
// Send color data
for (unsigned char channel = 0; channel < _channels; channel++) {
_write(_state ? _value[channel] : 0, bit_length);
}
// TStart > 12us. Ready for send DI pulse.
os_delay_us(12);
// Send 8 DI pulse. After 8 pulse falling edge, store old data.
_di_pulse(8);
// TStop > 12us.
os_delay_us(12);
// ets_intr_unlock();
}
// -----------------------------------------------------------------------------
unsigned char my92xx::getChannels() {
return _channels;
}
void my92xx::setChannel(unsigned char channel, unsigned int value) {
if (channel < _channels) {
_value[channel] = value;
}
}
unsigned int my92xx::getChannel(unsigned char channel) {
if (channel < _channels) {
return _value[channel];
}
return 0;
}
bool my92xx::getState() {
return _state;
}
void my92xx::setState(bool state) {
_state = state;
}
void my92xx::update() {
_send();
}
// -----------------------------------------------------------------------------
my92xx::my92xx(my92xx_model_t model, unsigned char chips, unsigned char di, unsigned char dcki, my92xx_cmd_t command) : _command(command) {
_model = model;
_chips = chips;
_pin_di = di;
_pin_dcki = dcki;
// Init channels
if (_model == MY92XX_MODEL_MY9291) {
_channels = 4 * _chips;
}
else if (_model == MY92XX_MODEL_MY9231) {
_channels = 3 * _chips;
}
_value = new uint16_t[_channels];
for (unsigned char i = 0; i < _channels; i++) {
_value[i] = 0;
}
// Init GPIO
pinMode(_pin_di, OUTPUT);
pinMode(_pin_dcki, OUTPUT);
digitalWrite(_pin_di, LOW);
digitalWrite(_pin_dcki, LOW);
// Clear all duty register
_dcki_pulse(32 * _chips);
// Send init command
_set_cmd(command);
DEBUG_MSG_MY92XX("[MY92XX] Initialized\n");
}
#endif

View File

@ -0,0 +1,45 @@
#pragma once
#include "wled.h"
#include "MY92xx.h"
#define MY92XX_MODEL MY92XX_MODEL_MY9291
#define MY92XX_CHIPS 1
#define MY92XX_DI_PIN 13
#define MY92XX_DCKI_PIN 15
#define MY92XX_RED 0
#define MY92XX_GREEN 1
#define MY92XX_BLUE 2
#define MY92XX_WHITE 3
class MY9291Usermod : public Usermod {
private:
my92xx _my92xx = my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND_DEFAULT);
public:
void setup() {
_my92xx.setState(true);
}
void connected() {
}
void loop() {
uint32_t c = strip.getPixelColor(0);
int w = ((c >> 24) & 0xff) * bri / 255.0;
int r = ((c >> 16) & 0xff) * bri / 255.0;
int g = ((c >> 8) & 0xff) * bri / 255.0;
int b = (c & 0xff) * bri / 255.0;
_my92xx.setChannel(MY92XX_RED, r);
_my92xx.setChannel(MY92XX_GREEN, g);
_my92xx.setChannel(MY92XX_BLUE, b);
_my92xx.setChannel(MY92XX_WHITE, w);
_my92xx.update();
}
uint16_t getId() {
return USERMOD_ID_MY9291;
}
};

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