Compare commits

...

No commits in common. "v9.5.0" and "master" have entirely different histories.

6177 changed files with 361 additions and 2654482 deletions

17
.gitattributes vendored
View File

@ -1,17 +0,0 @@
# Auto detect text files and perform LF normalization
* text=off
# Custom for Visual Studio
*.cs diff=csharp
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

View File

@ -1,81 +0,0 @@
---
name: Problem Report
about: Create a Report to help us improve
---
<!-- Thanks for reporting a problem for this project. READ THIS FIRST:
This issue template is meant to REPORT Tasmota software PROBLEMS ONLY
Please DO NOT OPEN AN ISSUE:
- If your Tasmota version is not the latest from the development branch, please update your device before submitting your issue. Your problem might already be solved. The latest precompiled binaries of Tasmota can be downloaded from http://ota.tasmota.com/tasmota/
- If you have an issue when flashing was done via Tuya Convert, please address it to Tuya Convert Team
- If your issue is a flashing issue, please address it to the [Tasmota Support Chat](https://discord.gg/Ks2Kzd4)
- If your issue is compilation problem, please address it to the [Tasmota Support Chat](https://discord.gg/Ks2Kzd4)
- If your issue has been addressed before (i.e., duplicated issue), please ask in the original issue
- If your issue is a Wi-Fi problem or MQTT problem, please try the steps provided in the [FAQ](https://tasmota.github.io/docs/FAQ) and [Troubleshooting](https://tasmota.github.io/docs/Troubleshooting)
Please take a few minutes to complete the requested information below. Our ability to provide assistance is greatly hampered without it. The details requested potentially affect which options to pursue. The small amount of time you spend completing the template will also help the volunteers providing the assistance to you to reduce the time required to help you.
DO NOT DELETE ANY TEXT from this template! Otherwise the issue will be auto-closed.
-->
### PROBLEM DESCRIPTION
_A clear and concise description of what the problem is._
### REQUESTED INFORMATION
_Make sure your have performed every step and checked the applicable boxes before submitting your issue. Thank you!_
- [ ] Read the [Contributing Guide and Policy](https://github.com/arendst/Tasmota/blob/development/CONTRIBUTING.md) and [the Code of Conduct](https://github.com/arendst/Tasmota/blob/development/CODE_OF_CONDUCT.md)
- [ ] Searched the problem in [issues](https://github.com/arendst/Tasmota/issues)
- [ ] Searched the problem in [discussions](https://github.com/arendst/Tasmota/discussions)
- [ ] Searched the problem in the [docs](https://tasmota.github.io/docs/FAQ)
- [ ] Searched the problem in the [chat](https://discord.gg/Ks2Kzd4)
- [ ] Device used (e.g., Sonoff Basic): _____
- [ ] Tasmota binary firmware version number used: _____
- [ ] Pre-compiled
- [ ] Self-compiled
- [ ] Flashing tools used: _____
- [ ] Provide the output of command: `Backlog Template; Module; GPIO 255`:
```lua
Configuration output here:
```
- [ ] If using rules, provide the output of this command: `Backlog Rule1; Rule2; Rule3`:
```lua
Rules output here:
```
- [ ] Provide the output of this command: `Status 0`:
```lua
STATUS 0 output here:
```
- [ ] Set `weblog` to 4 and then, when you experience your issue, provide the output of the Console log:
```lua
Console output here:
```
### TO REPRODUCE
_Steps to reproduce the behavior:_
### EXPECTED BEHAVIOUR
_A clear and concise description of what you expected to happen._
### SCREENSHOTS
_If applicable, add screenshots to help explain your problem._
### ADDITIONAL CONTEXT
_Add any other context about the problem here._
**(Please, remember to close the issue when the problem has been addressed)**

View File

@ -1,11 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Tasmota Docs
url: https://tasmota.github.io/docs
about: All the information related to Tasmota.
- name: Tasmota Discussions and Support
url: https://github.com/arendst/Tasmota/discussions
about: Tasmota usage Questions, Feature Requests and Projects.
- name: Tasmota Users Chat
url: https://discord.gg/Ks2Kzd4
about: Chat for feedback, questions and troubleshooting.

View File

@ -1,13 +0,0 @@
## Description:
**Related issue (if applicable):** fixes #<Tasmota issue number goes here>
## Checklist:
- [ ] The pull request is done against the latest development branch
- [ ] Only relevant files were touched
- [ ] Only one feature/fix was added per PR and the code change compiles without warnings
- [ ] The code change is tested and works on Tasmota core ESP8266 V.2.7.4.9
- [ ] The code change is tested and works with core ESP32 V.1.0.6
- [ ] I accept the [CLA](https://github.com/arendst/Tasmota/blob/development/CONTRIBUTING.md#contributor-license-agreement-cla).
_NOTE: The code change must pass CI tests. **Your PR cannot be merged unless tests pass**_

11
.github/config.yml vendored
View File

@ -1,11 +0,0 @@
# Configuration for sentiment-bot - https://github.com/behaviorbot/sentiment-bot
# *Required* toxicity threshold between 0 and .99 with the higher numbers being the most toxic
# Anything higher than this threshold will be marked as toxic and commented on
sentimentBotToxicityThreshold: .7
# *Required* Comment to reply with
sentimentBotReplyComment: >
Please be sure to review the code of conduct and be respectful of other users.
# Note: the bot will only work if your repository has a Code of Conduct

View File

@ -1,50 +0,0 @@
# CLOSE ISSUE BOT
# ---------------
# A bot which helps you to close issues that don't include some specific contents.
# See how to use it in https://github.com/offu/close-issue-app.
# Comment that will be sent if an issue is judged to be closed.
comment: >-
This issue has been automatically closed because the PROBLEM REPORT TEMPLATE is missing or incomplete.
Filling the template is required so standard questions don't need to be asked again each time.
Our ability to provide assistance is greatly hampered if few minutes are not taken to complete the issue template
with the requested information. The details requested potentially affect which options to pursue. The small amount
of time you will spend completing the template will also help the volunteers, providing assistance to you, to reduce
the time required to help you.
Please, could you be so kind on completing the [PROBLEM REPORT TEMPLATE](https://github.com/arendst/Tasmota/issues/new/choose) in order to have more information so as to properly help you?
Thank you for taking the time to report, hopefully it can be resolved soon.
[Docs](https://tasmota.github.io/docs/) for more information.
[Discussions](https://github.com/arendst/Tasmota/discussions) for Questions, Feature Requests and Projects.
[Chat](https://discord.gg/Ks2Kzd4) for more users experience.
Please check the [Code of Conduct](https://github.com/arendst/Tasmota/blob/development/CODE_OF_CONDUCT.md) and the [Contributing Guideline and Policy](https://github.com/arendst/Tasmota/blob/development/CONTRIBUTING.md)
issueConfigs:
# There can be several configs for different kind of issues.
- content:
# template 1: bug report
- "PROBLEM DESCRIPTION"
- "REQUESTED INFORMATION"
- "TO REPRODUCE"
- "EXPECTED BEHAVIOUR"
- content:
# template 2: feature request
- "Have you looked for this feature in other issues and in the docs"
- "Describe the solution you'd like"
# Optional configuration:
#
# whether the keywords are case-insensitive
# default value is false, which means keywords are case-sensitive
caseInsensitive: true
# the label that will be added when the bot close an issue
# The bot will only add a label if this property is set.
label: "template missing/incomplete"
# The issue is judged to be legal if it includes all keywords from any of these two configs.
# Or it will be closed by the app.

View File

@ -1,651 +0,0 @@
name: Tasmota CI
on:
pull_request:
jobs:
tasmota:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-minimal:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-minimal
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-lite:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-lite
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-knx:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-knx
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-sensors:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-sensors
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-display:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-display
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-ir:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-ir
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-zbbridge:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-zbbridge
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-zigbee:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-zigbee
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-AF:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-AF
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-BG:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-BG
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-BR:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-BR
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-CN:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-CN
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-CZ:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-CZ
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-DE:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-DE
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-ES:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-ES
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-FR:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-FR
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-FY:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-FY
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-GR:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-GR
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-HE:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-HE
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-HU:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-HU
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-IT:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-IT
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-KO:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-KO
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-NL:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-NL
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-PL:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-PL
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-PT:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-PT
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-RO:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-RO
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-RU:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-RU
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-SE:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-SE
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-SK:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-SK
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-TR:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-TR
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-TW:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-TW
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-UK:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-UK
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota-VN:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: platformio run -e tasmota-VN
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output

View File

@ -1,665 +0,0 @@
name: Tasmota ESP32 CI
on:
pull_request:
jobs:
tasmota32:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32solo1:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32solo1
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-webcam:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-webcam
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-odroidgo:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-odroidgo
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-core2:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-core2
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-bluetooth:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-bluetooth
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-display:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-display
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-ir:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-ir
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-AF:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-AF
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-BG:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-BG
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-BR:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-BR
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-CN:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-CN
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-CZ:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-CZ
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-DE:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-DE
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-ES:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-ES
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-FR:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-FR
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-FY:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-FY
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-GR:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-GR
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-HE:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-HE
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-HU:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-HU
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-IT:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-IT
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-KO:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-KO
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-NL:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-NL
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-PL:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-PL
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-PT:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-PT
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-RO:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-RO
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-RU:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-RU
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-SE:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-SE
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-SK:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-SK
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-TR:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-TR
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-TW:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-TW
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-UK:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-UK
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output
tasmota32-VN:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up Python
uses: actions/setup-python@v1
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio
platformio upgrade --dev
platformio update
- name: Run PlatformIO
run: |
platformio run -e tasmota32-VN
- uses: actions/upload-artifact@v2
with:
name: firmware
path: ./build_output

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +0,0 @@
name: "Mark or close stale issues and PRs"
on:
schedule:
- cron: "30 * * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v3.0.15
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
days-before-stale: 25
days-before-close: 5
stale-issue-message: "This issue has been automatically marked as stale because it hasn't any activity in last few weeks. It will be closed if no further activity occurs. Thank you for your contributions."
stale-pr-message: "This PR has been automatically marked as stale because it hasn't any activity in last few weeks. It will be closed if no further activity occurs. Thank you for your contributions."
close-issue-message: "This issue was automatically closed because of being stale. Feel free to open a new one if you still experience this problem."
close-pr-message: "This PR was automatically closed because of being stale."
stale-pr-label: "stale"
stale-issue-label: "stale"
exempt-issue-labels: "bug,enhancement,pinned,security"
exempt-pr-labels: "bug,enhancement,pinned,security"

389
.gitignore vendored
View File

@ -1,38 +1,361 @@
## OS specific ########
.DS_Store
# ---> C++
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
# ---> C
# Prerequisites
*.d
# Object files
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf
# ---> CMake
CMakeLists.txt.user
CMakeCache.txt
CMakeFiles
CMakeScripts
Testing
Makefile
cmake_install.cmake
install_manifest.txt
compile_commands.json
CTestTestfile.cmake
_deps
# ---> JetBrains
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# ---> Linux
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
## Compilation artefacts ########
*.pyc
*.d
*.o
*.gcno
*.gcda
# KDE directory preferences
.directory
## Project files ######
.platformio
.pio
.clang_complete
.gcc-flags.json
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
# ---> Ninja
.ninja_deps
.ninja_log
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
data
unpacked_fs
tasmota/user_config_override.h
build
build_output
firmware.map
firmware.asm
tasmota/tasmota.ino.cpp
tasmota*.bin
tasmota*.bin.gz
tasmota*.map
platformio_override.ini
platformio_tasmota_cenv.ini
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
## Visual Studio Code specific ######
.vscode
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
*.bak
*.code-workspace

5
.gitpod.Dockerfile vendored
View File

@ -1,5 +0,0 @@
FROM gitpod/workspace-full
USER gitpod
RUN pip3 install -U platformio && brew install uncrustify

View File

@ -1,14 +0,0 @@
tasks:
- before: platformio upgrade
- command: platformio run -e tasmota
image:
file: .gitpod.Dockerfile
vscode:
extensions:
- ms-vscode.cpptools@0.26.3:u3GsZ5PK12Ddr79vh4TWgQ==
- eamodio.gitlens@10.2.1:e0IYyp0efFqVsrZwsIe8CA==
- LaurentTreguier.uncrustify@2.18.0:/k8Osjj/XSuz09F+pEu7wg==
- Atishay-Jain.All-Autocomplete@0.0.23:fbZNfSpnd8XkAHGfAPS2rA==
- 2gua.rainbow-brackets@0.0.6:Tbu8dTz0i+/bgcKQTQ5b8g==

View File

@ -1,47 +0,0 @@
language: python
python:
- '3.7'
sudo: false
install:
- pip install -U platformio
- platformio upgrade --dev
- platformio update
cache: false
env:
- ENV=tasmota
- ENV=tasmota-minimal
- ENV=tasmota-lite
- ENV=tasmota-knx
- ENV=tasmota-sensors
- ENV=tasmota-display
- ENV=tasmota-ir
- ENV=tasmota-BG
- ENV=tasmota-BR
- ENV=tasmota-CN
- ENV=tasmota-CZ
- ENV=tasmota-DE
- ENV=tasmota-ES
- ENV=tasmota-FR
- ENV=tasmota-GR
- ENV=tasmota-HE
- ENV=tasmota-HU
- ENV=tasmota-IT
- ENV=tasmota-KO
- ENV=tasmota-NL
- ENV=tasmota-PL
- ENV=tasmota-PT
- ENV=tasmota-RO
- ENV=tasmota-RU
- ENV=tasmota-SE
- ENV=tasmota-SK
- ENV=tasmota-TR
- ENV=tasmota-TW
- ENV=tasmota-UK
- ENV=tasmota-VN
script:
- platformio run -e $ENV
before_deploy:
- for file in .pioenvs/*/firmware.bin; do cp $file ${file%/*}.bin; done

155
API.md
View File

@ -1,155 +0,0 @@
<img src="/tools/logo/TASMOTA_FullLogo_Vector.svg" alt="Logo" align="right" height="76"/>
# Basic API information
Tasmota can easily be extended by developers using provided function pointers as callback Ids. This document lists the available callback function Ids. Read [Sensor API](https://tasmota.github.io/docs/Sensor-API) for more information.
Callback availability can be checked by searching for either XdrvCall, XsnsCall, XdspCall, XnrgCall and XlgtCall.
## Driver, Sensor, Energy and Light Callback Ids
The following table lists Callback Ids and their availability for a Driver, Sensor or Energy service.
Callback Id | Bool | xdrv | xsns | xnrg | xlgt | Description
----------------------------|------|------|------|------|------|----------------------------------
FUNC_SETTINGS_OVERRIDE | | x | | | | Override start-up settings
FUNC_PIN_STATE | x | 1 | 2 | | | At GPIO configuration
FUNC_MODULE_INIT | x | 3 | 1 | | 2 | Init module specific parameters
FUNC_PRE_INIT | | 1 | 3 | 2 | | Once GPIO have been established
FUNC_INIT | | 1 | 3 | 2 | | At end of initialisation
FUNC_LOOP | | 1 | 2 | | | In main loop
FUNC_EVERY_50_MSECOND | | 1 | 2 | | |
FUNC_EVERY_100_MSECOND | | 1 | 2 | | |
FUNC_EVERY_200_MSECOND | | | | x | |
FUNC_EVERY_250_MSECOND | | 1 | 3 | 2 | |
FUNC_EVERY_SECOND | | 1 | 2 | | |
FUNC_SAVE_AT_MIDNIGHT | | | x | | | At midnight
FUNC_SAVE_BEFORE_RESTART | | 2 | 1 | | | Just before a planned restart
FUNC_AFTER_TELEPERIOD | | 2 | 1 | | | At end of teleperiod
FUNC_JSON_APPEND | | 2 | 1 | 3 | | Extend teleperiod JSON text
FUNC_WEB_SENSOR | | 2 | 1 | 3 | | Add sensor data to web GUI
FUNC_COMMAND | x | 1 | 2 | 3 | 4 | When a command is not recognized
FUNC_COMMAND_DRIVER | x | x | | | | When command Driver\<id\> is executed
FUNC_COMMAND_SENSOR | x | | x | | | When command Sensor\<id\> is executed
FUNC_MQTT_SUBSCRIBE | | x | | | | At end of MQTT subscriptions
FUNC_MQTT_INIT | | x | | | | Once at end of MQTT connection
FUNC_MQTT_DATA | x | x | | | | Before decoding command
FUNC_SET_POWER | | 1 | 2 | | | Before setting relays
FUNC_SET_DEVICE_POWER | x | x | | | | Set relay
FUNC_SHOW_SENSOR | | x | | | | When FUNC_JSON_APPEND completes
FUNC_ANY_KEY | | x | | | |
FUNC_ENERGY_EVERY_SECOND | | | | x | |
FUNC_ENERGY_RESET | | | | x | |
FUNC_RULES_PROCESS | x | x | | | | Process specific rule
FUNC_SERIAL | x | 1 | | 2 | 3 | Process serial data
FUNC_FREE_MEM | | x | | | | Show free memory for debugging
FUNC_BUTTON_PRESSED | x | x | | | | When a button is pressed
FUNC_WEB_ADD_BUTTON | | 1 | 2 | | | Add a Configuration Button to GUI
FUNC_WEB_ADD_MAIN_BUTTON | | 1 | 2 | | | Add a main button to GUI
FUNC_WEB_ADD_HANDLER | | 1 | 2 | | | Add a webserver handler
FUNC_SET_CHANNELS | | 2 | | | 1 |
FUNC_SET_SCHEME | | | | | x |
FUNC_HOTPLUG_SCAN | | | x | | |
FUNC_DEVICE_GROUP_ITEM | | x | | | |
The numbers represent the sequence of execution
## Display Call back Ids
The following table lists all Callback Ids for a Display service.
Callback Id | Bool | Description
------------------------------|------|---------------------
FUNC_DISPLAY_INIT_DRIVER | |
FUNC_DISPLAY_INIT | |
FUNC_DISPLAY_EVERY_50_MSECOND | |
FUNC_DISPLAY_EVERY_SECOND | |
FUNC_DISPLAY_MODEL | x |
FUNC_DISPLAY_MODE | |
FUNC_DISPLAY_POWER | |
FUNC_DISPLAY_CLEAR | |
FUNC_DISPLAY_DRAW_FRAME | |
FUNC_DISPLAY_DRAW_HLINE | |
FUNC_DISPLAY_DRAW_VLINE | |
FUNC_DISPLAY_DRAW_LINE | |
FUNC_DISPLAY_DRAW_CIRCLE | |
FUNC_DISPLAY_FILL_CIRCLE | |
FUNC_DISPLAY_DRAW_RECTANGLE | |
FUNC_DISPLAY_FILL_RECTANGLE | |
FUNC_DISPLAY_TEXT_SIZE | |
FUNC_DISPLAY_FONT_SIZE | |
FUNC_DISPLAY_ROTATION | |
FUNC_DISPLAY_DRAW_STRING | |
FUNC_DISPLAY_ONOFF | |
## Init sequence
The following list shows a typical callback init sequence
```
CFG: Loaded from flash at FB, Count 1581
xdrv - FUNC_SETTINGS_OVERRIDE
xdrv - FUNC_PIN_STATE
xsns - FUNC_PIN_STATE
xsns - FUNC_MODULE_INIT
xdrv - FUNC_MODULE_INIT
xlgt - FUNC_MODULE_INIT
xdrv - FUNC_PRE_INIT
xnrg - FUNC_PRE_INIT
xsns - FUNC_PRE_INIT
SRC: Restart
xdrv - FUNC_SET_POWER
xsns - FUNC_SET_POWER
xlgt - FUNC_SET_CHANNELS
xdrv - FUNC_SET_DEVICE_POWER
Project tasmota Wemos 2 Version 7.0.0.3(tasmota)-STAGE
xdrv - FUNC_INIT
xsns - FUNC_INIT
I2C: ADS1115 found at 0x48
xdrv - FUNC_LOOP
xsns - FUNC_LOOP
xdrv - FUNC_EVERY_50_MSECOND
xlgt - FUNC_SET_CHANNELS
xsns - FUNC_EVERY_50_MSECOND
xdrv - FUNC_EVERY_100_MSECOND
xsns - FUNC_EVERY_100_MSECOND
xdrv - FUNC_EVERY_250_MSECOND
xsns - FUNC_EVERY_250_MSECOND
xdrv - FUNC_EVERY_SECOND
xsns - FUNC_EVERY_SECOND
WIF: Attempting connection...
WIF: Network (re)scan started...
WIF: Attempting connection...
WIF: Attempting connection...
WIF: Attempting connection...
WIF: Network 0, AP1, SSId indebuurt1, Channel 1, BSSId 24:D3:F2:97:C0:A1, RSSI -86, Encryption 1
WIF: Network 1, AP2, SSId indebuurt2, Channel 5, BSSId A0:AB:1B:7D:42:AC, RSSI -42, Encryption 1
WIF: Network 2, AP-, SSId indebuurt3, Channel 12, BSSId 60:E3:27:58:77:E6, RSSI -84, Encryption 1
WIF: Connecting to AP2 indebuurt2 in mode 11N as wemos2...
WIF: Attempting connection...
WIF: Attempting connection...
WIF: Attempting connection...
WIF: Connected
xdrv - FUNC_WEB_ADD_HANDLER
xsns - FUNC_WEB_ADD_HANDLER
HTP: Web server active on wemos2 with IP address 192.168.2.191
NTP: Drift 0, (UTC) Wed Nov 06 13:57:08 2019, (DST) Sun Mar 31 02:00:00 2019, (STD) Sun Oct 27 03:00:00 2019
APP: Boot Count 500
MQT: Attempting connection...
MQT: Connected
MQT: tele/wemos2/LWT = Online (retained)
MQT: cmnd/wemos2/POWER =
MQT: Subscribe to cmnd/wemos2/#
MQT: Subscribe to cmnd/sonoffs/#
MQT: Subscribe to cmnd/DVES_15568C_fb/#
xdrv - FUNC_MQTT_SUBSCRIBE
MQT: tele/wemos2/INFO1 = {"Module":"Generic","Version":"7.0.0.3(tasmota)","FallbackTopic":"cmnd/DVES_15568C_fb/","GroupTopic":"cmnd/sonoffs/"}
MQT: tele/wemos2/INFO2 = {"WebServerMode":"Admin","Hostname":"wemos2","IPAddress":"192.168.2.191"}
MQT: tele/wemos2/INFO3 = {"RestartReason":"Software/System restart"}
MQT: stat/wemos2/RESULT = {"POWER1":"OFF"}
MQT: stat/wemos2/POWER1 = OFF
MQT: stat/wemos2/RESULT = {"POWER2":"ON"}
MQT: stat/wemos2/POWER2 = ON
xdrv - FUNC_MQTT_INIT
CFG: Saved to flash at FA, Count 1582, Bytes 4096
```

233
BUILDS.md
View File

@ -1,233 +0,0 @@
## Available Features and Sensors
ESP8266 / ESP32
m = minimal, l = lite, t = tasmota, k = knx, s = sensors, i = ir, d = display
| Feature or Sensor | m | l | t | k | s | i | d | Remarks
|-----------------------|---|---|-------|---|---|---|---|--------
| MY_LANGUAGE en_GB | x | x | x / x | x | x | x | x |
| USE_UFILESYS | - | - | - / x | - | - | - | - |
| USE_ARDUINO_OTA | - | - | - / - | - | - | - | - |
| USE_DOMOTICZ | - | - | x / x | x | x | x | - |
| USE_HOME_ASSISTANT | - | - | x / x | x | x | x | - |
| USE_MQTT_TLS | - | - | - / - | - | - | - | - |
| USE_MQTT_TLS_CA_CERT | - | - | - / - | - | - | - | - |
| USE_MQTT_AWS_IOT | - | - | - / - | - | - | - | - |
| USE_4K_RSA | - | - | - / - | - | - | - | - |
| USE_TELEGRAM | - | - | - / - | - | - | - | - |
| USE_KNX | - | - | - / x | x | - | - | - |
| USE_WEBSERVER | x | x | x / x | x | x | x | x |
| USE_JAVASCRIPT_ES6 | - | - | - / - | - | - | - | - |
| USE_WEBSEND_RESPONSE | - | - | - / - | - | - | - | - |
| USE_EMULATION_HUE | - | x | x / x | - | x | - | - |
| USE_EMULATION_WEMO | - | x | x / x | - | x | - | - |
| USE_DISCOVERY | - | - | - / - | - | - | - | - |
| WEBSERVER_ADVERTISE | - | - | x / - | x | - | - | x |
| MQTT_HOST_DISCOVERY | - | - | - / - | - | - | - | - |
| USE_TIMERS | - | x | x / x | x | x | x | x |
| USE_TIMERS_WEB | - | x | x / x | x | x | x | x |
| USE_SUNRISE | - | x | x / x | x | x | x | x |
| USE_RULES | - | x | x / x | x | x | x | x |
| USE_SCRIPT | - | - | - / - | - | - | - | - |
| USE_EXPRESSION | - | - | - / - | - | - | - | - |
| SUPPORT_IF_STATEMENT | - | - | - / - | - | - | - | - |
| USE_HOTPLUG | - | - | - / - | - | - | - | - |
| USE_PROMETHEUS | - | - | - / - | - | - | - | - |
| USE_PING | - | - | - / - | - | - | - | - |
| | | | | | | | |
| Feature or Sensor | m | l | t | k | s | i | d | Remarks
| ROTARY_V1 | - | - | x / x | - | x | - | - |
| USE_SONOFF_RF | - | - | x / - | x | x | - | - |
| USE_RF_FLASH | - | - | x / - | x | x | - | - |
| USE_SONOFF_SC | - | - | x / - | x | x | - | - |
| USE_TUYA_MCU | - | x | x / - | x | x | - | x |
| USE_ARMTRONIX_DIMMERS | - | - | x / - | x | - | - | - |
| USE_PS_16_DZ | - | - | x / - | x | - | - | - |
| USE_SONOFF_IFAN | - | - | x / - | x | - | - | - |
| USE_BUZZER | - | - | x / x | x | x | - | - |
| USE_ARILUX_RF | - | - | x / - | x | - | - | - |
| USE_SHUTTER | - | - | x / x | x | - | - | - |
| USE_DEEPSLEEP | - | - | x / x | - | x | - | - |
| USE_EXS_DIMMER | - | - | x / - | x | - | - | - |
| USE_DEVICE_GROUPS | - | - | x / x | - | - | - | - |
| USE_PWM_DIMMER | - | - | x / - | x | - | - | - |
| USE_KEELOQ | - | - | - / - | - | - | - | - |
| USE_SONOFF_D1 | - | - | x / - | x | - | - | - |
| USE_SHELLY_DIMMER | - | - | x / - | - | - | - | - |
| | | | | | | | |
| Feature or Sensor | m | l | t | k | s | i | d | Remarks
| USE_LIGHT | - | x | x / x | x | x | x | x |
| USE_WS2812 | - | - | x / x | x | x | - | x |
| USE_WS2812_DMA | - | - | - / - | - | - | - | - |
| USE_MY92X1 | - | - | x / - | x | x | - | x |
| USE_SM16716 | - | - | x / - | x | x | - | x |
| USE_SM2135 | - | - | x / - | x | x | - | x |
| USE_SONOFF_L1 | - | - | x / - | x | x | - | x |
| USE_ELECTRIQ_MOODL | - | - | x / - | x | x | - | x |
| | | | | | | | |
| USE_ENERGY_SENSOR | - | x | x / x | x | x | - | - |
| USE_ENERGY_DUMMY | - | x | x / x | x | x | - | - |
| USE_PZEM004T | - | - | x / x | x | x | - | - |
| USE_PZEM_AC | - | - | x / x | x | x | - | - |
| USE_PZEM_DC | - | - | x / x | x | x | - | - |
| USE_MCP39F501 | - | x | x / - | x | x | - | - |
| USE_SDM72 | - | - | - / x | - | x | - | - |
| USE_SDM120 | - | - | - / x | - | x | - | - |
| USE_SDM630 | - | - | - / x | - | x | - | - |
| USE_DDS2382 | - | - | - / x | - | x | - | - |
| USE_DDSU666 | - | - | - / x | - | x | - | - |
| USE_SOLAX_X1 | - | - | - / - | - | - | - | - |
| USE_LE01MR | - | - | - / - | - | - | - | - |
| USE_BL0940 | - | x | x / - | x | x | - | - |
| USE_TELEINFO | - | - | - / - | - | - | - | - |
| USE_IEM3000 | - | - | - / - | - | - | - | - |
| USE_WE517 | - | - | - / - | - | - | - | - |
| | | | | | | | |
| USE_ADC_VCC | x | x | - / - | - | - | x | - |
| USE_COUNTER | - | - | x / x | x | x | - | x |
| USE_DS18x20 | - | - | x / x | x | x | - | x |
| USE_DHT | - | - | x / x | x | x | - | x |
| USE_MAX31855 | - | - | - / x | - | x | - | - |
| USE_MAX31865 | - | - | - / - | - | - | - | - |
| USE_THERMOSTAT | - | - | - / - | - | - | - | - |
| USE_LMT01 | - | - | - / x | - | x | - | - |
| | | | | | | | |
| Feature or Sensor | m | l | t | k | s | i | d | Remarks
| USE_I2C | - | - | x / x | x | x | - | x |
| USE_SHT | - | - | - / x | - | x | - | - |
| USE_HTU | - | - | - / x | - | x | - | - |
| USE_BMP | - | - | - / x | - | x | - | - |
| USE_BME680 | - | - | - / x | - | x | - | - |
| USE_BH1750 | - | - | - / x | - | x | - | - |
| USE_VEML6070 | - | - | - / x | - | x | - | - |
| USE_ADS1115 | - | - | - / x | - | x | - | - |
| USE_INA219 | - | - | - / x | - | x | - | - |
| USE_INA226 | - | - | - / - | - | - | - | - |
| USE_SHT3X | - | - | - / x | - | x | - | - |
| USE_TSL2561 | - | - | - / - | - | - | - | - |
| USE_TSL2591 | - | - | - / - | - | - | - | - |
| USE_MGS | - | - | - / x | - | x | - | - |
| USE_SGP30 | - | - | - / x | - | x | - | - |
| USE_SI1145 | - | - | - / - | - | - | - | - |
| USE_LM75AD | - | - | - / x | - | x | - | - |
| USE_APDS9960 | - | - | - / - | - | - | - | - |
| USE_MCP230xx | - | - | - / - | - | - | - | - |
| USE_PCA9685 | - | - | - / - | - | - | - | - |
| USE_MPR121 | - | - | - / - | - | - | - | - |
| USE_CCS811 | - | - | - / - | - | x | - | - |
| USE_CCS811_V2 | - | - | - / x | - | - | - | - |
| USE_MPU6050 | - | - | - / - | - | - | - | - |
| USE_DS3231 | - | - | - / - | - | - | - | - |
| USE_MGC3130 | - | - | - / - | - | - | - | - |
| USE_MAX44009 | - | - | - / - | - | - | - | - |
| USE_SCD30 | - | - | - / x | - | x | - | - |
| USE_SPS30 | - | - | - / - | - | - | - | - |
| USE_ADE7953 | - | - | x / x | x | x | - | x |
| USE_VL53L0X | - | - | - / x | - | x | - | - |
| USE_MLX90614 | - | - | - / - | - | - | - | - |
| USE_CHIRP | - | - | - / - | - | - | - | - |
| USE_PAJ7620 | - | - | - / - | - | - | - | - |
| USE_PCF8574 | - | - | - / - | - | - | - | - |
| | | | | | | | |
| Feature or Sensor | m | l | t | k | s | i | d | Remarks
| USE_HIH6 | - | - | - / x | - | x | - | - |
| USE_DHT12 | - | - | - / x | - | x | - | - |
| USE_DS1624 | - | - | - / x | - | x | - | - |
| USE_AHT1x | - | - | - / - | - | - | - | - |
| USE_HDC1080 | - | - | - / - | - | - | - | - |
| USE_WEMOS_MOTOR_V1 | - | - | - / x | - | x | - | - |
| USE_IAQ | - | - | - / x | - | x | - | - |
| USE_AS3935 | - | - | - / x | - | x | - | - |
| USE_VEML6075 | - | - | - / - | - | - | - | - |
| USE_VEML7700 | - | - | - / - | - | - | - | - |
| USE_MCP9808 | - | - | - / - | - | - | - | - |
| USE_HP303B | - | - | - / - | - | - | - | - |
| USE_EZOCO2 | - | - | - / - | - | - | - | - |
| USE_EZODO | - | - | - / - | - | - | - | - |
| USE_EZOEC | - | - | - / - | - | - | - | - |
| USE_EZOFLO | - | - | - / - | - | - | - | - |
| USE_EZOHUM | - | - | - / - | - | - | - | - |
| USE_EZOO2 | - | - | - / - | - | - | - | - |
| USE_EZOORP | - | - | - / - | - | - | - | - |
| USE_EZOPH | - | - | - / - | - | - | - | - |
| USE_EZOPMP | - | - | - / - | - | - | - | - |
| USE_EZOPRS | - | - | - / - | - | - | - | - |
| USE_EZORGB | - | - | - / - | - | - | - | - |
| USE_EZORTD | - | - | - / - | - | - | - | - |
| USE_SEESAW_SOIL | - | - | - / - | - | - | - | - |
| USE_TOF10120 | - | - | - / - | - | - | - | - |
| | | | | | | | |
| Feature or Sensor | m | l | t | k | s | i | d | Remarks
| USE_SPI | - | - | - / - | - | - | - | x |
| USE_RC522 | - | - | - / - | - | - | - | - |
| USE_MHZ19 | - | - | - / x | - | x | - | - |
| USE_SENSEAIR | - | - | - / x | - | x | - | - |
| USE_PMS5003 | - | - | - / x | - | x | - | - |
| USE_NOVA_SDS | - | - | - / x | - | x | - | - |
| USE_HPMA | - | - | - / x | - | x | - | - |
| USE_SERIAL_BRIDGE | - | - | x / x | x | x | - | x |
| USE_MP3_PLAYER | - | - | - / x | - | x | - | - |
| USE_AZ7798 | - | - | - / - | - | - | - | - |
| USE_PN532_HSU | - | - | - / x | - | x | - | - |
| USE_RDM6300 | - | - | - / x | - | x | - | - |
| USE_IBEACON | - | - | - / x | - | x | - | - |
| USE_GPS | - | - | - / - | - | - | - | - |
| USE_HM10 | - | - | - / - | - | x | - | - |
| USE_HRXL | - | - | - / x | - | x | - | - |
| USE_TASMOTA_CLIENT | - | - | - / - | - | - | - | - |
| USE_OPENTHERM | - | - | - / - | - | - | - | - |
| USE_MIEL_HVAC | - | - | - / - | - | - | - | - |
| USE_PROJECTOR_CTRL | - | - | - / - | - | - | - | - |
| USE_AS608 | - | - | - / - | - | - | - | - |
| USE_TCP_BRIDGE | - | - | - / - | - | - | - | - | zbbridge
| | | | | | | | |
| USE_NRF24 | - | - | - / - | - | - | - | - |
| USE_MIBLE | - | - | - / - | - | - | - | - |
| USE_ZIGBEE | - | - | - / - | - | - | - | - |
| USE_ZIGBEE_ZNP | - | - | - / - | - | - | - | - |
| USE_ZIGBEE_EZSP | - | - | - / - | - | - | - | - | Sonoff ZbBridge
| | | | | | | | |
| USE_IR_REMOTE | - | - | x / - | x | x | x | x |
| USE_IR_RECEIVE | - | - | x / - | x | x | x | x |
| USE_IR_REMOTE_FULL | - | - | - / - | - | - | x | - | Enable ALL protocols
| | | | | | | | |
| USE_SR04 | - | - | - / - | - | x | - | - |
| USE_DYP | - | - | - / - | - | - | - | - |
| USE_TM1638 | - | - | - / x | - | x | - | - |
| USE_HX711 | - | - | - / x | - | x | - | - |
| USE_TX2x_WIND_SENSOR | - | - | - / - | - | - | - | - |
| USE_WINDMETER | - | - | - / - | - | - | - | - |
| USE_RC_SWITCH | - | - | - / x | - | x | - | - |
| USE_RF_SENSOR | - | - | - / x | - | x | - | - | AlectoV2 only
| USE_HRE | - | - | - / x | - | x | - | - |
| USE_A4988_STEPPER | - | - | - / - | - | - | - | - |
| USE_NEOPOOL | - | - | - / - | - | - | - | - |
| | | | | | | | |
| Feature or Sensor | m | l | t | k | s | i | d | Remarks
| USE_DISPLAY | - | - | - / - | - | - | - | x |
| USE_DISPLAY_LCD | - | - | - / - | - | - | - | x |
| USE_DISPLAY_SSD1306 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_MATRIX | - | - | - / - | - | - | - | x |
| USE_DISPLAY_SH1106 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_ILI9341 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_EPAPER_29 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_EPAPER_42 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_ILI9488 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_SSD1351 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_RA8876 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_ST7789 | - | - | - / - | - | - | - | x |
| USE_DISPLAY_TM1637 | - | - | - / - | - | - | - | x |
| | | | | | | | |
| USE_FT5206 | - | - | - / - | - | - | - | - |
| USE_FTC532 | - | - | - / - | - | - | - | - |
| USE_BS814A2 | - | - | - / - | - | - | - | - |
| | | | | | | | |
| ESP32 Feature | m | l | t | k | s | i | d | Remarks
| USE_HALLEFFECT | | | / x | | | | |
| USE_MI_ESP32 | | | / x | | | | | See SetOption115
| USE_IBEACON_ESP32 | | | / - | | | | |
| USE_WEBCAM | | | / - | | | | |
| USE_ETHERNET | | | / - | | | | |
| USE_I2S_AUDIO | | | / - | | | | |
| USE_TTGO_WATCH | | | / - | | | | |

File diff suppressed because it is too large Load Diff

View File

@ -1,130 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
https://sidweb.nl/cms3/en/contact.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

View File

@ -1,115 +0,0 @@
<img src="/tools/logo/TASMOTA_FullLogo_Vector.svg" alt="Logo" align="right" height="76"/>
# Contributing
**Any contribution helps our team and makes Tasmota better for the entire community!**
Everybody is welcome and invited to contribute to Tasmota Project by:
* Testing newly released features and reporting issues.
* Providing Pull Requests (Features, Proof of Concepts, Language files or Fixes)
* Contributing missing documentation for features and devices in our [documentation](https://tasmota.github.io/docs/Contributing)
This document describes rules that are in effect for this repository, meant for handling issues by contributors in the issue tracker and PRs.
## Opening New Issues
**Issue tracker is NOT a general discussion forum!**
1. Opening an issue means that a problem exists in the code and should be addressed by the project contributors.
2. When opening an issue, it is required to fill out the presented template. The requested information is important! If the template is ignored or insufficient info about the issue is provided, the issue may be closed.
3. Questions of type "How do I..." or "Can you please help me with..." or "Can Tasmota do..." WILL NOT be handled here. Such questions should be directed at a discussion forum or to the Tasmota Support Chat. All issues of this type will be closed with a simple reference to this contributing policy.
4. Issues about topics already handled in the documentation will be closed in a similar manner.
5. Issues for unmerged PRs will be closed. If there is an issue with a PR, the explanation should be added to the PR itself.
6. Issues with accompanied investigation that shows the root of the problem should be given priority.
7. Duplicate issues will be closed.
## Triaging of Issues/PR's
1. Any contributor to the project can participate in the triaging process, if he/she chooses to do so.
2. An issue that needs to be closed, either due to not complying with this policy, or for other reasons, should be closed by a contributor.
3. Issues that are accepted should be marked with appropriate labels.
4. Issues that could impact functionality for many users should be considered severe.
5. Issues caused by the SDK or chip should not be marked severe, as there usually isnt much to be done. Common sense should be applied when deciding. Such issues should be documented in the Wiki, for reference by users.
6. Issues with feature requests should be discussed for viability/desirability.
7. Feature requests or changes that are meant to address a very specific/limited use case, especially if at the expense of increased code complexity, may be denied, or may be required to be redesigned, generalized, or simplified.
8. Feature requests that are not accompanied by a PR:
* could be closed immediately (denied).
* could be closed after some predetermined period of time (left as candidate for somebody to pick up).
9. In some cases, feedback may be requested from the issue reporter, either as additional info for clarification, additional testing, or other. If no feedback is provided, the issue may be closed by a contributor or after 30 days by the STALE bot.
## Pull requests
A Pull Request (PR) is the process where code modifications are managed in GitHub.
The process is straight-forward.
- Read [How to get faster PR reviews](https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews) by Kubernetes (but skip step 0)
- Fork the Tasmota Repository [git repository](https://github.com/arendst/Tasmota).
- Write/Change the code in your Fork for a new feature, bug fix, new sensor, optimization, etc.
- Ensure tests work.
- Create a Pull Request against the [**development**](https://github.com/arendst/Tasmota/tree/development) branch of Tasmota.
1. All pull requests must be done against the development branch.
2. Only relevant files should be touched (Also beware if your editor has auto-formatting feature enabled).
3. Only one feature/fix should be added per PR.
4. If adding a new functionality (new hardware, new library support) not related to an existing component move it to it's own modules (.ino file).
5. PRs that don't compile (fail in CI Tests) or cause coding errors will not be merged. Please fix the issue. Same goes for PRs that are raised against older commit in development - you might need to rebase and resolve conflicts.
6. All pull requests should undergo peer review by at least one contributor other than the creator, excepts for the owner.
7. All pull requests should consider updates to the documentation.
8. Pull requests that address an outstanding issue, particularly an issue deemed to be severe, should be given priority.
9. If a PR is accepted, then it should undergo review and updated based on the feedback provided, then merged.
10. By submitting a PR, it is needed to use the provided PR template and check all boxes, performing the required tasks and accepting the CLA.
11. Pull requests that don't meet the above will be denied and closed.
--------------------------------------
## Contributor License Agreement (CLA)
```
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the GPL-3.0 license; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the GPL-3.0 license; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it) is maintained indefinitely
and may be redistributed consistent with this project or the open
source license(s) involved.
```
This Contributor License Agreement (CLA) was adopted on April 1st, 2019.
The text of this license is available under the [Creative Commons Attribution-ShareAlike 3.0 Unported License](http://creativecommons.org/licenses/by-sa/3.0/). It is based on the Linux [Developer Certificate Of Origin](http://elinux.org/Developer_Certificate_Of_Origin), but is modified to explicitly use the GPL-3.0 license and not mention sign-off (due to GitHub.com keeps an historial, with your user name, of PRs' commits and all editions on PR's comments).
To accept the CLA it is required to put a x between [ ] on `[ ] I accept the CLA` in the PR template when submitting it. The [ ] is an opt-in box, so you have to manually accept it.
**Why a CLA ?**
_"A Contributor Licence Agreement (CLA) is strongly recommended when accepting third party contributions to an open development project, such as an open source software project. In order to redistribute contributions, it is necessary to ensure that the project has the necessary rights to do so. A Contributor Licence Agreement is a lightweight agreement, signed by the copyright holder, that grants the necessary rights for the contribution to be redistributed as part of the project."_ [OSS Watch](http://oss-watch.ac.uk/resources/cla)
A CLA is a legal document in which you state _you are entitled to contribute the code/documentation/translation to the project_ youre contributing to and that _you are willing to have it used in distributions and derivative works_. This means that should there be any kind of legal issue in the future as to the origins and ownership of any particular piece of code, then that project has the necessary forms on file from the contributor(s) saying they were permitted to make this contribution.
CLA is a safety because it also ensures that once you have provided a contribution, you cannot try to withdraw permission for its use at a later date. People can therefore use that software, confident that they will not be asked to stop using pieces of the code at a later date.
A __license__ grants "outbound" rights to the user of project.
A __CLA__ enables a contributor to grant "inbound" rights to a project.
<Other>
<A table should be maintained for relating maintainers and components. When triaging, this is essential to figure out if someone in particular should be consulted about specific changes.>
<A stable release cadence should be established, e.g.: every month.>

2489
Doxyfile

File diff suppressed because it is too large Load Diff

View File

@ -1,44 +0,0 @@
![Tasmota logo](https://github.com/arendst/Tasmota/blob/development/tools/logo/TASMOTA_FullLogo_Vector.svg)
Alternative firmware for [ESP8266](https://en.wikipedia.org/wiki/ESP8266) based devices with **easy configuration using webUI, OTA updates, automation using timers or rules, expandability and entirely local control over MQTT, HTTP, Serial or KNX**.
_Written for PlatformIO with limited support for Arduino IDE._
[![GitHub version](https://img.shields.io/github/release/arendst/Tasmota.svg)](https://github.com/arendst/Tasmota/releases/latest)
[![GitHub download](https://img.shields.io/github/downloads/arendst/Tasmota/total.svg)](https://github.com/arendst/Tasmota/releases/latest)
[![License](https://img.shields.io/github/license/arendst/Tasmota.svg)](LICENSE.txt)
[![Chat](https://img.shields.io/discord/479389167382691863.svg)](https://discord.gg/Ks2Kzd4)
If you like **Tasmota**, give it a star, or fork it and contribute!
[![GitHub stars](https://img.shields.io/github/stars/arendst/Tasmota.svg?style=social&label=Star)](https://github.com/arendst/Tasmota/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/arendst/Tasmota.svg?style=social&label=Fork)](https://github.com/arendst/Tasmota/network)
[![donate](https://img.shields.io/badge/donate-PayPal-blue.svg)](https://paypal.me/tasmota)
See [CHANGELOG.md](https://github.com/arendst/Tasmota/blob/development/tasmota/CHANGELOG.md) for changes since last release.
## Development
[![Dev Version](https://img.shields.io/badge/development%20version-v9.5.x.x-blue.svg)](https://github.com/arendst/Tasmota)
[![Download Dev](https://img.shields.io/badge/download-development-yellow.svg)](http://ota.tasmota.com/tasmota/)
[![Tasmota CI](https://github.com/arendst/Tasmota/workflows/Tasmota%20CI/badge.svg)](https://github.com/arendst/Tasmota/actions?query=workflow%3A%22Tasmota+CI%22)
[![Tasmota ESP32 CI](https://github.com/arendst/Tasmota/workflows/Tasmota%20ESP32%20CI/badge.svg)](https://github.com/arendst/Tasmota/actions?query=workflow%3A%22Tasmota+ESP32+CI%22)
[![Build_firmware](https://github.com/arendst/Tasmota/workflows/Build_firmware/badge.svg)](https://github.com/arendst/Tasmota/actions?query=workflow%3ABuild_firmware)
Unless your Tasmota powered device exhibits a problem or you need to make use of a feature that is not available in the Tasmota version currently installed on your device, leave your device alone - it works so don't make unnecessary changes! If the release version (i.e., the master branch) exhibits unexpected behaviour for your device and configuration, you should upgrade to the latest development version instead to see if your problem is resolved as some bugs in previous releases or development builds may already have been resolved.
If new commits have been merged and they compile successfuly, new binary files for every variant will be placed here https://github.com/arendst/Tasmota/tree/firmware/firmware (this URL address can NOT be used for OTA updates) It is important to note that these binaries are based on the current development codebase. These commits are tested as much as is possible and are typically quite stable. However, it is infeasible to test on the hundreds of different types of devices with all the available configuration options permitted.
Note that there is a chance, as with any upgrade, that the device may not function as expected. You must always account for the possibility that you may need to flash the device via the serial programming interface if the OTA upgrade fails. Even with the master release, you should always attempt to test the device or a similar prototype before upgrading a device which is in production or is hard to reach. And, as always, make a backup of the device configuration before beginning any firmware update.
## Disclaimer
:warning: **DANGER OF ELECTROCUTION** :warning:
If your device connects to mains electricity (AC power) there is danger of electrocution if not installed properly. If you don't know how to install it, please call an electrician (***Beware:*** certain countries prohibit installation without a licensed electrician present). Remember: _**SAFETY FIRST**_. It is not worth the risk to yourself, your family and your home if you don't know exactly what you are doing. Never tinker or try to flash a device using the serial programming interface while it is connected to MAINS ELECTRICITY (AC power).
We don't take any responsibility nor liability for using this software nor for the installation or any tips, advice, videos, etc. given by any member of this site or any related site.
## Quick Install
Download one of the binaries https://github.com/arendst/Tasmota/tree/firmware/firmware and flash it to your hardware [using our installation guide](https://tasmota.github.io/docs/Getting-Started).

View File

@ -1,95 +0,0 @@
# I2C devices
Tasmota supports several I2C devices but to use them they mostly need to be enabled at compile time to solve possible address conflicts.
Using command ``I2cDriver`` individual drivers can be enabled or disabled at runtime allowing duplicate I2C addresses at compile time. Use the Index from the table below to control I2C drivers like ``I2cDriver10 0`` for disabling BMP support.
## Supported I2C devices
The following table lists the supported I2C devices
Index | Define | Driver | Device | Address(es) | Description
------|---------------------|---------|----------|-------------|-----------------------------------------------
1 | USE_PCA9685 | xdrv_15 | PCA9685 | 0x40 - 0x47 | 16-channel 12-bit pwm driver
2 | USE_PCF8574 | xdrv_28 | PCF8574 | 0x20 - 0x26 | 8-bit I/O expander
2 | USE_PCF8574 | xdrv_28 | PCF8574A | 0x39 - 0x3F | 8-bit I/O expander
3 | USE_DISPLAY_LCD | xdsp_01 | | 0x27, 0x3F | LCD display
4 | USE_DISPLAY_SSD1306 | xdsp_02 | SSD1306 | 0x3C - 0x3D | Oled display
5 | USE_DISPLAY_MATRIX | xdsp_03 | HT16K33 | 0x70 - 0x77 | 8x8 led matrix
6 | USE_DISPLAY_SH1106 | xdsp_07 | SH1106 | 0x3C - 0x3D | Oled display
7 | USE_ADE7953 | xnrg_07 | ADE7953 | 0x38 | Energy monitor
8 | USE_SHT | xsns_07 | SHT1X | Any | Temperature and Humidity sensor
9 | USE_HTU | xsns_08 | HTU21 | 0x40 | Temperature and Humidity sensor
9 | USE_HTU | xsns_08 | SI7013 | 0x40 | Temperature and Humidity sensor
9 | USE_HTU | xsns_08 | SI7020 | 0x40 | Temperature and Humidity sensor
9 | USE_HTU | xsns_08 | SI7021 | 0x40 | Temperature and Humidity sensor
10 | USE_BMP | xsns_09 | BMP085 | 0x76 - 0x77 | Pressure and temperature sensor
10 | USE_BMP | xsns_09 | BMP180 | 0x76 - 0x77 | Pressure and temperature sensor
10 | USE_BMP | xsns_09 | BMP280 | 0x76 - 0x77 | Pressure and temperature sensor
10 | USE_BMP | xsns_09 | BME280 | 0x76 - 0x77 | Pressure, temperature and humidity sensor
10 | USE_BMP | xsns_09 | BME680 | 0x76 - 0x77 | Pressure, temperature, humidity and gas sensor
11 | USE_BH1750 | xsns_10 | BH1750 | 0x23, 0x5C | Ambient light intensity sensor
12 | USE_VEML6070 | xsns_11 | VEML6070 | 0x38 - 0x39 | Ultra violet light intensity sensor
13 | USE_ADS1115 | xsns_12 | ADS1115 | 0x48 - 0x4B | 4-channel 16-bit A/D converter
14 | USE_INA219 | xsns_13 | INA219 | 0x40 - 0x41, 0x44 - 0x45 | Low voltage current sensor
15 | USE_SHT3X | xsns_14 | SHT3X | 0x44 - 0x45 | Temperature and Humidity sensor
15 | USE_SHT3X | xsns_14 | SHTC3 | 0x70 | Temperature and Humidity sensor
16 | USE_TSL2561 | xsns_16 | TSL2561 | 0x29, 0x39, 0x49 | Light intensity sensor
17 | USE_MGS | xsns_19 | Grove | 0x04 | Multichannel gas sensor
18 | USE_SGP30 | xsns_21 | SGP30 | 0x58 | Gas (TVOC) and air quality sensor
19 | USE_SI1145 | xsns_24 | SI1145 | 0x60 | Ultra violet index and light sensor
19 | USE_SI1145 | xsns_24 | SI1146 | 0x60 | Ultra violet index and light sensor
19 | USE_SI1145 | xsns_24 | SI1147 | 0x60 | Ultra violet index and light sensor
20 | USE_LM75AD | xsns_26 | LM75AD | 0x48 - 0x4F | Temperature sensor
21 | USE_APDS9960 | xsns_27 | APDS9960 | 0x39 | Proximity ambient light RGB and gesture sensor
22 | USE_MCP230xx | xsns_29 | MCP23008 | 0x20 - 0x26 | 16-bit I/O expander
22 | USE_MCP230xx | xsns_29 | MCP23017 | 0x20 - 0x26 | 16-bit I/O expander
23 | USE_MPR121 | xsns_30 | MPR121 | 0x5A - 0x5D | Proximity capacitive touch sensor
24 | USE_CCS811 | xsns_31 | CCS811 | 0x5A | Gas (TVOC) and air quality sensor
25 | USE_MPU6050 | xsns_32 | MPU6050 | 0x68 - 0x69 | 3-axis gyroscope and temperature sensor
26 | USE_DS3231 | xsns_33 | DS3231 | 0x68 | Real time clock
27 | USE_MGC3130 | xsns_36 | MGC3130 | 0x42 | Electric field sensor
28 | USE_MAX44009 | xsns_41 | MAX44009 | 0x4A - 0x4B | Ambient light intensity sensor
29 | USE_SCD30 | xsns_42 | SCD30 | 0x61 | CO2 sensor
30 | USE_SPS30 | xsns_44 | SPS30 | 0x69 | Particle sensor
31 | USE_VL53L0X | xsns_45 | VL53L0X | 0x29 | Time-of-flight (ToF) distance sensor
32 | USE_MLX90614 | xsns_46 | MLX90614 | 0x5A | Infra red temperature sensor
33 | USE_CHIRP | xsns_48 | CHIRP | 0x20 | Soil moisture sensor
34 | USE_PAJ7620 | xsns_50 | PAJ7620 | 0x73 | Gesture sensor
35 | USE_INA226 | xsns_54 | INA226 | 0x40 - 0x41, 0x44 - 0x45 | Low voltage current sensor
36 | USE_HIH6 | xsns_55 | HIH6130 | 0x27 | Temperature and Humidity sensor
37 | USE_24C256 | xdrv_10 | 24C256 | 0x50 | Scripter EEPROM storage
38 | USE_DISPLAY_ILI9488 | xdsp_08 | FT6236 | 0x38 | Touch panel controller
39 | USE_DISPLAY_RA8876 | xdsp_10 | FT5316 | 0x38 | Touch panel controller
40 | USE_TSL2591 | xsns_57 | TLS2591 | 0x29 | Light intensity sensor
41 | USE_DHT12 | xsns_58 | DHT12 | 0x5C | Temperature and humidity sensor
42 | USE_DS1624 | xsns_59 | DS1621 | 0x48 - 0x4F | Temperature sensor
42 | USE_DS1624 | xsns_59 | DS1624 | 0x48 - 0x4F | Temperature sensor
43 | USE_AHT1x | xsns_63 | AHT10/15 | 0x38 - 0x39 | Temperature and humidity sensor
43 | USE_AHT2x | xsns_63 | AHT20 | 0x38 | Temperature and humidity sensor
44 | USE_WEMOS_MOTOR_V1 | xdrv_34 | | 0x2D - 0x30 | WEMOS motor shield v1.0.0 (6612FNG)
45 | USE_HDC1080 | xsns_65 | HDC1080 | 0x40 | Temperature and Humidity sensor
46 | USE_IAQ | xsns_66 | IAQ | 0x5a | Air quality sensor
47 | USE_DISPLAY_SEVENSEG| xdsp_11 | HT16K33 | 0x70 - 0x77 | Seven segment LED
48 | USE_AS3935 | xsns_67 | AS3935 | 0x03 | Franklin Lightning Sensor
49 | USE_VEML6075 | xsns_70 | VEML6075 | 0x10 | UVA/UVB/UVINDEX Sensor
50 | USE_VEML7700 | xsns_71 | VEML7700 | 0x10 | Ambient light intensity sensor
51 | USE_MCP9808 | xsns_72 | MCP9808 | 0x18 - 0x1F | Temperature sensor
52 | USE_HP303B | xsns_73 | HP303B | 0x76 - 0x77 | Pressure and temperature sensor
53 | USE_MLX90640 | xdrv_43 | MLX90640 | 0x33 | IR array temperature sensor
54 | USE_VL53L1X | xsns_77 | VL53L1X | 0x29 | Time-of-flight (ToF) distance sensor
55 | USE_EZOPH | xsns_78 | EZOPH | 0x61 - 0x70 | pH sensor
55 | USE_EZOORP | xsns_78 | EZOORP | 0x61 - 0x70 | ORP sensor
55 | USE_EZORTD | xsns_78 | EZORTD | 0x61 - 0x70 | Temperature sensor
55 | USE_EZOHUM | xsns_78 | EZOHUM | 0x61 - 0x70 | Humidity sensor
55 | USE_EZOEC | xsns_78 | EZOEC | 0x61 - 0x70 | Electric conductivity sensor
55 | USE_EZOCO2 | xsns_78 | EZOCO2 | 0x61 - 0x70 | CO2 sensor
55 | USE_EZOO2 | xsns_78 | EZOO2 | 0x61 - 0x70 | O2 sensor
55 | USE_EZOPRS | xsns_78 | EZOPRS | 0x61 - 0x70 | Pressure sensor
55 | USE_EZOFLO | xsns_78 | EZOFLO | 0x61 - 0x70 | Flow meter sensor
55 | USE_EZODO | xsns_78 | EZODO | 0x61 - 0x70 | Disolved Oxygen sensor
55 | USE_EZORGB | xsns_78 | EZORGB | 0x61 - 0x70 | Color sensor
55 | USE_EZOPMP | xsns_78 | EZOPMP | 0x61 - 0x70 | Peristaltic Pump
56 | USE_SEESAW_SOIL | xsns_81 | SEESOIL | 0x36 - 0x39 | Adafruit seesaw soil moisture sensor
57 | USE_TOF10120 | xsns_84 | TOF10120 | 0x52 | Time-of-flight (ToF) distance sensor
58 | USE_MPU_ACCEL | xsns_85 | MPU_ACCEL| 0x68 | MPU6886/MPU9250 6-axis MotionTracking sensor from M5Stack
59 | USE_BM8563 | xdrv_56 | BM8563 | 0x51 | BM8563 RTC from M5Stack

4
lib/libesp32/LITTLEFS/src/LICENSE → LICENSE Executable file → Normal file
View File

@ -1,4 +1,6 @@
Copyright 2020 Brian Pugh
MIT License
Copyright (c) 2026 mgeppert
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,97 +0,0 @@
## Supported Modules
### ESP8266 based
The following ESP8266 based hardware modules are supported.
Module | LCode | Description
-------------------|-------|-----------------------
01 Sonoff Basic | | Sonoff Basic Wi-Fi Smart Switch
02 Sonoff RF | | Sonoff RF Wi-Fi Smart Switch with RF (434MHz) receiver
03 Sonoff SV | | Sonoff SV Safe Voltage Wi-Fi Smart Switch
04 Sonoff TH | | Sonoff TH10/TH16 Wi-Fi Smart Switch with Sensor connection
05 Sonoff Dual | x | Sonoff Dual Wi-Fi Smart Switch
06 Sonoff Pow | | Sonoff Pow Wi-Fi Smart Switch with Energy Monitoring
07 Sonoff 4CH | | Sonoff 4CH 4-gang Wi-Fi Smart Switch
08 Sonoff S2X | | Sonoff S20/S26 Wi-Fi Smart Socket
09 Slampher | | Sonoff Slampher Wi-Fi Smart Light Bulb Socket with RF (434MHz) receiver
10 Sonoff Touch | x | Sonoff Touch Wi-Fi Light Switch
11 Sonoff LED | x | Sonoff Led Wi-Fi Led Pack (Retired)
12 1 Channel | | 1 Channel Inching/Self Locking Wi-Fi Switch 5V/12V
13 4 Channel | x | 4 Channel Inching/Self Locking Wi-Fi Switch (Retired)
14 Motor C/AC | x | Motor Clockwise/Antoclockwise Wi-Fi Switch (Retired)
15 ElectroDragon | | Electrodragon Wi-Fi IoT Board
16 EXS Relay(s) | x | Electronic Experience Store 1 or 2-gang Wi-Fi Module
17 WiOn | | WiOn Wi-Fi Smart Socket
18 Generic | x | Any ESP8266/ESP8285 device like WeMos and NodeMCU
19 Sonoff Dev | | Sonoff Dev Wi-Fi Development Board
20 H801 | x | H801 Wi-Fi 5 Channel LED Controller
21 Sonoff SC | x | Sonoff SC Wi-Fi Environmental Monitor
22 Sonoff BN-SZ | x | Sonoff BN-SZ01 Wi-Fi Ceiling Led (Retired)
23 Sonoff 4CH Pro | x | Sonoff 4CH Pro 4-gang Wi-Fi Smart Switch
24 Huafan SS | | HuaFan Wi-Fi Smart Socket
25 Sonoff Bridge | x | Sonoff RF (434MHz) transceive to Wi-Fi Bridge
26 Sonoff B1 | x | Sonoff B1 Wi-Fi RGBWW Led Bulb
27 AiLight | x | Ai-Thinker RGBW Led Bulb
28 Sonoff T1 1CH | x | Sonoff T1 1-gang Wi-Fi Light Switch
29 Sonoff T1 2CH | x | Sonoff T1 2-gang Wi-Fi Light Switch
30 Sonoff T1 3CH | x | Sonoff T1 3-gang Wi-Fi Light Switch
31 Supla Espablo | | 2-gang Wi-Fi Module
32 Witty Cloud | | Witty Cloud ESP8266 Wi-Fi Development Board
33 Yunshan Relay | | ESP8266 Wi-Fi Network Relay Module
34 MagicHome | | MagicHome, Flux-light and some Arilux LC10 RGB(W) Led Controller
35 Luani HVIO | | Luani ESP8266 Wi-Fi I/O Module
36 KMC 70011 | | KMC Wi-Fi Smart Socket with Energy Monitoring
37 Arilux LC01 | | Arilux AL-LC01 RGB Led Controller
38 Arilux LC11 | | Arilux AL-LC11 RGBWW Led Controller
39 Sonoff Dual R2 | x | Sonoff Dual R2 Wi-Fi Smart Switch
40 Arilux LC06 | | Arilux AL-LC06 RGB(WW) Led Controller
41 Sonoff S31 | | Sonoff S31 Wi-Fi Smart Socket with Energy Monitoring
42 Zengge WF017 | | Zengge WF017 Wi-Fi RGB(W) Led Controller
43 Sonoff Pow R2 | | Sonoff Pow R2 Wi-Fi Smart Switch with Energy Monitoring
44 Sonoff iFan02 | x | Sonoff iFan02 Wi-Fi Smart Ceiling Fan with Light
45 BlitzWolf SHP | | BlitzWolf BW-SHP2, BW-SHP6, HomeCube SP1, Gosund SP111, Teckin SP22 Wi-Fi Smart Switch with Energy Monitoring
46 Shelly 1 | | Shelly 1 Open Source Wi-Fi Relay Module
47 Shelly 2 | | Shelly 2 Wi-Fi 2-gang Relay Module with Energy Monitoring
48 Xiaomi Philips | x | Xiaomi Philips Wi-Fi WW Led Bulb
49 Neo Coolcam | | Neo Coolcam Wi-Fi Smart Socket
50 ESP Switch | | ESP Switch 4-gang Wi-Fi Switch with Leds
51 OBI Socket | | OBI Wi-Fi Smart Socket
52 Teckin | | Teckin SP22 Wi-Fi Smart Switch with Energy Monitoring
53 AplicWDP303075 | | Aplic WDP 303075 CSL Wi-Fi Smart Switch with Energy Monitoring
54 TuyaMCU | x | Devices with an MCU using Tuya communication protocol for control
55 Gosund SP1 v23 | | Gosund SP1 v2.3 Wi-Fi Smart Switch with Energy Monitoring
56 ARMTR Dimmer | x | ARMtronix Wi-Fi dimmer for Incandescent Lights and Led
57 SK03 Outdoor | x | SK03 Outdoor Wi-Fi Smart Switch with Energy Monitoring
58 PS-16-DZ | x | PS-16-DZ Wi-Fi dimmer for Incandescent Lights and Led
59 Teckin US | | Teckin SP20 and ZooZee SA102 Wi-Fi Smart Switch with Energy Monitoring
60 Manzoku strip | | Manzoku Wi-Fi Smart Power Strip with four Relays
61 OBI Socket 2 | | OBI 2 Wi-Fi Smart Socket
62 YTF IR Bridge | x | YTF Universal IR Bridge
63 Digoo DG-SP202 | | Digoo DG-SP202 Dual Wi-Fi Smart Switch with Energy Monitoring
64 KA10 | | Smanergy KA10 Wi-Fi Smart Wall Switch with Energy Monitoring
65 Luminea ZX2820 | | Luminea ZX2820 Wi-Fi Smart Switch with Energy Monitoring
66 Mi Desk Lamp | | Mi Desk Lamp with rotary switch and Wi-Fi
67 SP10 | | Tuya SP10 Wi-Fi Smart Switch with Energy Monitoring
68 WAGA CHCZ02MB | | WAGA life CHCZ02MB Wi-Fi Smart Switch with Energy Monitoring
69 SYF05 | | Sunyesmart SYF05 RGBWW Wi-Fi Led Bulb
70 Sonoff L1 | x | Sonoff L1 light strip
71 Sonoff iFan03 | x | Sonoff iFan03 Wi-Fi Smart Ceiling Fan with Light
72 EXS Dimmer | x | EXS Wi-Fi Dimmer v4
73 PWM Dimmer | x | Martin Jerry/acenx/Tessan/NTONPOWER SD0x PWM Dimmer Switches
74 Sonoff D1 | x | Sonoff D1 Wi-Fi and RF Dimmer
75 Sonoff ZbBridge | x | Sonoff Zigbee bridge
### ESP32 based
The following ESP32 based hardware modules are supported.
Module | LCode | Description
-------------------|-------|-----------------------
01 ESP32-DevKit | x | Any ESP32 device
02 ESP32-Cam | x | ESP32 webcam
03 Odroid Go | x | Odroid Go
04 ESP32-Solo | x | ESP32-Solo
05 WT32-Eth01 | x | WT32-Eth01 ethernet
06 TTGO Watch | x | TTGO Watch
07 M5Stack Core2 | x | M5Stack Core2
Over 2000 additional devices are supported using [templates](TEMPLATES.md).

158
README.md
View File

@ -1,157 +1,3 @@
![Tasmota logo](/tools/logo/TASMOTA_FullLogo_Vector.svg)
# Tasmota
Alternative firmware for [ESP8266](https://en.wikipedia.org/wiki/ESP8266) and [ESP32](https://en.wikipedia.org/wiki/ESP32) based devices with **easy configuration using webUI, OTA updates, automation using timers or rules, expandability and entirely local control over MQTT, HTTP, Serial or KNX**.
_Written for PlatformIO with limited support for Arduino IDE._
[![GitHub version](https://img.shields.io/github/release/arendst/Tasmota.svg)](http://ota.tasmota.com/tasmota/release)
[![GitHub download](https://img.shields.io/github/downloads/arendst/Tasmota/total.svg)](https://github.com/arendst/Tasmota/releases/latest)
[![License](https://img.shields.io/github/license/arendst/Tasmota.svg)](LICENSE.txt)
[![Chat](https://img.shields.io/discord/479389167382691863.svg)](https://discord.gg/Ks2Kzd4)
[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/arendst/Tasmota)
If you like **Tasmota**, give it a star, or fork it and contribute!
[![GitHub stars](https://img.shields.io/github/stars/arendst/Tasmota.svg?style=social&label=Star)](https://github.com/arendst/Tasmota/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/arendst/Tasmota.svg?style=social&label=Fork)](https://github.com/arendst/Tasmota/network)
[![donate](https://img.shields.io/badge/donate-PayPal-blue.svg)](https://paypal.me/tasmota)
See [RELEASENOTES.md](https://github.com/arendst/Tasmota/blob/master/RELEASENOTES.md) for release information.
Firmware binaries can be downloaded from http://ota.tasmota.com/tasmota/release/ or http://ota.tasmota.com/tasmota32/release/ for ESP32 binaries.
## Development
[![Dev Version](https://img.shields.io/badge/development%20version-v9.5.x.x-blue.svg)](https://github.com/arendst/Tasmota)
[![Download Dev](https://img.shields.io/badge/download-development-yellow.svg)](http://ota.tasmota.com/tasmota/)
[![Tasmota CI](https://github.com/arendst/Tasmota/workflows/Tasmota%20CI/badge.svg)](https://github.com/arendst/Tasmota/actions?query=workflow%3A%22Tasmota+CI%22)
[![Tasmota ESP32 CI](https://github.com/arendst/Tasmota/workflows/Tasmota%20ESP32%20CI/badge.svg)](https://github.com/arendst/Tasmota/actions?query=workflow%3A%22Tasmota+ESP32+CI%22)
[![Build_firmware](https://github.com/arendst/Tasmota/workflows/Build_firmware/badge.svg)](https://github.com/arendst/Tasmota/actions?query=workflow%3ABuild_firmware)
See [CHANGELOG.md](CHANGELOG.md) for detailed change information.
Unless your Tasmota powered device exhibits a problem or you need to make use of a feature that is not available in the Tasmota version currently installed on your device, leave your device alone - it works so don't make unnecessary changes! If the release version (i.e., the master branch) exhibits unexpected behaviour for your device and configuration, you should upgrade to the latest development version instead to see if your problem is resolved as some bugs in previous releases or development builds may already have been resolved.
Every commit made to the development branch, which is compiling successfuly, will post new binary files at http://ota.tasmota.com/tasmota/ (this web address can be used for OTA updates too). It is important to note that these binaries are based on the current development codebase. These commits are tested as much as is possible and are typically quite stable. However, it is infeasible to test on the hundreds of different types of devices with all the available configuration options permitted.
Note that there is a chance, as with any upgrade, that the device may not function as expected. You must always account for the possibility that you may need to flash the device via the serial programming interface if the OTA upgrade fails. Even with the master release, you should always attempt to test the device or a similar prototype before upgrading a device which is in production or is hard to reach. And, as always, make a backup of the device configuration before beginning any firmware update.
## Disclaimer
:warning: **DANGER OF ELECTROCUTION** :warning:
If your device connects to mains electricity (AC power) there is danger of electrocution if not installed properly. If you don't know how to install it, please call an electrician (***Beware:*** certain countries prohibit installation without a licensed electrician present). Remember: _**SAFETY FIRST**_. It is not worth the risk to yourself, your family and your home if you don't know exactly what you are doing. Never tinker or try to flash a device using the serial programming interface while it is connected to MAINS ELECTRICITY (AC power).
We don't take any responsibility nor liability for using this software nor for the installation or any tips, advice, videos, etc. given by any member of this site or any related site.
## Note
Please do not ask to add new devices unless it requires additional code for new features. If the device is not listed as a module, try using [Templates](https://tasmota.github.io/docs/Templates) first. If it is not listed in the [Tasmota Device Templates Repository](http://templates.blakadder.com) create your own [Template](https://tasmota.github.io/docs/Templates#creating-your-template).
## Quick Install
Download one of the released binaries from http://ota.tasmota.com/tasmota/release/ or http://ota.tasmota.com/tasmota32/release/ and flash it to your hardware [using our installation guide](https://tasmota.github.io/docs/Getting-Started).
## Important User Compilation Information
If you want to compile Tasmota yourself keep in mind the following:
- For ESP8285 based devices only Flash Mode **DOUT** is supported. Do not use Flash Mode DIO / QIO / QOUT as it might seem to brick your device.
- For ESP8285 based devices Tasmota uses a 1M linker script WITHOUT spiffs **1M (no SPIFFS)** for optimal code space.
- To make compile time changes to Tasmota use the `user_config_override.h` file. It assures keeping your custom settings when you download and compile a new version. You have to make a copy from the provided `user_config_override_sample.h` file and add your setting overrides.
## Configuration Information
Please refer to the installation and configuration articles in our [documentation](https://tasmota.github.io/docs).
## Migration Information
See [wiki migration path](https://tasmota.github.io/docs/Upgrading#migration-path) for instructions how to migrate to a major version. Pay attention to the following version breaks due to dynamic settings updates:
1. Migrate to **Sonoff-Tasmota 3.9.x**
2. Migrate to **Sonoff-Tasmota 4.x**
3. Migrate to **Sonoff-Tasmota 5.14**
4. Migrate to **Sonoff-Tasmota 6.7.1** (http://ota.tasmota.com/tasmota/release-6.7.1/)
5. Migrate to **Tasmota 7.2.0** (http://ota.tasmota.com/tasmota/release-7.2.0/)
--- Major change in parameter storage layout ---
6. Migrate to **Tasmota 8.5.1** (http://ota.tasmota.com/tasmota/release-8.5.1/)
--- Major change in internal GPIO function representation ---
7. Migrate to **Tasmota 9.1** (http://ota.tasmota.com/tasmota/release-9.1.0/)
While fallback or downgrading is common practice it was never supported due to Settings additions or changes in newer releases. Starting with version **v9.0.0.1** the internal GPIO function representation has changed in such a way that fallback is only possible to the latest GPIO configuration before installing **v9.0.0.1**.
## Support Information
<img src="https://user-images.githubusercontent.com/5904370/68332933-e6e5a600-00d7-11ea-885d-50395f7239a1.png" width=150 align="right" />
For a database of supported devices see [Tasmota Device Templates Repository](https://templates.blakadder.com)
If you're looking for support on **Tasmota** there are some options available:
### Documentation
* [Documentation Site](https://tasmota.github.io/docs): For information on how to flash Tasmota, configure, use and expand it
* [FAQ and Troubleshooting](https://tasmota.github.io/docs/FAQ/): For information on common problems and solutions.
* [Commands Information](https://tasmota.github.io/docs/Commands): For information on all the commands supported by Tasmota.
### Support's Community
* [Tasmota Discussions](https://github.com/arendst/Tasmota/discussions): For Tasmota usage questions, Feature Requests and Projects.
* [Tasmota Users Chat](https://discord.gg/Ks2Kzd4): For support, troubleshooting and general questions. You have better chances to get fast answers from members of the Tasmota Community.
* [Search in Issues](https://github.com/arendst/Tasmota/issues): You might find an answer to your question by searching current or closed issues.
* [Software Problem Report](https://github.com/arendst/Tasmota/issues/new?template=Bug_report.md): For reporting problems of Tasmota Software.
## Contribute
You can contribute to Tasmota by
- Providing Pull Requests (Features, Proof of Concepts, Language files or Fixes)
- Testing new released features and report issues
- Donating to acquire hardware for testing and implementing or out of gratitude
- Contributing missing [documentation](https://tasmota.github.io/docs) for features and devices
[![donate](https://img.shields.io/badge/donate-PayPal-blue.svg)](https://paypal.me/tasmota)
## Credits
People helping to keep the show on the road:
- David Lang providing initial issue resolution and code optimizations
- Heiko Krupp for his IRSend, HTU21, SI70xx and Wemo/Hue emulation drivers
- Wiktor Schmidt for Travis CI implementation
- Thom Dietrich for PlatformIO optimizations
- Marinus van den Broek for his EspEasy groundwork
- Pete Ba for more user friendly energy monitor calibration
- Lobradov providing compile optimization tips
- Flexiti for his initial timer implementation
- reloxx13 for his [TasmoAdmin](https://github.com/reloxx13/TasmoAdmin) management tool
- Joachim Banzhaf for his TSL2561 library and driver
- Andre Thomas for providing many drivers
- Gijs Noorlander for his MHZ19, SenseAir and updated PubSubClient drivers
- Erik Montnemery for his HomeAssistant Discovery concept and many code tuning tips
- Federico Leoni for continued HomeAssistant Discovery support
- Aidan Mountford for his HSB support
- Daniel Ztolnai for his Serial Bridge implementation
- Gerhard Mutz for multiple sensor & display drivers, Sunrise/Sunset, and scripting
- Nuno Ferreira for his HC-SR04 driver
- Adrian Scillato for his (security)fixes and implementing and maintaining KNX
- Gennaro Tortone for implementing and maintaining Eastron drivers
- Raymond Mouthaan for managing Wemos Wiki information
- Norbert Richter for his [decode-config.py](https://github.com/tasmota/decode-config) tool
- Joel Stein, digiblur and Shantur Rathore for their Tuya research and driver
- Frogmore42 for providing many issue answers
- Jason2866 for platformio support and providing many issue answers
- Blakadder for managing the new document site and providing template management
- Stephan Hadinger for refactoring light driver, enhancing HueEmulation, LVGL, Zigbee and Berry support
- tmo for designing the official Tasmota logo
- Stefan Bode for his Shutter and Deep sleep drivers
- Jacek Ziółkowski for his [TDM](https://github.com/jziolkowski/tdm) management tool and [Tasmotizer](https://github.com/tasmota/tasmotizer) flashing tool
- Christian Staars for NRF24L01 and HM-10 Bluetooth sensor support
- Paul Diem for UDP Group communication support
- Jörg Schüler-Maroldt for his initial ESP32 port
- Javier Arigita for his thermostat driver
- Simon Hailes for ESP32 Bluetooth extensions
- Many more providing Tips, Wips, Pocs, PRs and Donations
## License
This program is licensed under GPL-3.0
Local copy of the https://github.com/arendst/Tasmota#

View File

@ -1,164 +0,0 @@
<img src="https://github.com/arendst/Tasmota/blob/master/tools/logo/TASMOTA_FullLogo_Vector.svg" alt="Logo" align="right" height="76"/>
# RELEASE NOTES
## Migration Information
**This version removes support for direct migration from versions before v8.1.0 (Doris)**
See [migration path](https://tasmota.github.io/docs/Upgrading#migration-path) for instructions how to migrate to a major version. Pay attention to the following version breaks due to dynamic settings updates:
1. Migrate to **Sonoff-Tasmota 3.9.x**
2. Migrate to **Sonoff-Tasmota 4.x**
3. Migrate to **Sonoff-Tasmota 5.14**
4. Migrate to **Sonoff-Tasmota 6.7.1** (http://ota.tasmota.com/tasmota/release-6.7.1/)
5. Migrate to **Tasmota 7.2.0** (http://ota.tasmota.com/tasmota/release-7.2.0/)
--- Major change in parameter storage layout ---
6. Migrate to **Tasmota 8.5.1** (http://ota.tasmota.com/tasmota/release-8.5.1/)
--- Major change in internal GPIO function representation ---
7. Migrate to **Tasmota 9.1** (http://ota.tasmota.com/tasmota/release-9.1.0/)
While fallback or downgrading is common practice it was never supported due to Settings additions or changes in newer releases. Starting with release **v9.1.0 Imogen** the internal GPIO function representation has changed in such a way that fallback is only possible to the latest GPIO configuration before installing **v9.1.0**.
## Supported Core versions
This release will be supported from ESP8266/Arduino library Core version **2.7.4.9** due to reported security and stability issues on previous Core version. This will also support gzipped binaries.
Support of Core versions before 2.7.1 has been removed.
## Support of TLS
In addition to TLS using fingerprints now also user supplied CA certs, AWS IoT and Azure IoT is supported. Read [full documentation](https://tasmota.github.io/docs/AWS-IoT)
## Initial configuration tools
For initial configuration this release supports Webserver based **WifiManager** or **Serial** based command interface only. Support for **WPS** and **SmartConfig** has been removed.
## Provided Binary Downloads
### ESP8266 or ESP8285 based
The following binary downloads have been compiled with ESP8266/Arduino library core version **2.7.4.9**.
- **tasmota.bin** = The Tasmota version with most drivers for 1M+ flash. **RECOMMENDED RELEASE BINARY**
- **tasmota-AF.bin** to **tasmota-VN.bin** = The Tasmota version in different languages for 1M+ flash.
- **tasmota-lite.bin** = The Lite version without most drivers and sensors for 1M+ flash.
- **tasmota-knx.bin** = The Knx version without some features but adds KNX support for 1M+ flash.
- **tasmota-sensors.bin** = The Sensors version adds more useful sensors for 1M+ flash.
- **tasmota-ir.bin** = The InfraRed Receiver and transmitter version allowing all available protocols provided by library IRremoteESP8266 but without most other features for 1M+ flash.
- **tasmota-display.bin** = The Display version without Energy Monitoring but adds display support for 1M+ flash.
- **tasmota-zbbridge.bin** = The dedicated Sonoff Zigbee Bridge version for 2M+ flash.
- **tasmota-zigbee.bin** = The dedicated cc25xx Zigbee Bridge version for 4M+ flash.
- **tasmota-minimal.bin** = The Minimal version allows intermediate OTA uploads to support larger versions and does NOT change any persistent parameter for 1M+ flash. This version **should NOT be used for initial installation**.
Above binaries are also available as gzipped version allowing faster uploads.
Latest released binaries can be downloaded from
- https://github.com/arendst/Tasmota/tree/release-firmware
- http://ota.tasmota.com/tasmota/release
Historical binaries can be downloaded from
- http://ota.tasmota.com/tasmota/release-9.5.0
The latter links can be used for OTA upgrades too like ``OtaUrl http://ota.tasmota.com/tasmota/release/tasmota.bin.gz``
### ESP32 based
The following binary downloads have been compiled with ESP32/Arduino library core version **1.0.6**.
- **tasmota32.bin** = The Tasmota version with most drivers including additional sensors and KNX for 4M+ flash. **RECOMMENDED RELEASE BINARY**
- **tasmota32_8M.bin** = The Tasmota version with most drivers including additional sensors and KNX for 8M+ flash.
- **tasmota32_16M.bin** = The Tasmota version with most drivers including additional sensors and KNX for 16M+ flash.
- **tasmota32solo1.bin** = The Tasmota version with most drivers including additional sensors and KNX for single core ESP32 and 4M+ flash.
- **tasmota32-AF.bin** to **tasmota32-VN.bin** = The Tasmota version in different languages for 4M+ flash.
- **tasmota32-ir.bin** = The InfraRed Receiver and transmitter version allowing all available protocols provided by library IRremoteESP8266 but without most other features for 4M+ flash.
- **tasmota32-display.bin** = The Display version without Energy Monitoring but adds display support for 4M+ flash.
- **tasmota32-webcam.bin** = The Webcam version adds webcam support for 4M+ flash.
- **tasmota32-bluetooth.bin** = The Bluetooth version adds BLE support for 4M+ flash.
- **tasmota32-odroidgo.bin** = The Odroid-Go version is specifically tailored to Odroid_go hardware for 8M+ flash.
- **tasmota32-core2.bin** = The Core2 version is specifically tailored to M5Stack Core2 hardware for 8M+ flash.
Latest released binaries can be downloaded from
- https://github.com/arendst/Tasmota/tree/release-firmware
- http://ota.tasmota.com/tasmota32/release
Historical binaries can be downloaded from
- http://ota.tasmota.com/tasmota32/release-9.5.0
The latter links can be used for OTA upgrades too like ``OtaUrl http://ota.tasmota.com/tasmota32/release/tasmota32.bin``
## Additional information
[List](MODULES.md) of embedded modules.
[Complete list](BUILDS.md) of available feature and sensors.
## Changelog v9.5.0 Michael (Rossi)
### Added
- Command ``Status0`` providing all status information on a single line
- Command ``TuyaSend5`` for hex string [#12211](https://github.com/arendst/Tasmota/issues/12211)
- Command ``MqttWifiTimeout 100..20000`` to control MQTT Wi-Fi connection timeout default set to 200 mS [#12222](https://github.com/arendst/Tasmota/issues/12222)
- Commands ``Color2`` and ``Dimmer4`` to allow retaining brightness ratio between white and color channels when setting dimmer for linked lights [#12072](https://github.com/arendst/Tasmota/issues/12072)
- Extend command ``Wifi`` with Wi-Fi Mode Control [#12292](https://github.com/arendst/Tasmota/issues/12292)
- Defines ``USER_RULE1``, ``USER_RULE2`` and ``USER_RULE3`` to store rules at compile time
- Define ``USER_BACKLOG`` to store commands at compile time to be executed at firmware load or when executing command ``reset``
- Support for optional ``Template`` JSON fieldpair ``"CMND":"<any template related command>|<any template related command>|..."`` [#11788](https://github.com/arendst/Tasmota/issues/11788)
- ESP32 pulldown buttons ``Button_d`` and ``Button_id`` and switches ``Switch_d`` [#10814](https://github.com/arendst/Tasmota/issues/10814)
- Support for MQTT using Azure IoT Hub by Kevin Saye [#11906](https://github.com/arendst/Tasmota/issues/11906)
- Make Telegram command ``TmState`` persistent [#11965](https://github.com/arendst/Tasmota/issues/11965)
- Zigbee binary supporting cc25xx hardware on ESP8266 4M flash hardware [#11872](https://github.com/arendst/Tasmota/issues/11872)
- Zigbee firmware for Tube's Zigbee coordinator based on EFR32 and ESP32
- Zigbee firmware 6.7.9 for Sonoff ZBBridge
- LVGL support for 3 buttons as rotary encoder [#12035](https://github.com/arendst/Tasmota/issues/12035)
- LVGL support for touchscreen [#12039](https://github.com/arendst/Tasmota/issues/12039)
- LVGL support for PSRAM [#12062](https://github.com/arendst/Tasmota/issues/12062)
- LVGL support for TrueType fonts via FreeType library [#12087](https://github.com/arendst/Tasmota/issues/12087)
- LVGL support for PNG images [#12148](https://github.com/arendst/Tasmota/issues/12148)
- Allow Home Assistant discovery of MCP2300xx output as relay [#12037](https://github.com/arendst/Tasmota/issues/12037)
- Preliminary support for Esp32C3 - RiscV based
- Support for voltage and current monitoring when using Shelly dimmer 2 hardware [#11988](https://github.com/arendst/Tasmota/issues/11988)
- Support for Azure Device Provisioning Service for IoT Hub [#12056](https://github.com/arendst/Tasmota/issues/12056)
- Show new IP after the Wi-Fi Initial Config [#12091](https://github.com/arendst/Tasmota/issues/12091)
- Update Sugar Valley Neopool driver [#12171](https://github.com/arendst/Tasmota/issues/12171)
- Acer projector support [#12190](https://github.com/arendst/Tasmota/issues/12190)
- I2S and Interrupt GPIO types [#12192](https://github.com/arendst/Tasmota/issues/12192)
- Update OpenTherm driver [#12195](https://github.com/arendst/Tasmota/issues/12195)
- Support for BM8563 RTC chip (I2C) found in M5Stack Core2 and M5StickC [#12199](https://github.com/arendst/Tasmota/issues/12199)
### Changed
- IRremoteESP8266 library from v2.7.16 to v2.7.18
- NeoPixelBus library from v2.6.1.4 to v2.6.3 stage
- Shelly Dimmer 1 and 2 stm32 firmware from v51.5 to v51.6
- Allow longer MQTT response messages by removing fixed memory buffer with size 1040 to heap allocated buffer
- Command ``Timers`` layout of JSON message changed to single line
- Command ``Gpio`` layout of JSON message changed to single line
- Command ``Modules`` layout of JSON message changed to single line
- ESP32 increase log buffer from 4k to 6k to support longer messages
- Move Settings from DRAM to heap
- Refactor platformio configurations by Jason2866
- WifiManager save Wi-Fi configuration from settings, do it only once [#12242](https://github.com/arendst/Tasmota/issues/12242)
- Improving SI7021 reading reliability by adjusting timers [#12256](https://github.com/arendst/Tasmota/issues/12256)
- Refactor ESP32 partition selection, now via boards [#12257](https://github.com/arendst/Tasmota/issues/12257)
- Use correct template for Home Assistant light [#12317](https://github.com/arendst/Tasmota/issues/12317)
### Fixed
- Wrong flash size detection when saving Zigbee device information on ESP8266 [#11870](https://github.com/arendst/Tasmota/issues/11870)
- Prometheus metrics parse error on DS18x20 [#11931](https://github.com/arendst/Tasmota/issues/11931)
- DS18x20 name search id [#11958](https://github.com/arendst/Tasmota/issues/11958)
- Avoid erasing of Zigbee data if zigbee is not started [#11961](https://github.com/arendst/Tasmota/issues/11961)
- Zigbee XModem retries [#11967](https://github.com/arendst/Tasmota/issues/11967)
- Teleinfo standard mode and blacklist feature crash [#11991](https://github.com/arendst/Tasmota/issues/11991)
- ESP32 Hue light [#12005](https://github.com/arendst/Tasmota/issues/12005)
- Map received CCT channels back in DevGroups [#12044](https://github.com/arendst/Tasmota/issues/12044)
- Increase TLS minimum stack thunk to 3800 bytes [#12063](https://github.com/arendst/Tasmota/issues/12063)
- Delay discovery of PZEM sensors [#12076](https://github.com/arendst/Tasmota/issues/12076)
- PING race condition breaks JSON in rule [#12106](https://github.com/arendst/Tasmota/issues/12106)
- Support Tuya powermeter >6500W [#12115](https://github.com/arendst/Tasmota/issues/12115)
- Zigbee max end-device [#12159](https://github.com/arendst/Tasmota/issues/12159)
- Prevent keep state MCP230xx output fast toggle on reboot [#12264](https://github.com/arendst/Tasmota/issues/12264)
- Tuya data type 2 read as 32 bit integer (instead of 16 bit) [#12282](https://github.com/arendst/Tasmota/issues/12282)
### Noted
- ESP32 single core **tasmota32solo1.bin** binary can only be uploaded using the GUI as OTA upload will trigger the watchdog timer

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,49 +0,0 @@
<?php
// mkdir and chmod arduino folder to 777
//
//var_dump($_FILES);
/**
* GZIPs a file on disk (appending .gz to the name)
*
* From http://stackoverflow.com/questions/6073397/how-do-you-create-a-gz-file-using-php
* Based on function by Kioob at:
* http://www.php.net/manual/en/function.gzwrite.php#34955
*
* @param string $source Path to file that should be compressed
* @param integer $level GZIP compression level (default: 9)
* @return string New filename (with .gz appended) if success, or false if operation fails
*/
function gzCompressFile($source, $level = 9){
$dest = $source . '.gz';
$mode = 'wb' . $level;
$error = false;
if ($fp_out = gzopen($dest, $mode)) {
if ($fp_in = fopen($source,'rb')) {
while (!feof($fp_in))
gzwrite($fp_out, fread($fp_in, 1024 * 512));
fclose($fp_in);
} else {
$error = true;
}
gzclose($fp_out);
} else {
$error = true;
}
if ($error)
return false;
else
return $dest;
}
$image = basename($_FILES["file"]["name"]);
$target_file = "arduino/".$image;
$hostname = $_SERVER['SERVER_NAME'];
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
gzCompressFile($target_file);
echo "The files $image and $image.gz have been uploaded to OTA server $hostname. \n";
} else {
echo "Sorry, there was an error uploading your file $image to OTA server $hostname. \n";
}
?>

View File

@ -1,38 +0,0 @@
{
"build": {
"arduino":{
"ldscript": "esp32_out.ld"
},
"core": "esp32",
"extra_flags": "-DARDUINO_ESP32_DEV -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue",
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "dio",
"mcu": "esp32",
"variant": "esp32",
"partitions": "esp32_partition_app1856k_spiffs320k.csv"
},
"connectivity": [
"wifi",
"bluetooth",
"ethernet",
"can"
],
"debug": {
"openocd_board": "esp-wroom-32.cfg"
},
"frameworks": [
"arduino",
"espidf"
],
"name": "AI Thinker ESP32-CAM, 4M Flash 4MB PSRAM, Tasmota 1856k Code/OTA, 320k SPIFFS",
"upload": {
"flash_size": "4MB",
"maximum_ram_size": 327680,
"maximum_size": 4194304,
"require_upload_port": true,
"speed": 460800
},
"url": "https://wiki.ai-thinker.com/esp32-cam",
"vendor": "AI Thinker"
}

View File

@ -1,35 +0,0 @@
{
"build": {
"arduino":{
"ldscript": "esp32_out.ld"
},
"core": "esp32",
"extra_flags": "-DARDUINO_M5STACK_Core2 -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue",
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "dio",
"mcu": "esp32",
"variant": "m5stack_core2",
"partitions": "esp32_partition_app2944k_spiffs10M.csv"
},
"connectivity": [
"wifi",
"bluetooth",
"ethernet",
"can"
],
"frameworks": [
"arduino",
"espidf"
],
"name": "M5Stack Core2 16M Flash, 4MB PSRAM, Tasmota 2944k Code/OTA, 10M SPIFFS",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 327680,
"maximum_size": 16777216,
"require_upload_port": true,
"speed": 2000000
},
"url": "http://www.m5stack.com",
"vendor": "M5Stack"
}

View File

@ -1,35 +0,0 @@
{
"build": {
"arduino":{
"ldscript": "esp32_out.ld"
},
"core": "esp32",
"extra_flags": "-DARDUINO_ODROID_ESP32 -DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue",
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "dio",
"mcu": "esp32",
"variant": "odroid_esp32",
"partitions": "esp32_partition_app2944k_spiffs10M.csv"
},
"connectivity": [
"wifi",
"bluetooth",
"ethernet",
"can"
],
"frameworks": [
"arduino",
"espidf"
],
"name": "ESP32 ODROID-GO 16M Flash, 4MB PSRAM, Tasmota 2944k Code/OTA, 10M SPIFFS",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 327680,
"maximum_size": 16777216,
"require_upload_port": true,
"speed": 2000000
},
"url": "https://www.hardkernel.com/main/products/prdt_info.php?g_code=G152875062626",
"vendor": "Hardkernel"
}

View File

@ -1,38 +0,0 @@
{
"build": {
"arduino":{
"ldscript": "esp32_out.ld"
},
"core": "esp32",
"extra_flags": "-DARDUINO_ESP32_DEV",
"f_cpu": "80000000L",
"f_flash": "40000000L",
"flash_mode": "dio",
"mcu": "esp32",
"variant": "esp32",
"partitions": "esp32_partition_app2944k_spiffs10M.csv"
},
"connectivity": [
"wifi",
"bluetooth",
"ethernet",
"can"
],
"debug": {
"openocd_board": "esp-wroom-32.cfg"
},
"frameworks": [
"arduino",
"espidf"
],
"name": "Espressif Generic ESP32 16M Flash, Tasmota 2944k Code/OTA, 10M SPIFFS",
"upload": {
"flash_size": "16MB",
"maximum_ram_size": 327680,
"maximum_size": 16777216,
"require_upload_port": true,
"speed": 460800
},
"url": "https://en.wikipedia.org/wiki/ESP32",
"vendor": "Espressif"
}

View File

@ -1,38 +0,0 @@
{
"build": {
"arduino":{
"ldscript": "esp32_out.ld"
},
"core": "esp32",
"extra_flags": "-DARDUINO_ESP32_DEV",
"f_cpu": "80000000L",
"f_flash": "40000000L",
"flash_mode": "dio",
"mcu": "esp32",
"variant": "esp32",
"partitions": "esp32_partition_app1856k_spiffs320k.csv"
},
"connectivity": [
"wifi",
"bluetooth",
"ethernet",
"can"
],
"debug": {
"openocd_board": "esp-wroom-32.cfg"
},
"frameworks": [
"arduino",
"espidf"
],
"name": "Espressif Generic ESP32 4M Flash, Tasmota 1856k Code/OTA, 320k SPIFFS",
"upload": {
"flash_size": "4MB",
"maximum_ram_size": 327680,
"maximum_size": 4194304,
"require_upload_port": true,
"speed": 460800
},
"url": "https://en.wikipedia.org/wiki/ESP32",
"vendor": "Espressif"
}

View File

@ -1,38 +0,0 @@
{
"build": {
"arduino":{
"ldscript": "esp32_out.ld"
},
"core": "esp32",
"extra_flags": "-DARDUINO_ESP32_DEV",
"f_cpu": "80000000L",
"f_flash": "40000000L",
"flash_mode": "dio",
"mcu": "esp32",
"variant": "esp32",
"partitions": "esp32_partition_app2944k_spiffs2M.csv"
},
"connectivity": [
"wifi",
"bluetooth",
"ethernet",
"can"
],
"debug": {
"openocd_board": "esp-wroom-32.cfg"
},
"frameworks": [
"arduino",
"espidf"
],
"name": "Espressif Generic ESP32 8M Flash, Tasmota 2944k Code/OTA, 2112k SPIFFS",
"upload": {
"flash_size": "8MB",
"maximum_ram_size": 327680,
"maximum_size": 8388608,
"require_upload_port": true,
"speed": 460800
},
"url": "https://en.wikipedia.org/wiki/ESP32",
"vendor": "Espressif"
}

View File

@ -1,30 +0,0 @@
{
"build": {
"arduino":{
"ldscript": "esp32c3_out.ld"
},
"core": "esp32",
"f_cpu": "160000000L",
"f_flash": "80000000L",
"flash_mode": "dio",
"mcu": "esp32c3",
"variant": "esp32c3",
"partitions": "esp32_partition_app1856k_spiffs320k.csv"
},
"connectivity": [
"wifi"
],
"frameworks": [
"arduino"
],
"name": "Espressif Generic ESP32-C3 4M Flash, Tasmota 1856k Code/OTA, 320k SPIFFS",
"upload": {
"flash_size": "4MB",
"maximum_ram_size": 327680,
"maximum_size": 4194304,
"require_upload_port": true,
"speed": 460800
},
"url": "https://docs.espressif.com/projects/esp-idf/en/latest",
"vendor": "Espressif"
}

View File

@ -1,34 +0,0 @@
{
"build": {
"arduino":{
"ldscript": "esp32s2_out.ld"
},
"core": "esp32",
"f_cpu": "240000000L",
"f_flash": "80000000L",
"flash_mode": "dio",
"mcu": "esp32s2",
"variant": "esp32s2",
"partitions": "esp32_partition_app1856k_spiffs320k.csv"
},
"connectivity": [
"wifi"
],
"debug": {
"openocd_target": "esp32s2.cfg"
},
"frameworks": [
"espidf",
"arduino"
],
"name": "Espressif Generic ESP32-S2 4M Flash, Tasmota 1856k Code/OTA, 320k SPIFFS",
"upload": {
"flash_size": "4MB",
"maximum_ram_size": 327680,
"maximum_size": 4194304,
"require_upload_port": true,
"speed": 460800
},
"url": "https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/hw-reference/esp32s2/user-guide-saola-1-v1.2.html",
"vendor": "Espressif"
}

View File

@ -1,32 +0,0 @@
{
"build": {
"arduino": {
"ldscript": "eagle.flash.1m.ld"
},
"core": "esp8266",
"extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP01",
"f_cpu": "80000000L",
"f_flash": "40000000L",
"flash_mode": "dout",
"mcu": "esp8266",
"variant": "generic"
},
"connectivity": [
"wifi"
],
"frameworks": [
"arduino",
"esp8266-rtos-sdk",
"esp8266-nonos-sdk"
],
"name": "Espressif Generic ESP8266 Tasmota 1M sketch NO SPIFFS",
"upload": {
"maximum_ram_size": 81920,
"maximum_size": 995326,
"require_upload_port": true,
"resetmethod": "ck",
"speed": 115200
},
"url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
"vendor": "Espressif"
}

View File

@ -1,32 +0,0 @@
{
"build": {
"arduino": {
"ldscript": "eagle.flash.2m1m.ld"
},
"core": "esp8266",
"extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP01",
"f_cpu": "80000000L",
"f_flash": "40000000L",
"flash_mode": "dout",
"mcu": "esp8266",
"variant": "generic"
},
"connectivity": [
"wifi"
],
"frameworks": [
"arduino",
"esp8266-rtos-sdk",
"esp8266-nonos-sdk"
],
"name": "Espressif Generic ESP8266 Tasmota 1M sketch 1M SPIFFS",
"upload": {
"maximum_ram_size": 81920,
"maximum_size": 995326,
"require_upload_port": true,
"resetmethod": "ck",
"speed": 115200
},
"url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
"vendor": "Espressif"
}

View File

@ -1,32 +0,0 @@
{
"build": {
"arduino": {
"ldscript": "eagle.flash.2m256.ld"
},
"core": "esp8266",
"extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP01",
"f_cpu": "80000000L",
"f_flash": "40000000L",
"flash_mode": "dout",
"mcu": "esp8266",
"variant": "generic"
},
"connectivity": [
"wifi"
],
"frameworks": [
"arduino",
"esp8266-rtos-sdk",
"esp8266-nonos-sdk"
],
"name": "Espressif Generic ESP8266 Tasmota 1M sketch 772k OTA 256k SPIFFS",
"upload": {
"maximum_ram_size": 81920,
"maximum_size": 995326,
"require_upload_port": true,
"resetmethod": "ck",
"speed": 115200
},
"url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
"vendor": "Espressif"
}

View File

@ -1,32 +0,0 @@
{
"build": {
"arduino": {
"ldscript": "eagle.flash.4m2m.ld"
},
"core": "esp8266",
"extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP01",
"f_cpu": "80000000L",
"f_flash": "40000000L",
"flash_mode": "dout",
"mcu": "esp8266",
"variant": "generic"
},
"connectivity": [
"wifi"
],
"frameworks": [
"arduino",
"esp8266-rtos-sdk",
"esp8266-nonos-sdk"
],
"name": "Espressif Generic ESP8266 Tasmota 1M sketch 1M OTA 2M SPIFFS",
"upload": {
"maximum_ram_size": 81920,
"maximum_size": 995326,
"require_upload_port": true,
"resetmethod": "ck",
"speed": 115200
},
"url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
"vendor": "Espressif"
}

View File

@ -1,32 +0,0 @@
{
"build": {
"arduino": {
"ldscript": "eagle.flash.4m3m.ld"
},
"core": "esp8266",
"extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP01",
"f_cpu": "80000000L",
"f_flash": "40000000L",
"flash_mode": "dout",
"mcu": "esp8266",
"variant": "generic"
},
"connectivity": [
"wifi"
],
"frameworks": [
"arduino",
"esp8266-rtos-sdk",
"esp8266-nonos-sdk"
],
"name": "Espressif Generic ESP8266 Tasmota 1M sketch 3M SPIFFS",
"upload": {
"maximum_ram_size": 81920,
"maximum_size": 995326,
"require_upload_port": true,
"resetmethod": "ck",
"speed": 115200
},
"url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
"vendor": "Espressif"
}

View File

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

View File

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

View File

@ -1,6 +0,0 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x2F0000,
app1, app, ota_1, 0x300000, 0x2F0000,
spiffs, data, spiffs, 0x5F0000,0xA10000,
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 0x2F0000
5 app1 app ota_1 0x300000 0x2F0000
6 spiffs data spiffs 0x5F0000 0xA10000

View File

@ -1,6 +0,0 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x2F0000,
app1, app, ota_1, 0x300000, 0x2F0000,
spiffs, data, spiffs, 0x5F0000,0x210000,
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 0x2F0000
5 app1 app ota_1 0x300000 0x2F0000
6 spiffs data spiffs 0x5F0000 0x210000

View File

@ -1,54 +0,0 @@
/*
esp32x_fixes.h - fix esp32x toolchain
Copyright (C) 2021 Theo Arends
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/>.
*/
/*
* Xtensa toolchain declares `int32_t` as `int` but RISC-V toolchain
* declares `int32_t` as `long int` which causes compilation errors.
*
* See:
* https://github.com/espressif/esp-idf/issues/6906
* https://github.com/espressif/arduino-esp32/issues/5086
*
* You need to add the following lines in `build_flags`:
* -I$PROJECT_DIR/include
* -include "esp32x_fixes.h"
*/
#ifdef __riscv
#undef __INT32_TYPE__
#define __INT32_TYPE__ int
#undef __UINT32_TYPE__
#define __UINT32_TYPE__ unsigned int
#endif // __riscv
// fix a bug in esp-idf 4.4 for esp32c3
#ifndef REG_SPI_BASE
#define REG_SPI_BASE(i) (DR_REG_SPI1_BASE + (((i)>1) ? (((i)* 0x1000) + 0x20000) : (((~(i)) & 1)* 0x1000 )))
#endif
#if CONFIG_IDF_TARGET_ESP32C3
// SPI_MOSI_DLEN_REG is not defined anymore in esp32c3, instead use SPI_MS_DLEN_REG
#define SPI_MOSI_DLEN_REG(x) SPI_MS_DLEN_REG(x)
//alias for different chips, deprecated for the chips after esp32s2
#define SPI_HOST SPI1_HOST
#define HSPI_HOST SPI2_HOST
#define VSPI_HOST SPI2_HOST /* No SPI3_host on C3 */
#endif

View File

@ -1,26 +0,0 @@
/*
tasmota_include.h - header to be included in libs for external configuration via Tasmota ifdefs
Copyright (C) 2021 Theo Arends
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 __TASMOTA_INCLUDE__
#define __TASMOTA_INCLUDE__
#include "../tasmota/my_user_config.h"
#include "../tasmota/tasmota_configurations.h"
#endif // __TASMOTA_INCLUDE__

View File

@ -1,334 +0,0 @@
/**************************************************************************//**
* \brief EEPROM 24C128 / 24C256 library for Arduino
* \author Copyright (C) 2012 Julien Le Sech - www.idreammicro.com
* \version 1.0
* \date 20120203
*
* This file is part of the EEPROM 24C128 / 24C256 library for Arduino.
*
* This library is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
******************************************************************************/
/**************************************************************************//**
* \file Eeprom24C128_256.cpp
******************************************************************************/
/******************************************************************************
* Header file inclusions.
******************************************************************************/
#include <Arduino.h>
#include <Wire.h>
#include <Eeprom24C128_256.h>
/******************************************************************************
* Private macro definitions.
******************************************************************************/
/**************************************************************************//**
* \def EEPROM__PAGE_SIZE
* \brief Size of a page in EEPROM memory.
* This size is given by EEPROM memory datasheet.
******************************************************************************/
#define EEPROM__PAGE_SIZE 64
/**************************************************************************//**
* \def EEPROM__RD_BUFFER_SIZE
* \brief Size of input TWI buffer.
* This size is equal to BUFFER_LENGTH defined in Wire library (32 bytes).
******************************************************************************/
#define xBUFFER_LENGTH 24
#define EEPROM__RD_BUFFER_SIZE xBUFFER_LENGTH
/**************************************************************************//**
* \def EEPROM__WR_BUFFER_SIZE
* \brief Size of output TWI buffer.
* This size is equal to BUFFER_LENGTH - 2 bytes reserved for address.
******************************************************************************/
#define EEPROM__WR_BUFFER_SIZE (xBUFFER_LENGTH - 2)
/******************************************************************************
* Public method definitions.
******************************************************************************/
/**************************************************************************//**
* \fn Eeprom24C128_256::Eeprom24C128_256(byte deviceAddress)
*
* \brief Constructor.
*
* \param deviceAddress EEPROM address on TWI bus.
******************************************************************************/
Eeprom24C128_256::Eeprom24C128_256
(
byte deviceAddress
){
m_deviceAddress = deviceAddress;
}
/**************************************************************************//**
* \fn void Eeprom24C128_256::initialize()
*
* \brief Initialize library and TWI bus.
*
* If several devices are connected to TWI bus, this method mustn't be
* called. TWI bus must be initialized out of this library using
* Wire.begin() method.
******************************************************************************/
void
Eeprom24C128_256::initialize()
{
Wire.begin();
}
/**************************************************************************//**
* \fn void Eeprom24C128_256::writeByte(
* word address,
* byte data)
*
* \brief Write a byte in EEPROM memory.
*
* \remarks A delay of 10 ms is required after write cycle.
*
* \param address Address.
* \param data Byte to write.
******************************************************************************/
void
Eeprom24C128_256::writeByte
(
word address,
byte data
){
Wire.beginTransmission(m_deviceAddress);
Wire.write(address >> 8);
Wire.write(address & 0xFF);
Wire.write(data);
Wire.endTransmission();
}
/**************************************************************************//**
* \fn void Eeprom24C128_256::writeBytes(
* word address,
* word length,
* byte* p_data)
*
* \brief Write bytes in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes to write.
* \param[in] p_data Bytes to write.
******************************************************************************/
void
Eeprom24C128_256::writeBytes
(
word address,
word length,
byte* p_data
){
// Write first page if not aligned.
byte notAlignedLength = 0;
byte pageOffset = address % EEPROM__PAGE_SIZE;
if (pageOffset > 0)
{
notAlignedLength = EEPROM__PAGE_SIZE - pageOffset;
if (length < notAlignedLength)
{
notAlignedLength = length;
}
writePage(address, notAlignedLength, p_data);
length -= notAlignedLength;
}
if (length > 0)
{
address += notAlignedLength;
p_data += notAlignedLength;
// Write complete and aligned pages.
word pageCount = length / EEPROM__PAGE_SIZE;
for (word i = 0; i < pageCount; i++)
{
writePage(address, EEPROM__PAGE_SIZE, p_data);
address += EEPROM__PAGE_SIZE;
p_data += EEPROM__PAGE_SIZE;
length -= EEPROM__PAGE_SIZE;
}
if (length > 0)
{
// Write remaining uncomplete page.
writePage(address, length, p_data);
}
}
}
/**************************************************************************//**
* \fn byte Eeprom24C128_256::readByte(word address)
*
* \brief Read a byte in EEPROM memory.
*
* \param address Address.
*
* \return Read byte.
******************************************************************************/
byte
Eeprom24C128_256::readByte
(
word address
){
Wire.beginTransmission(m_deviceAddress);
Wire.write(address >> 8);
Wire.write(address & 0xFF);
Wire.endTransmission();
Wire.requestFrom(m_deviceAddress, (byte)1);
byte data = 0;
if (Wire.available())
{
data = Wire.read();
}
return data;
}
/**************************************************************************//**
* \fn void Eeprom24C128_256::readBytes(
* word address,
* word length,
* byte* p_data)
*
* \brief Read bytes in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes to read.
* \patam[in] p_data Byte array to fill with read bytes.
******************************************************************************/
void
Eeprom24C128_256::readBytes
(
word address,
word length,
byte* p_data
){
byte bufferCount = length / EEPROM__RD_BUFFER_SIZE;
for (byte i = 0; i < bufferCount; i++)
{
word offset = i * EEPROM__RD_BUFFER_SIZE;
readBuffer(address + offset, EEPROM__RD_BUFFER_SIZE, p_data + offset);
}
byte remainingBytes = length % EEPROM__RD_BUFFER_SIZE;
word offset = length - remainingBytes;
readBuffer(address + offset, remainingBytes, p_data + offset);
}
/******************************************************************************
* Private method definitions.
******************************************************************************/
/**************************************************************************//**
* \fn void Eeprom24C128_256::writePage(
* word address,
* byte length,
* byte* p_data)
*
* \brief Write page in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes (EEPROM__PAGE_SIZE bytes max).
* \param[in] p_data Data.
******************************************************************************/
void
Eeprom24C128_256::writePage
(
word address,
byte length,
byte* p_data
){
// Write complete buffers.
byte bufferCount = length / EEPROM__WR_BUFFER_SIZE;
for (byte i = 0; i < bufferCount; i++)
{
byte offset = i * EEPROM__WR_BUFFER_SIZE;
writeBuffer(address + offset, EEPROM__WR_BUFFER_SIZE, p_data + offset);
}
// Write remaining bytes.
byte remainingBytes = length % EEPROM__WR_BUFFER_SIZE;
byte offset = length - remainingBytes;
writeBuffer(address + offset, remainingBytes, p_data + offset);
}
/**************************************************************************//**
* \fn void Eeprom24C128_256::writeBuffer(
* word address,
* byte length,
* byte* p_data)
*
* \brief Write bytes into memory.
*
* \param address Start address.
* \param length Number of bytes (EEPROM__WR_BUFFER_SIZE bytes max).
* \param[in] p_data Data.
******************************************************************************/
void
Eeprom24C128_256::writeBuffer
(
word address,
byte length,
byte* p_data
){
Wire.beginTransmission(m_deviceAddress);
Wire.write(address >> 8);
Wire.write(address & 0xFF);
for (byte i = 0; i < length; i++)
{
Wire.write(p_data[i]);
}
Wire.endTransmission();
// Write cycle time (tWR). See EEPROM memory datasheet for more details.
delay(10);
}
/**************************************************************************//**
* \fn void Eeprom24C128_256::readBuffer(
* word address,
* byte length,
* byte* p_data)
*
* \brief Read bytes in memory.
*
* \param address Start address.
* \param length Number of bytes (EEPROM__RD_BUFFER_SIZE bytes max).
* \param[in] p_data Buffer to fill with read bytes.
******************************************************************************/
void
Eeprom24C128_256::readBuffer
(
word address,
byte length,
byte* p_data
){
Wire.beginTransmission(m_deviceAddress);
Wire.write(address >> 8);
Wire.write(address & 0xFF);
Wire.endTransmission();
Wire.requestFrom(m_deviceAddress, length);
for (byte i = 0; i < length; i++)
{
if (Wire.available())
{
p_data[i] = Wire.read();
}
}
}

View File

@ -1,212 +0,0 @@
/**************************************************************************//**
* \brief EEPROM 24C128 / 24C256 library for Arduino
* \author Copyright (C) 2012 Julien Le Sech - www.idreammicro.com
* \version 1.0
* \date 20120203
*
* This file is part of the EEPROM 24C128 / 24C256 library for Arduino.
*
* This library is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
******************************************************************************/
/**************************************************************************//**
* \headerfile Eeprom24C128_256.h
******************************************************************************/
#ifndef Eeprom24C128_256_h
#define Eeprom24C128_256_h
/******************************************************************************
* Header file inclusion.
******************************************************************************/
#include <Arduino.h>
/**************************************************************************//**
* \class Eeprom24C128_256
*
* \brief EEPROM 24C128 / 24C256 memory driver.
*
* This driver is mainly designed for 24C128 and 24C256 EEPROM memories. It's
* also suitable for 24C512 memories.
******************************************************************************/
class Eeprom24C128_256
{
public:
/******************************************************************//**
* \fn Eeprom24C128_256(byte deviceAddress)
*
* \brief Constructor.
*
* \param deviceAddress EEPROM address on TWI bus.
**********************************************************************/
Eeprom24C128_256
(
byte deviceAddress
);
/******************************************************************//**
* \fn void initialize()
*
* \brief Initialize library abnd TWI bus.
*
* If several devices are connected to TWI bus, this method mustn't be
* called. TWI bus must be initialized out of this library using
* Wire.begin() method.
**********************************************************************/
void
initialize();
/******************************************************************//**
* \fn void writeByte(
* word address,
* byte data)
*
* \brief Write a byte in EEPROM memory.
*
* \remarks A delay of 10 ms is required after write cycle.
*
* \param address Address.
* \param data Byte to write.
**********************************************************************/
void
writeByte
(
word address,
byte data
);
/******************************************************************//**
* \fn void writeBytes(
* word address,
* word length,
* byte* p_data)
*
* \brief Write bytes in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes to write.
* \param[in] p_data Bytes to write.
**********************************************************************/
void
writeBytes
(
word address,
word length,
byte* p_data
);
/******************************************************************//**
* \fn byte readByte(word address)
*
* \brief Read a byte in EEPROM memory.
*
* \param address Address.
*
* \return Read byte.
**********************************************************************/
byte
readByte
(
word address
);
/******************************************************************//**
* \fn void readBytes(
* word address,
* word length,
* byte* p_data)
*
* \brief Read bytes in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes to read.
* \patam[in] p_data Byte array to fill with read bytes.
**********************************************************************/
void
readBytes
(
word address,
word length,
byte* p_buffer
);
private:
byte m_deviceAddress;
/******************************************************************//**
* \fn void writePage(
* word address,
* byte length,
* byte* p_data)
*
* \brief Write page in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes (64 bytes max).
* \param[in] p_data Data.
**********************************************************************/
void
writePage
(
word address,
byte length,
byte* p_data
);
/******************************************************************//**
* \fn void writeBuffer(
* word address,
* byte length,
* byte* p_data)
*
* \brief Write bytes into memory.
*
* \param address Start address.
* \param length Number of bytes (30 bytes max).
* \param[in] p_date Data.
**********************************************************************/
void
writeBuffer
(
word address,
byte length,
byte* p_data
);
/******************************************************************//**
* \fn void readBuffer(
* word address,
* byte length,
* byte* p_data)
*
* \brief Read bytes in memory.
*
* \param address Start address.
* \param length Number of bytes to read (32 bytes max).
* \param[in] p_data Buffer to fill with read bytes.
**********************************************************************/
void
readBuffer
(
word address,
byte length,
byte* p_data
);
};
#endif // Eeprom24C128_256_h

View File

@ -1,336 +0,0 @@
/**************************************************************************//**
* \brief EEPROM 24C512 library for Arduino
* \author Copyright (C) 2012 Julien Le Sech - www.idreammicro.com
* \version 1.0
* \date 20120218
*
* This file is part of the EEPROM 24C512 library for Arduino.
*
* This library is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
******************************************************************************/
/**************************************************************************//**
* \file Eeprom24C512.cpp
******************************************************************************/
/******************************************************************************
* Header file inclusions.
******************************************************************************/
#include <Arduino.h>
#include <Wire.h>
#include <Eeprom24C512.h>
/******************************************************************************
* Private macro definitions.
******************************************************************************/
/**************************************************************************//**
* \def EEPROM__PAGE_SIZE
* \brief Size of a page in EEPROM memory.
* This size is given by EEPROM memory datasheet.
******************************************************************************/
#define EEPROM__PAGE_SIZE 128
/**************************************************************************//**
* \def EEPROM__RD_BUFFER_SIZE
* \brief Size of input TWI buffer.
* This size is equal to BUFFER_LENGTH defined in Wire library (32 bytes).
******************************************************************************/
#define EEPROM__RD_BUFFER_SIZE BUFFER_LENGTH
/**************************************************************************//**
* \def EEPROM__WR_BUFFER_SIZE
* \brief Size of output TWI buffer.
* This size is equal to BUFFER_LENGTH - 2 bytes reserved for address.
******************************************************************************/
#define EEPROM__WR_BUFFER_SIZE (BUFFER_LENGTH - 2)
/******************************************************************************
* Public method definitions.
******************************************************************************/
/**************************************************************************//**
* \fn Eeprom24C512::Eeprom24C512(byte deviceAddress)
*
* \brief Constructor.
*
* \param deviceAddress EEPROM address on TWI bus.
******************************************************************************/
Eeprom24C512::Eeprom24C512
(
byte deviceAddress
){
m_deviceAddress = deviceAddress;
}
/**************************************************************************//**
* \fn void Eeprom24C512::initialize()
*
* \brief Initialize library and TWI bus.
*
* If several devices are connected to TWI bus, this method mustn't be
* called. TWI bus must be initialized out of this library using
* Wire.begin() method.
******************************************************************************/
void
Eeprom24C512::initialize()
{
Wire.begin();
}
/**************************************************************************//**
* \fn void Eeprom24C512::writeByte(
* word address,
* byte data)
*
* \brief Write a byte in EEPROM memory.
*
* \remarks A delay of 10 ms is required after write cycle.
*
* \param address Address.
* \param data Byte to write.
******************************************************************************/
void
Eeprom24C512::writeByte
(
word address,
byte data
){
Wire.beginTransmission(m_deviceAddress);
Wire.write(address >> 8);
Wire.write(address & 0xFF);
Wire.write(data);
Wire.endTransmission();
}
/**************************************************************************//**
* \fn void Eeprom24C512::writeBytes(
* word address,
* word length,
* byte* p_data)
*
* \brief Write bytes in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes to write.
* \param[in] p_data Bytes to write.
******************************************************************************/
void
Eeprom24C512::writeBytes
(
word address,
word length,
byte* p_data
){
// Write first page if not aligned.
byte notAlignedLength = 0;
byte pageOffset = address % EEPROM__PAGE_SIZE;
if (pageOffset > 0)
{
notAlignedLength = EEPROM__PAGE_SIZE - pageOffset;
if (length < notAlignedLength)
{
notAlignedLength = length;
}
writePage(address, notAlignedLength, p_data);
length -= notAlignedLength;
}
if (length > 0)
{
address += notAlignedLength;
p_data += notAlignedLength;
// Write complete and aligned pages.
word pageCount = length / EEPROM__PAGE_SIZE;
for (word i = 0; i < pageCount; i++)
{
writePage(address, EEPROM__PAGE_SIZE, p_data);
address += EEPROM__PAGE_SIZE;
p_data += EEPROM__PAGE_SIZE;
length -= EEPROM__PAGE_SIZE;
}
if (length > 0)
{
// Write remaining uncomplete page.
writePage(address, length, p_data);
}
}
}
/**************************************************************************//**
* \fn byte Eeprom24C512::readByte(word address)
*
* \brief Read a byte in EEPROM memory.
*
* \param address Address.
*
* \return Read byte.
******************************************************************************/
byte
Eeprom24C512::readByte
(
word address
){
Wire.beginTransmission(m_deviceAddress);
Wire.write(address >> 8);
Wire.write(address & 0xFF);
Wire.endTransmission();
Wire.requestFrom(m_deviceAddress, (byte)1);
byte data = 0;
if (Wire.available())
{
data = Wire.read();
}
return data;
}
/**************************************************************************//**
* \fn void Eeprom24C512::readBytes(
* word address,
* word length,
* byte* p_data)
*
* \brief Read bytes in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes to read.
* \patam[in] p_data Byte array to fill with read bytes.
******************************************************************************/
void
Eeprom24C512::readBytes
(
word address,
word length,
byte* p_data
){
word bufferCount = length / EEPROM__RD_BUFFER_SIZE;
for (word i = 0; i < bufferCount; i++)
{
word offset = i * EEPROM__RD_BUFFER_SIZE;
readBuffer(address + offset, EEPROM__RD_BUFFER_SIZE, p_data + offset);
}
byte remainingBytes = length % EEPROM__RD_BUFFER_SIZE;
word offset = length - remainingBytes;
if (remainingBytes > 0) {
readBuffer(address + offset, remainingBytes, p_data + offset);
}
}
/******************************************************************************
* Private method definitions.
******************************************************************************/
/**************************************************************************//**
* \fn void Eeprom24C512::writePage(
* word address,
* byte length,
* byte* p_data)
*
* \brief Write page in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes (EEPROM__PAGE_SIZE bytes max).
* \param[in] p_data Data.
******************************************************************************/
void
Eeprom24C512::writePage
(
word address,
byte length,
byte* p_data
){
// Write complete buffers.
byte bufferCount = length / EEPROM__WR_BUFFER_SIZE;
for (byte i = 0; i < bufferCount; i++)
{
byte offset = i * EEPROM__WR_BUFFER_SIZE;
writeBuffer(address + offset, EEPROM__WR_BUFFER_SIZE, p_data + offset);
}
// Write remaining bytes.
byte remainingBytes = length % EEPROM__WR_BUFFER_SIZE;
byte offset = length - remainingBytes;
writeBuffer(address + offset, remainingBytes, p_data + offset);
}
/**************************************************************************//**
* \fn void Eeprom24C512::writeBuffer(
* word address,
* byte length,
* byte* p_data)
*
* \brief Write bytes into memory.
*
* \param address Start address.
* \param length Number of bytes (EEPROM__WR_BUFFER_SIZE bytes max).
* \param[in] p_data Data.
******************************************************************************/
void
Eeprom24C512::writeBuffer
(
word address,
byte length,
byte* p_data
){
Wire.beginTransmission(m_deviceAddress);
Wire.write(address >> 8);
Wire.write(address & 0xFF);
for (byte i = 0; i < length; i++)
{
Wire.write(p_data[i]);
}
Wire.endTransmission();
// Write cycle time (tWR). See EEPROM memory datasheet for more details.
delay(10);
}
/**************************************************************************//**
* \fn void Eeprom24C512::readBuffer(
* word address,
* byte length,
* byte* p_data)
*
* \brief Read bytes in memory.
*
* \param address Start address.
* \param length Number of bytes (EEPROM__RD_BUFFER_SIZE bytes max).
* \param[in] p_data Buffer to fill with read bytes.
******************************************************************************/
void
Eeprom24C512::readBuffer
(
word address,
byte length,
byte* p_data
){
Wire.beginTransmission(m_deviceAddress);
Wire.write(address >> 8);
Wire.write(address & 0xFF);
Wire.endTransmission();
Wire.requestFrom(m_deviceAddress, length);
for (byte i = 0; i < length; i++)
{
if (Wire.available())
{
p_data[i] = Wire.read();
}
}
}

View File

@ -1,211 +0,0 @@
/**************************************************************************//**
* \brief EEPROM 24C512 library for Arduino
* \author Copyright (C) 2012 Julien Le Sech - www.idreammicro.com
* \version 1.0
* \date 20120203
*
* This file is part of the EEPROM 24C512 library for Arduino.
*
* This library is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
******************************************************************************/
/**************************************************************************//**
* \headerfile Eeprom24C512.h
******************************************************************************/
#ifndef Eeprom24C512_h
#define Eeprom24C512_h
/******************************************************************************
* Header file inclusion.
******************************************************************************/
#include <Arduino.h>
/**************************************************************************//**
* \class Eeprom24C512
*
* \brief EEPROM 24C512 memory driver.
*
* This driver is designed for 24C512 memory.
******************************************************************************/
class Eeprom24C512
{
public:
/******************************************************************//**
* \fn Eeprom24C512(byte deviceAddress)
*
* \brief Constructor.
*
* \param deviceAddress EEPROM address on TWI bus.
**********************************************************************/
Eeprom24C512
(
byte deviceAddress
);
/******************************************************************//**
* \fn void initialize()
*
* \brief Initialize library abnd TWI bus.
*
* If several devices are connected to TWI bus, this method mustn't be
* called. TWI bus must be initialized out of this library using
* Wire.begin() method.
**********************************************************************/
void
initialize();
/******************************************************************//**
* \fn void writeByte(
* word address,
* byte data)
*
* \brief Write a byte in EEPROM memory.
*
* \remarks A delay of 10 ms is required after write cycle.
*
* \param address Address.
* \param data Byte to write.
**********************************************************************/
void
writeByte
(
word address,
byte data
);
/******************************************************************//**
* \fn void writeBytes(
* word address,
* word length,
* byte* p_data)
*
* \brief Write bytes in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes to write.
* \param[in] p_data Bytes to write.
**********************************************************************/
void
writeBytes
(
word address,
word length,
byte* p_data
);
/******************************************************************//**
* \fn byte readByte(word address)
*
* \brief Read a byte in EEPROM memory.
*
* \param address Address.
*
* \return Read byte.
**********************************************************************/
byte
readByte
(
word address
);
/******************************************************************//**
* \fn void readBytes(
* word address,
* word length,
* byte* p_data)
*
* \brief Read bytes in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes to read.
* \patam[in] p_data Byte array to fill with read bytes.
**********************************************************************/
void
readBytes
(
word address,
word length,
byte* p_buffer
);
private:
byte m_deviceAddress;
/******************************************************************//**
* \fn void writePage(
* word address,
* byte length,
* byte* p_data)
*
* \brief Write page in EEPROM memory.
*
* \param address Start address.
* \param length Number of bytes (64 bytes max).
* \param[in] p_data Data.
**********************************************************************/
void
writePage
(
word address,
byte length,
byte* p_data
);
/******************************************************************//**
* \fn void writeBuffer(
* word address,
* byte length,
* byte* p_data)
*
* \brief Write bytes into memory.
*
* \param address Start address.
* \param length Number of bytes (30 bytes max).
* \param[in] p_date Data.
**********************************************************************/
void
writeBuffer
(
word address,
byte length,
byte* p_data
);
/******************************************************************//**
* \fn void readBuffer(
* word address,
* byte length,
* byte* p_data)
*
* \brief Read bytes in memory.
*
* \param address Start address.
* \param length Number of bytes to read (32 bytes max).
* \param[in] p_data Buffer to fill with read bytes.
**********************************************************************/
void
readBuffer
(
word address,
byte length,
byte* p_data
);
};
#endif // Eeprom24C512_h

View File

@ -1,9 +0,0 @@
name=EEPROM 24C128_256_521
version=
author=Julien Le Sech
maintainer=Julien Le Sech - www.idreammicro.com
sentence=EEPROM 24C128 / 24C256 / 24C512 memory driver.
paragraph=EEPROM 24C128 / 24C256 / 24C512 memory driver.
category=
url=
architectures=*

View File

@ -1,7 +0,0 @@
name=Ext-printf
version=1.0
author=Stephan Hadinger
maintainer=Stephan <stephan.hadinger@gmail.com>
sentence=Extension of snprintf() and vsnprintf()
paragraph=This library provides extended types support for snprintf (float, uint64_t)
architectures=esp8266, esp32

View File

@ -1,307 +0,0 @@
/*
support_buffer.ino - Static binary buffer for Zigbee on Tasmota
Copyright (C) 2021 Theo Arends and Stephan Hadinger
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/>.
*/
typedef struct SBuffer_impl {
uint16_t size; // size in bytes of the buffer
uint16_t len; // current size of the data in buffer. Invariant: len <= size
uint8_t buf[]; // the actual data
} SBuffer_impl;
typedef class SBuffer {
protected:
SBuffer(void) {
// unused empty constructor except from subclass
}
public:
SBuffer(const size_t size) {
_buf = (SBuffer_impl*) new char[size+4]; // add 4 bytes for size and len
_buf->size = size;
_buf->len = 0;
//*((uint32_t*)_buf) = size; // writing both size and len=0 in a single 32 bits write
}
inline size_t getSize(void) const { return _buf->size; }
inline size_t size(void) const { return _buf->size; }
inline size_t getLen(void) const { return _buf->len; }
inline size_t len(void) const { return _buf->len; }
inline uint8_t *getBuffer(void) const { return _buf->buf; }
inline uint8_t *buf(size_t i = 0) const { return &_buf->buf[i]; }
inline char *charptr(size_t i = 0) const { return (char*) &_buf->buf[i]; }
virtual ~SBuffer(void) {
delete[] _buf;
}
// increase the internal buffer if needed
// do nothing if the buffer is big enough
void reserve(const size_t size) {
if (size > _buf->size) {
// we need to increase the buffer size
SBuffer_impl * new_buf = (SBuffer_impl*) new char[size+4]; // add 4 bytes for size and len
new_buf->size = size;
new_buf->len = _buf->len;
memmove(&new_buf->buf, &_buf->buf, _buf->len); // copy buffer
delete[] _buf;
_buf = new_buf;
}
}
inline void setLen(const size_t len) {
uint16_t old_len = _buf->len;
_buf->len = (len <= _buf->size) ? len : _buf->size;
if (old_len < _buf->len) {
memset((void*) &_buf->buf[old_len], 0, _buf->len - old_len);
}
}
void set8(const size_t offset, const uint8_t data) {
if (offset < _buf->len) {
_buf->buf[offset] = data;
}
}
size_t add8(const uint8_t data) { // append 8 bits value
if (_buf->len < _buf->size) { // do we have room for 1 byte
_buf->buf[_buf->len++] = data;
}
return _buf->len;
}
size_t add16(const uint16_t data) { // append 16 bits value
if (_buf->len < _buf->size - 1) { // do we have room for 2 bytes
_buf->buf[_buf->len++] = data;
_buf->buf[_buf->len++] = data >> 8;
}
return _buf->len;
}
size_t add16BigEndian(const uint16_t data) { // append 16 bits value
if (_buf->len < _buf->size - 1) { // do we have room for 2 bytes
_buf->buf[_buf->len++] = data >> 8;
_buf->buf[_buf->len++] = data;
}
return _buf->len;
}
size_t add32(const uint32_t data) { // append 32 bits value
if (_buf->len < _buf->size - 3) { // do we have room for 4 bytes
_buf->buf[_buf->len++] = data;
_buf->buf[_buf->len++] = data >> 8;
_buf->buf[_buf->len++] = data >> 16;
_buf->buf[_buf->len++] = data >> 24;
}
return _buf->len;
}
size_t add32BigEndian(const uint32_t data) { // append 32 bits value
if (_buf->len < _buf->size - 3) { // do we have room for 4 bytes
_buf->buf[_buf->len++] = data >> 24;
_buf->buf[_buf->len++] = data >> 16;
_buf->buf[_buf->len++] = data >> 8;
_buf->buf[_buf->len++] = data;
}
return _buf->len;
}
size_t add64(const uint64_t data) { // append 64 bits value
if (_buf->len < _buf->size - 7) { // do we have room for 8 bytes
_buf->buf[_buf->len++] = data;
_buf->buf[_buf->len++] = data >> 8;
_buf->buf[_buf->len++] = data >> 16;
_buf->buf[_buf->len++] = data >> 24;
_buf->buf[_buf->len++] = data >> 32;
_buf->buf[_buf->len++] = data >> 40;
_buf->buf[_buf->len++] = data >> 48;
_buf->buf[_buf->len++] = data >> 56;
}
return _buf->len;
}
void replace(const SBuffer &buf2) {
uint32_t len = buf2.len();
reserve(len);
setLen(0); // clear buffer
addBuffer(buf2);
}
size_t addBuffer(const SBuffer &buf2) {
if (len() + buf2.len() <= size()) {
for (uint32_t i = 0; i < buf2.len(); i++) {
_buf->buf[_buf->len++] = buf2.buf()[i];
}
}
return _buf->len;
}
size_t addBuffer(const uint8_t *buf2, size_t len2) {
if ((buf2) && (len() + len2 <= size())) {
for (uint32_t i = 0; i < len2; i++) {
_buf->buf[_buf->len++] = pgm_read_byte(&buf2[i]);
}
}
return _buf->len;
}
size_t addBuffer(const char *buf2, size_t len2) {
if ((buf2) && (len() + len2 <= size())) {
for (uint32_t i = 0; i < len2; i++) {
_buf->buf[_buf->len++] = pgm_read_byte(&buf2[i]);
}
}
return _buf->len;
}
uint8_t get8(size_t offset) const {
if (offset < _buf->len) {
return _buf->buf[offset];
} else {
return 0;
}
}
uint8_t read8(const size_t offset) const {
if (offset < len()) {
return _buf->buf[offset];
}
return 0;
}
uint16_t get16(const size_t offset) const {
if (offset < len() - 1) {
return _buf->buf[offset] | (_buf->buf[offset+1] << 8);
}
return 0;
}
uint16_t get16BigEndian(const size_t offset) const {
if (offset < len() - 1) {
return _buf->buf[offset+1] | (_buf->buf[offset] << 8);
}
return 0;
}
uint32_t get32(const size_t offset) const {
if (offset < len() - 3) {
return _buf->buf[offset] | (_buf->buf[offset+1] << 8) |
(_buf->buf[offset+2] << 16) | (_buf->buf[offset+3] << 24);
}
return 0;
}
uint32_t get32BigEndian(const size_t offset) const {
if (offset < len() - 3) {
return _buf->buf[offset+3] | (_buf->buf[offset+2] << 8) |
(_buf->buf[offset+1] << 16) | (_buf->buf[offset] << 24);
}
return 0;
}
int32_t get32IBigEndian(const size_t offset) const {
if (offset < len() - 3) {
return _buf->buf[offset+3] | (_buf->buf[offset+2] << 8) |
(_buf->buf[offset+1] << 16) | (_buf->buf[offset] << 24);
}
return 0;
}
uint64_t get64(const size_t offset) const {
if (offset < len() - 7) {
return (uint64_t)_buf->buf[offset] | ((uint64_t)_buf->buf[offset+1] << 8) |
((uint64_t)_buf->buf[offset+2] << 16) | ((uint64_t)_buf->buf[offset+3] << 24) |
((uint64_t)_buf->buf[offset+4] << 32) | ((uint64_t)_buf->buf[offset+5] << 40) |
((uint64_t)_buf->buf[offset+6] << 48) | ((uint64_t)_buf->buf[offset+7] << 56);
}
return 0;
}
size_t strlen(const size_t offset) const {
if (offset >= len()) { return 0; }
size_t slen = strnlen((const char*) &_buf->buf[offset], len() - offset);
if (slen == (len() - offset)) {
return 0; // we didn't find a NULL char
} else {
return slen;
}
}
SBuffer subBuffer(const size_t start, size_t len) const {
if (start >= _buf->len) {
len = 0;
} else if (start + len > _buf->len) {
len = _buf->len - start;
}
SBuffer buf2(len);
memcpy(buf2.buf(), buf()+start, len);
buf2._buf->len = len;
return buf2;
}
static SBuffer SBufferFromHex(const char *hex, size_t len) {
size_t buf_len = (len + 3) / 2;
SBuffer buf2(buf_len);
uint8_t val;
for (; len > 1; len -= 2) {
val = asc2byte(*hex++) << 4;
val |= asc2byte(*hex++);
buf2.add8(val);
}
return buf2;
}
// nullptr accepted
static bool equalsSBuffer(const class SBuffer * buf1, const class SBuffer * buf2) {
if (buf1 == buf2) { return true; }
if (!buf1 && (buf2->len() == 0)) { return true; }
if (!buf2 && (buf1->len() == 0)) { return true; }
if (!buf1 || !buf2) { return false; } // at least one buf is not empty
// we know that both buf1 and buf2 are non-null
if (buf1->len() != buf2->len()) { return false; }
size_t len = buf1->len();
for (uint32_t i=0; i<len; i++) {
if (buf1->get8(i) != buf2->get8(i)) { return false; }
}
return true;
}
protected:
static uint8_t asc2byte(char chr) {
uint8_t rVal = 0;
if (isdigit(chr)) { rVal = chr - '0'; }
else if (chr >= 'A' && chr <= 'F') { rVal = chr + 10 - 'A'; }
else if (chr >= 'a' && chr <= 'f') { rVal = chr + 10 - 'a'; }
return rVal;
}
static void unHex(const char* in, uint8_t *out, size_t len) {
}
protected:
SBuffer_impl * _buf;
} SBuffer;
typedef class PreAllocatedSBuffer : public SBuffer {
public:
PreAllocatedSBuffer(const size_t size, void * buffer) {
_buf = (SBuffer_impl*) buffer;
_buf->size = size - 4;
_buf->len = 0;
}
~PreAllocatedSBuffer(void) {
// don't deallocate
_buf = nullptr;
}
} PreAllocatedSBuffer;

View File

@ -1,445 +0,0 @@
/*
ext_printf.ino - Extended printf for Arduino objects
Copyright (C) 2021 Stephan Hadinger
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/>.
*/
#include "ext_printf.h"
#include <Arduino.h>
#include <IPAddress.h>
#include <SBuffer.hpp>
/*********************************************************************************************\
* va_list extended support
*
* va_list allows to get the next argument but not to get the address of this argument in the stack.
*
* We add `va_cur_ptr(va, TYPE)` to get a pointer to the current argument.
* This will allow to modify it in place and call back printf with altered arguments
\*********************************************************************************************/
#if defined(__XTENSA__) // this works only for xtensa, other platforms needs va_list to be adapted
// This code is heavily inspired by the gcc implementation of va_list
// https://github.com/gcc-mirror/gcc/blob/master/gcc/config/xtensa/xtensa.c
// Here is the va_list structure:
// struct va_list {
// void * __va_stk; // offset 0 - pointer to arguments on the stack
// void * __va_reg; // offset 4 - pointer to arguments from registers
// uint32_t __va_ndx; // offset 8 - index in bytes of the argument (overshoot by sizeof(T))
// }
//
// When `va_start()` is called, the first 6 arguments are passed through registers r2-r7 and
// are saved on the stack like local variables
// The algorightm used by `va_arg()` is the following:
// /* Implement `va_arg'.  */
// /* First align __va_ndx if necessary for this arg:
//     orig_ndx = (AP).__va_ndx;
//     if (__alignof__ (TYPE) > 4 )
//       orig_ndx = ((orig_ndx + __alignof__ (TYPE) - 1)
// & -__alignof__ (TYPE)); */
// /* Increment __va_ndx to point past the argument:
//     (AP).__va_ndx = orig_ndx + __va_size (TYPE); */
// /* Check if the argument is in registers:
//     if ((AP).__va_ndx <= __MAX_ARGS_IN_REGISTERS * 4
//         && !must_pass_in_stack (type))
//       __array = (AP).__va_reg; */
// /* ...otherwise, the argument is on the stack (never split between
//     registers and the stack -- change __va_ndx if necessary):
//     else
//       {
// if (orig_ndx <= __MAX_ARGS_IN_REGISTERS * 4)
//     (AP).__va_ndx = 32 + __va_size (TYPE);
// __array = (AP).__va_stk;
//       } */
// /* Given the base array pointer (__array) and index to the subsequent
//     argument (__va_ndx), find the address:
//     __array + (AP).__va_ndx - (BYTES_BIG_ENDIAN && sizeof (TYPE) < 4
// ? sizeof (TYPE)
// : __va_size (TYPE))
//     The results are endian-dependent because values smaller than one word
//     are aligned differently.  */
// So we can simply get the argument address
#define MAX_ARGS_IN_REGISTERS 6 // ESP8266 passes 6 arguments by register, then on stack
// #define va_cur_ptr(va,T) ( (T*) __va_cur_ptr(va,sizeof(T)) ) // we only support 4 bytes aligned arguments, so we don't need this one
// void * __va_cur_ptr(va_list &va, size_t size) {
// size = (size + 3) & 0xFFFFFFFC; // round to upper 4 bytes boundary
// uintptr_t * va_stk = (uintptr_t*) &va;
// uintptr_t * va_reg = 1 + (uintptr_t*) &va;
// uintptr_t * va_ndx = 2 + (uintptr_t*) &va;
// uintptr_t arr;
// if (*va_ndx <= MAX_ARGS_IN_REGISTERS * 4) {
// arr = *va_reg;
// } else {
// arr = *va_stk;
// }
// return (void*) (arr + *va_ndx - size);
// }
// reduced version when arguments are always 4 bytes
#define va_cur_ptr4(va,T) ( (T*) __va_cur_ptr4(va) )
void * __va_cur_ptr4(va_list &va) {
uintptr_t * va_stk = (uintptr_t*) &va;
uintptr_t * va_reg = 1 + (uintptr_t*) &va;
uintptr_t * va_ndx = 2 + (uintptr_t*) &va;
uintptr_t arr;
if (*va_ndx <= MAX_ARGS_IN_REGISTERS * 4) {
arr = *va_reg;
} else {
arr = *va_stk;
}
return (void*) (arr + *va_ndx - 4);
}
// Example of logs with 8 arguments (+1 static argument)
// We see that the first 5 are from low in the stack (local variables)
// while the last 8 are upper in the stack pushed by caller
//
// Note 64 bits arguments cannot be split between registers and stack
//
// >>> Reading a_ptr=0x3FFFFD44 *a_ptr=1
// >>> Reading a_ptr=0x3FFFFD48 *a_ptr=2
// >>> Reading a_ptr=0x3FFFFD4C *a_ptr=3
// >>> Reading a_ptr=0x3FFFFD50 *a_ptr=4
// >>> Reading a_ptr=0x3FFFFD54 *a_ptr=5
// >>> Reading a_ptr=0x3FFFFD70 *a_ptr=6
// >>> Reading a_ptr=0x3FFFFD74 *a_ptr=7
// >>> Reading a_ptr=0x3FFFFD78 *a_ptr=8
#elif defined(__riscv)
// #define __va_argsiz_tas(t) (((sizeof(t) + sizeof(int) - 1) / sizeof(int)) * sizeof(int))
#define va_cur_ptr4(va,T) ( (T*) __va_cur_ptr4(va) )
void * __va_cur_ptr4(va_list &va) {
uintptr_t * va_ptr = (uintptr_t*) &va;
int32_t * cur_ptr = (int32_t*) *va_ptr;
return (void*) (cur_ptr - 1);
}
#else // __XTENSA__, __riscv
#error "ext_printf is not suppoerted on this platform"
#endif // __XTENSA__, __riscv
/*********************************************************************************************\
* Genral function to convert u64 to hex
\*********************************************************************************************/
// Simple function to print a 64 bits unsigned int
/*
char * U64toHex(uint64_t value, char *str) {
// str must be at least 17 bytes long
str[16] = 0; // end of string
for (uint32_t i=0; i<16; i++) { // 16 digits
uint32_t n = value & 0x0F;
str[15 - i] = (n < 10) ? (char)n+'0' : (char)n-10+'A';
value = value >> 4;
}
return str;
}
*/
char * U64toHex(uint64_t value, char *str, uint32_t zeroleads) {
// str must be at least 17 bytes long
str[16] = 0; // end of string
for (uint32_t i=0; i<16; i++) { // 16 digits
uint32_t n = value & 0x0F;
str[15 - i] = (n < 10) ? (char)n+'0' : (char)n-10+'A';
value = value >> 4;
}
if (zeroleads < 16) {
uint32_t max_zeroes = 16 - zeroleads;
while (max_zeroes) {
if (str[0] == '0') {
memmove(str, str +1, strlen(str));
} else {
break;
}
max_zeroes--;
}
}
return str;
}
// see https://stackoverflow.com/questions/6357031/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-in-c
// char* ToHex_P(unsigned char * in, size_t insz, char * out, size_t outsz, char inbetween = '\0'); in tasmota_globals.h
char* ToHex_P(const unsigned char * in, size_t insz, char * out, size_t outsz, char inbetween = '\0') {
// ToHex_P(in, insz, out, outz) -> "12345667"
// ToHex_P(in, insz, out, outz, ' ') -> "12 34 56 67"
// ToHex_P(in, insz, out, outz, ':') -> "12:34:56:67"
static const char * hex PROGMEM = "0123456789ABCDEF";
int between = (inbetween) ? 3 : 2;
const unsigned char * pin = in;
char * pout = out;
for (; pin < in+insz; pout += between, pin++) {
pout[0] = pgm_read_byte(&hex[(pgm_read_byte(pin)>>4) & 0xF]);
pout[1] = pgm_read_byte(&hex[ pgm_read_byte(pin) & 0xF]);
if (inbetween) { pout[2] = inbetween; }
if (pout + 3 - out > outsz) { break; } // Better to truncate output string than overflow buffer
}
pout[(inbetween && insz) ? -1 : 0] = 0; // Discard last inbetween if any input
return out;
}
/*********************************************************************************************\
* snprintf extended
*
* New: if the provided buffer is nullptr, a buffer is allocated on the heap (malloc)
* and returned as a pointer instead of the length of the output (needs casting)
\*********************************************************************************************/
// get a fresh malloc allocated string based on the current pointer (can be in PROGMEM)
// It is the caller's responsibility to free the memory
char * copyStr(const char * str) {
if (str == nullptr) { return nullptr; }
char * cpy = (char*) malloc(strlen_P(str) + 1);
strcpy_P(cpy, str);
return cpy;
}
const char ext_invalid_mem[] PROGMEM = "<--INVALID-->";
const uint32_t min_valid_ptr = 0x3F000000; // addresses below this line are invalid
int32_t ext_vsnprintf_P(char * out_buf, size_t buf_len, const char * fmt_P, va_list va) {
va_list va_cpy;
va_copy(va_cpy, va);
// iterate on fmt to extract arguments and patch them in place
char * fmt_cpy = copyStr(fmt_P);
if (fmt_cpy == nullptr) { return 0; }
char * fmt = fmt_cpy;
const uint32_t ALLOC_SIZE = 12;
static const char * allocs[ALLOC_SIZE] = {}; // initialized to zeroes
uint32_t alloc_idx = 0;
static char hex[20]; // buffer used for 64 bits, favor RAM instead of stack to remove pressure
for (; *fmt != 0; ++fmt) {
int32_t decimals = -2; // default to 2 decimals and remove trailing zeros
int32_t * decimals_ptr = nullptr;
if (alloc_idx >= ALLOC_SIZE) { break; } // buffer is full, don't continue parsing
if (*fmt == '%') {
fmt++;
char * fmt_start = fmt;
if (*fmt == '\0') { break; } // end of string
if (*fmt == '%') { continue; } // actual '%' char
if (*fmt == '*') {
decimals = va_arg(va, int32_t); // skip width argument as int
decimals_ptr = va_cur_ptr4(va, int32_t); // pointer to value on stack
fmt++;
// Serial.printf("> decimals=%d, decimals_ptr=0x%08X\n", decimals, decimals_ptr);
}
if (*fmt < 'A') {
decimals = strtol(fmt, nullptr, 10);
}
while (*fmt < 'A') { // brutal way to munch anything that is not a letter or '-' (or anything else)
// while ((*fmt >= '0' && *fmt <= '9') || (*fmt == '.') || (*fmt == '*') || (*fmt == '-' || (*fmt == ' ' || (*fmt == '+') || (*fmt == '#')))) {
fmt++;
}
if (*fmt == '_') { // extension
if (decimals_ptr) {
// Serial.printf(">2 decimals=%d, decimals_ptr=0x%08X\n", decimals, decimals_ptr);
*decimals_ptr = 0; // if '*' was used, make sure we replace the value with zero for snprintf()
*(fmt_start++) = '-'; // in this case replace with `%-*s`
*(fmt_start++) = '*';
}
for (; fmt_start <= fmt; fmt_start++) {
*fmt_start = '0';
}
// *fmt = '0';
fmt++;
uint32_t cur_val = va_arg(va, uint32_t); // current value
const char ** cur_val_ptr = va_cur_ptr4(va, const char*); // pointer to value on stack
const char * new_val_str = "";
switch (*fmt) {
case 'H': // Hex, decimals indicates the length, default 2
{
if (decimals < 0) { decimals = 0; }
if (cur_val < min_valid_ptr) { new_val_str = ext_invalid_mem; }
else if (decimals > 0) {
char * hex_char = (char*) malloc(decimals*2 + 2);
ToHex_P((const uint8_t *)cur_val, decimals, hex_char, decimals*2 + 2);
new_val_str = hex_char;
allocs[alloc_idx++] = new_val_str;
// Serial.printf("> hex=%s\n", hex_char);
}
}
break;
case 'B': // Pointer to SBuffer
{
if (cur_val < min_valid_ptr) { new_val_str = ext_invalid_mem; }
else {
const SBuffer & buf = *(const SBuffer*)cur_val;
size_t buf_len = (&buf != nullptr) ? buf.len() : 0;
if (buf_len) {
char * hex_char = (char*) malloc(buf_len*2 + 2);
ToHex_P(buf.getBuffer(), buf_len, hex_char, buf_len*2 + 2);
new_val_str = hex_char;
allocs[alloc_idx++] = new_val_str;
}
}
}
break;
// case 'D':
// decimals = *(int32_t*)cur_val_ptr;
// break;
// `%_I` ouputs an IPv4 32 bits address passed as u32 into a decimal dotted format
case 'I': // Input is `uint32_t` 32 bits IP address, output is decimal dotted address
{
char * ip_str = (char*) malloc(16);
snprintf_P(ip_str, 16, PSTR("%u.%u.%u.%u"), cur_val & 0xFF, (cur_val >> 8) & 0xFF, (cur_val >> 16) & 0xFF, (cur_val >> 24) & 0xFF);
new_val_str = ip_str;
allocs[alloc_idx++] = new_val_str;
}
break;
// `%_f` or `%*_f` outputs a float with optionan number of decimals passed as first argument if `*` is present
// positive number of decimals means an exact number of decimals, can be `0` terminate
// negative number of decimals will suppress
// Ex:
// char c[128];
// float f = 3.141f;
// ext_vsnprintf_P(c; szeof(c), "%_f %*_f %*_f", &f, 4, 1f, -4, %f);
// --> c will be "3.14 3.1410 3.141"
// Note: float MUST be passed by address, because C alsays promoted float to double when in vararg
case 'f': // input is `float`, printed to float with 2 decimals
{
if (cur_val < min_valid_ptr) { new_val_str = ext_invalid_mem; }
else {
bool truncate = false;
if (decimals < 0) {
decimals = -decimals;
truncate = true;
}
float number = *(float*)cur_val;
if (isnan(number) || isinf(number)) {
new_val_str = "null";
} else {
dtostrf(*(float*)cur_val, (decimals + 2), decimals, hex);
if (truncate) {
uint32_t last = strlen(hex) - 1;
// remove trailing zeros
while (hex[last] == '0') {
hex[last--] = 0; // remove last char
}
// remove trailing dot
if (hex[last] == '.') {
hex[last] = 0;
}
}
new_val_str = copyStr(hex);
allocs[alloc_idx++] = new_val_str;
}
}
}
break;
// '%_X' outputs a 64 bits unsigned int to uppercase HEX with 16 digits
case 'X': // input is `uint64_t*`, printed as 16 hex digits (no prefix 0x)
{
if (cur_val < min_valid_ptr) { new_val_str = ext_invalid_mem; }
else {
if ((decimals < 0) || (decimals > 16)) { decimals = 16; }
U64toHex(*(uint64_t*)cur_val, hex, decimals);
new_val_str = copyStr(hex);
allocs[alloc_idx++] = new_val_str;
}
}
break;
// Trying to do String allocation alternatives, but not as interesting as I thought in the beginning
// case 's':
// {
// new_val_str = copyStr(((String*)cur_val)->c_str());
// allocs[alloc_idx++] = new_val_str;
// }
// break;
// case 'S':
// {
// funcString_t * func_str = (funcString_t*) cur_val;
// new_val_str = copyStr((*func_str)().c_str());
// allocs[alloc_idx++] = new_val_str;
// }
// break;
}
*cur_val_ptr = new_val_str;
*fmt = 's'; // replace `%_X` with `%0s` to display a string instead
} else {
va_arg(va, int32_t); // munch one 32 bits argument and leave it unchanged
// we take the hypothesis here that passing 64 bits arguments is always unsupported in ESP8266
}
}
}
// Serial.printf("> format_final=%s\n", fmt_cpy); Serial.flush();
int32_t ret = 0; // return 0 if unsuccessful
if (out_buf != nullptr) {
ret = vsnprintf_P(out_buf, buf_len, fmt_cpy, va_cpy);
} else {
// if there is no output buffer, we allocate one on the heap
// first we do a dry-run to know the target size
char dummy[2];
int32_t target_len = vsnprintf_P(dummy, 1, fmt_cpy, va_cpy);
if (target_len >= 0) {
// successful
char * allocated_buf = (char*) malloc(target_len + 1);
if (allocated_buf != nullptr) {
allocated_buf[0] = 0; // default to empty string
vsnprintf_P(allocated_buf, target_len + 1, fmt_cpy, va_cpy);
ret = (int32_t) allocated_buf;
}
}
}
va_end(va_cpy);
// disallocated all temporary strings
for (uint32_t i = 0; i < alloc_idx; i++) {
free((void*)allocs[i]); // it is ok to call free() on nullptr so we don't test for nullptr first
allocs[i] = nullptr;
}
free(fmt_cpy); // free the local copy of the format string
return ret;
}
char * ext_vsnprintf_malloc_P(const char * fmt_P, va_list va) {
int32_t ret = ext_vsnprintf_P(nullptr, 0, fmt_P, va);
return (char*) ret;
}
int32_t ext_snprintf_P(char * out_buf, size_t buf_len, const char * fmt, ...) {
va_list va;
va_start(va, fmt);
int32_t ret = ext_vsnprintf_P(out_buf, buf_len, fmt, va);
va_end(va);
return ret;
}
char * ext_snprintf_malloc_P(const char * fmt, ...) {
va_list va;
va_start(va, fmt);
int32_t ret = ext_vsnprintf_P(nullptr, 0, fmt, va);
va_end(va);
return (char*) ret;
}

View File

@ -1,36 +0,0 @@
/*
ext_printf.ino - Extended printf for Arduino objects
Copyright (C) 2021 Stephan Hadinger
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 EXT_PRINTF_H
#define EXT_PRINTF_H
#include <cstddef>
#include <cstdint>
#include <cstdarg>
int32_t ext_vsnprintf_P(char * buf, size_t buf_len, const char * fmt_P, va_list va);
int32_t ext_snprintf_P(char * buf, size_t buf_len, const char * fmt, ...);
char * ext_snprintf_malloc_P(const char * fmt, ...);
char * ext_vsnprintf_malloc_P(const char * fmt_P, va_list va);
char* ToHex_P(const unsigned char * in, size_t insz, char * out, size_t outsz, char inbetween);
// void test_ext_snprintf_P(void);
#endif // EXT_PRINTF_H

View File

@ -1,110 +0,0 @@
/*
ext_printf.ino - Extended printf for Arduino objects
Copyright (C) 2021 Stephan Hadinger
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/>.
*/
#include "ext_printf.h"
#include <Arduino.h>
// DEBUG only
// String test_string(void) {
// String s("This is the string");
// return s;
// }
// String f_str(void) { return String("foobar"); }
// String k_str("foobar");
// void f1(String s) {
// Serial.printf("> %s\n", s.c_str());
// }
// void f2(void) {
// f1(f_str());
// }
// void test_snprintf1(void) {
// char c[100];
// snprintf_P(c, sizeof(c), PSTR("s1=%s, s2=%s"), k_str.c_str(), f_str().c_str());
// }
// void test_snprintf2(void) {
// char c[100];
// ext_snprintf_P(c, sizeof(c), PSTR("s1=%_s, s2=%_S"), &k_str, &f_str, &ResponseAppendTHD);
// }
void test_ext_snprintf_P(void) {
// test_snprintf1();
// test_snprintf2();
// if (0) {
// // testVarArg2("", 1, 2, 3, 4, 5, 6, 7, 8);
char c[128];
float fpi=-3333.1415926535f;
float f3 = 3333;
float f31 = 3333.1;
ext_snprintf_P(c, sizeof(c), "Int1 = %d, ip=%_I", 1, 0x10203040);
Serial.printf("--> out=%s\n", c);
ext_snprintf_P(c, sizeof(c), "Float default=%_f %_f", &f3, &fpi);
Serial.printf("--> out=%s\n", c);
ext_snprintf_P(c, sizeof(c), "Float default=%1_f, int(3)=%4_f, int(3)=%-4_f, int(3)=%-4_f, 6dec=%-8_f", &fpi, &f3, &f3, &f31, &fpi);
Serial.printf("--> out=%s\n", c);
ext_snprintf_P(c, sizeof(c), "Float default=%*_f, int(3)=%*_f, int(3)=%*_f, int(3)=%*_f, 6dec=%*_f", 1, &fpi, 4, &f3, -4, &f3, -4, &f31, -8, &fpi);
Serial.printf("--> out=%s\n", c);
uint64_t u641 = 0x1122334455667788LL;
uint64_t u642 = 0x0123456789ABCDEFLL;
uint64_t u643 = 0xFEDCBA9876543210LL;
ext_snprintf_P(c, sizeof(c), "Int64 0x%_X 0x%_X 0x%_X", &u641, &u642, &u643);
Serial.printf("--> out=%s\n", c);
// ext_snprintf_P(c, sizeof(c), "Float default=%*_f, int(3)=%*_f, int(3)=%*_f, int(3)=%*_f, 6dec=%*_f", &fpi, &f3, &f3, &f31, &fpi);
// String string("Foobar");
// ext_snprintf_P(c, sizeof(c), "String 0x%08X %_s", &string, &string);
// Serial.printf("--> out=%s\n", c);
// ext_snprintf_P(c, sizeof(c), "StringFunc 0x%08X %_S", &test_string, &test_string);
// Serial.printf("--> out=%s\n", c);
// uint64_t u64 = 0x123456789ABCDEFLL;
// testVarArg2("", u64, 2, 3, 4, 5, 6, 7, 8);
// // Serial.printf("+++ ld=%ld, lld=%lld\n", 1,2,3,4);
// // testVarArg("", 1, 2, 3, 4, 5, 6, 7, 8);
// }
// tprintf("%s", 12, "14");
}
// void tprintf(const char* format) // base function
// {
// Serial.printf("%s\n", format);
// }
// template<typename T, typename... Targs>
// void tprintf(const char* format, T value, Targs... Fargs) // recursive variadic function
// {
// for ( ; *format != '\0'; format++ ) {
// if ( *format == '%' ) {
// Serial.printf("%d", (uint32_t) value);
// tprintf(format+1, Fargs...); // recursive call
// return;
// }
// Serial.printf("%s", format);
// }
// }

View File

@ -1,9 +0,0 @@
# TasmotaSerial
Implementation of software serial with hardware serial fallback library for the ESP8266
Implementation of dual UART hardware serial for the ESP32
Implementation of single UART hardware serial for the ESP32-S2
Allows for several instances to be active at the same time.
Please note that due to the fact that the ESP always have other activities ongoing, there will be some inexactness in interrupt timings. This may lead to bit errors when having heavy data traffic.

View File

@ -1,27 +0,0 @@
#include <TasmotaSerial.h>
TasmotaSerial swSer(14, 12);
void setup() {
Serial.begin(115200);
swSer.begin();
Serial.println("\nTasmota serial test started");
for (char ch = ' '; ch <= 'z'; ch++) {
swSer.write(ch);
}
swSer.println("");
}
void loop() {
while (swSer.available() > 0) {
Serial.write(swSer.read());
}
while (Serial.available() > 0) {
swSer.write(Serial.read());
}
}

View File

@ -1,27 +0,0 @@
#######################################
# Syntax Coloring Map for TasmotaSerial
# (esp8266 and esp32)
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
TasmotaSerial KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
hardwareSerial KEYWORD2
read KEYWORD2
write KEYWORD2
available KEYWORD2
flush KEYWORD2
peek KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@ -1,17 +0,0 @@
{
"name": "TasmotaSerial",
"version": "3.3.0",
"keywords": [
"serial", "io", "TasmotaSerial"
],
"description": "Implementation of software serial with hardware serial fallback for ESP8266 and ESP32.",
"repository":
{
"type": "git",
"url": "https://github.com/arendst/Tasmota/lib/TasmotaSerial"
},
"frameworks": "arduino",
"platforms": [
"espressif8266", "espressif32"
]
}

View File

@ -1,9 +0,0 @@
name=TasmotaSerial
version=3.3.0
author=Theo Arends
maintainer=Theo Arends <theo@arends.com>
sentence=Implementation of software serial with hardware serial fallback for ESP8266 and ESP32.
paragraph=
category=Signal Input/Output
url=
architectures=esp8266,esp32

View File

@ -1,430 +0,0 @@
/*
TasmotaSerial.cpp - Implementation of software serial with hardware serial fallback for Tasmota
Copyright (C) 2021 Theo Arends
This library 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/>.
*/
#include <Arduino.h>
// The Arduino standard GPIO routines are not enough,
// must use some from the Espressif SDK as well
extern "C" {
#include "gpio.h"
}
#include <TasmotaSerial.h>
#ifdef ESP8266
void IRAM_ATTR callRxRead(void *self) { ((TasmotaSerial*)self)->rxRead(); };
// As the Arduino attachInterrupt has no parameter, lists of objects
// and callbacks corresponding to each possible GPIO pins have to be defined
TasmotaSerial *tms_obj_list[16];
#endif // ESP8266
#ifdef ESP32
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
static int tasmota_serial_index = 2; // Allow UART2 and UART1 only
#elif CONFIG_IDF_TARGET_ESP32S2 // ESP32-S2
static int tasmota_serial_index = 1; // Allow UART1 only
#elif CONFIG_IDF_TARGET_ESP32C3 // ESP32-C3
static int tasmota_serial_index = 1; // Allow UART1 only
#endif
#endif // ESP32
TasmotaSerial::TasmotaSerial(int receive_pin, int transmit_pin, int hardware_fallback, int nwmode, int buffer_size) {
m_valid = false;
m_hardserial = false;
m_hardswap = false;
m_stop_bits = 1;
m_nwmode = nwmode;
serial_buffer_size = buffer_size;
m_rx_pin = receive_pin;
m_tx_pin = transmit_pin;
m_in_pos = m_out_pos = 0;
#ifdef ESP8266
if (!((isValidGPIOpin(receive_pin)) && (isValidGPIOpin(transmit_pin) || transmit_pin == 16))) {
return;
}
if (hardware_fallback && (((3 == m_rx_pin) && (1 == m_tx_pin)) || ((3 == m_rx_pin) && (-1 == m_tx_pin)) || ((-1 == m_rx_pin) && (1 == m_tx_pin)))) {
m_hardserial = true;
}
else if ((2 == hardware_fallback) && (((13 == m_rx_pin) && (15 == m_tx_pin)) || ((13 == m_rx_pin) && (-1 == m_tx_pin)) || ((-1 == m_rx_pin) && (15 == m_tx_pin)))) {
m_hardserial = true;
m_hardswap = true;
}
else {
if ((m_rx_pin < 0) && (m_tx_pin < 0)) { return; }
if (m_rx_pin > -1) {
m_buffer = (uint8_t*)malloc(serial_buffer_size);
if (m_buffer == NULL) return;
// Use getCycleCount() loop to get as exact timing as possible
m_bit_time = ESP.getCpuFreqMHz() * 1000000 / TM_SERIAL_BAUDRATE;
m_bit_start_time = m_bit_time + m_bit_time/3 - 500; // pre-compute first wait
pinMode(m_rx_pin, INPUT);
tms_obj_list[m_rx_pin] = this;
attachInterruptArg(m_rx_pin, callRxRead, this, (m_nwmode) ? CHANGE : FALLING);
}
if (m_tx_pin > -1) {
pinMode(m_tx_pin, OUTPUT);
digitalWrite(m_tx_pin, HIGH);
}
}
#endif // ESP8266
#ifdef ESP32
if (transmit_pin > 33) { return; } // GPIO34 - GPIO39 are Input only
m_hardserial = true;
#endif // ESP32
m_valid = true;
}
TasmotaSerial::~TasmotaSerial(void) {
#ifdef ESP8266
if (!m_hardserial) {
if (m_rx_pin > -1) {
detachInterrupt(m_rx_pin);
tms_obj_list[m_rx_pin] = NULL;
if (m_buffer) {
free(m_buffer);
}
}
}
#endif // ESP8266
#ifdef ESP32
TSerial->end();
tasmota_serial_index++;
#endif // ESP32
}
bool TasmotaSerial::isValidGPIOpin(int pin) {
return (pin >= -1 && pin <= 5) || (pin >= 12 && pin <= 15);
}
bool TasmotaSerial::begin(uint32_t speed, uint32_t config) {
if (!m_valid) { return false; }
if (config > 2) {
// Legacy support where software serial fakes two stop bits if either stop bits is 2 or parity is not None
m_stop_bits = ((config &0x30) >> 5) +1;
if ((1 == m_stop_bits) && (config &0x03)) {
m_stop_bits++;
}
} else {
m_stop_bits = ((config -1) &1) +1;
#ifdef ESP8266
config = (2 == m_stop_bits) ? (uint32_t)SERIAL_8N2 : (uint32_t)SERIAL_8N1;
#endif // ESP8266
#ifdef ESP32
config = (2 == m_stop_bits) ? SERIAL_8N2 : SERIAL_8N1;
#endif // ESP32
}
if (m_hardserial) {
#ifdef ESP8266
Serial.flush();
Serial.begin(speed, (SerialConfig)config);
if (m_hardswap) {
Serial.swap();
}
if (serial_buffer_size > 256) {
Serial.setRxBufferSize(serial_buffer_size);
}
#endif // ESP8266
#ifdef ESP32
if (tasmota_serial_index > 0) { // We only support UART1 and UART2 and keep UART0 for debugging
m_uart = tasmota_serial_index;
tasmota_serial_index--;
TSerial = new HardwareSerial(m_uart);
TSerial->begin(speed, config, m_rx_pin, m_tx_pin);
if (serial_buffer_size > 256) {
TSerial->setRxBufferSize(serial_buffer_size);
}
} else {
m_valid = false;
}
// Serial.printf("TSR: Using UART%d\n", m_uart);
#endif // ESP32
} else {
// Use getCycleCount() loop to get as exact timing as possible
m_bit_time = ESP.getCpuFreqMHz() * 1000000 / speed;
m_bit_start_time = m_bit_time + m_bit_time/3 - (ESP.getCpuFreqMHz() > 120 ? 700 : 500); // pre-compute first wait
m_high_speed = (speed >= 9600);
m_very_high_speed = (speed >= 50000);
}
return m_valid;
}
bool TasmotaSerial::hardwareSerial(void) {
#ifdef ESP8266
return m_hardserial;
#endif // ESP8266
#ifdef ESP32
return false; // On ESP32 do not mess with Serial0 buffers
#endif // ESP32
}
void TasmotaSerial::flush(void) {
if (m_hardserial) {
#ifdef ESP8266
Serial.flush();
#endif // ESP8266
#ifdef ESP32
TSerial->flush(); // Flushes Tx only https://github.com/espressif/arduino-esp32/pull/4263
while (TSerial->available()) { TSerial->read(); }
#endif // ESP32
} else {
m_in_pos = m_out_pos = 0;
}
}
int TasmotaSerial::peek(void) {
if (m_hardserial) {
#ifdef ESP8266
return Serial.peek();
#endif // ESP8266
#ifdef ESP32
return TSerial->peek();
#endif // ESP32
} else {
if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) return -1;
return m_buffer[m_out_pos];
}
}
int TasmotaSerial::read(void) {
if (m_hardserial) {
#ifdef ESP8266
return Serial.read();
#endif // ESP8266
#ifdef ESP32
return TSerial->read();
#endif // ESP32
} else {
if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) return -1;
uint32_t ch = m_buffer[m_out_pos];
m_out_pos = (m_out_pos +1) % serial_buffer_size;
return ch;
}
}
size_t TasmotaSerial::read(char* buffer, size_t size) {
if (m_hardserial) {
#ifdef ESP8266
return Serial.read(buffer, size);
#endif // ESP8266
#ifdef ESP32
return TSerial->read(buffer, size);
#endif // ESP32
} else {
if ((-1 == m_rx_pin) || (m_in_pos == m_out_pos)) { return 0; }
size_t count = 0;
for( ; size && (m_in_pos == m_out_pos) ; --size, ++count) {
*buffer++ = m_buffer[m_out_pos];
m_out_pos = (m_out_pos +1) % serial_buffer_size;
}
return count;
}
}
int TasmotaSerial::available(void) {
if (m_hardserial) {
#ifdef ESP8266
return Serial.available();
#endif // ESP8266
#ifdef ESP32
return TSerial->available();
#endif // ESP32
} else {
int avail = m_in_pos - m_out_pos;
if (avail < 0) avail += serial_buffer_size;
return avail;
}
}
#define TM_SERIAL_WAIT_SND { while (ESP.getCycleCount() < (wait + start)) if (!m_high_speed) optimistic_yield(1); wait += m_bit_time; } // Watchdog timeouts
#define TM_SERIAL_WAIT_SND_FAST { while (ESP.getCycleCount() < (wait + start)); wait += m_bit_time; }
#define TM_SERIAL_WAIT_RCV { while (ESP.getCycleCount() < (wait + start)); wait += m_bit_time; }
#define TM_SERIAL_WAIT_RCV_LOOP { while (ESP.getCycleCount() < (wait + start)); }
void IRAM_ATTR TasmotaSerial::_fast_write(uint8_t b) {
uint32_t wait = m_bit_time;
uint32_t start = ESP.getCycleCount();
// Start bit;
digitalWrite(m_tx_pin, LOW);
TM_SERIAL_WAIT_SND_FAST;
for (uint32_t i = 0; i < 8; i++) {
digitalWrite(m_tx_pin, (b & 1) ? HIGH : LOW);
TM_SERIAL_WAIT_SND_FAST;
b >>= 1;
}
// Stop bit(s)
digitalWrite(m_tx_pin, HIGH);
for (uint32_t i = 0; i < m_stop_bits; i++) {
TM_SERIAL_WAIT_SND_FAST;
}
}
size_t TasmotaSerial::write(uint8_t b) {
if (m_hardserial) {
#ifdef ESP8266
return Serial.write(b);
#endif // ESP8266
#ifdef ESP32
return TSerial->write(b);
#endif // ESP32
} else {
if (-1 == m_tx_pin) return 0;
if (m_high_speed) {
cli(); // Disable interrupts in order to get a clean transmit
_fast_write(b);
sei();
} else {
uint32_t wait = m_bit_time;
//digitalWrite(m_tx_pin, HIGH); // already in HIGH mode
uint32_t start = ESP.getCycleCount();
// Start bit;
digitalWrite(m_tx_pin, LOW);
TM_SERIAL_WAIT_SND;
for (uint32_t i = 0; i < 8; i++) {
digitalWrite(m_tx_pin, (b & 1) ? HIGH : LOW);
TM_SERIAL_WAIT_SND;
b >>= 1;
}
// Stop bit(s)
digitalWrite(m_tx_pin, HIGH);
// re-enable interrupts during stop bits, it's not an issue if they are longer than expected
for (uint32_t i = 0; i < m_stop_bits; i++) {
TM_SERIAL_WAIT_SND;
}
}
return 1;
}
}
void IRAM_ATTR TasmotaSerial::rxRead(void) {
if (!m_nwmode) {
int32_t loop_read = m_very_high_speed ? serial_buffer_size : 1;
// Advance the starting point for the samples but compensate for the
// initial delay which occurs before the interrupt is delivered
uint32_t wait = m_bit_start_time;
uint32_t start = ESP.getCycleCount();
while (loop_read-- > 0) { // try to receveive all consecutive bytes in a raw
uint32_t rec = 0;
for (uint32_t i = 0; i < 8; i++) {
TM_SERIAL_WAIT_RCV;
rec >>= 1;
if (digitalRead(m_rx_pin)) rec |= 0x80;
}
// Store the received value in the buffer unless we have an overflow
uint32_t next = (m_in_pos+1) % serial_buffer_size;
if (next != (int)m_out_pos) {
m_buffer[m_in_pos] = rec;
m_in_pos = next;
}
TM_SERIAL_WAIT_RCV_LOOP; // wait for stop bit
if (2 == m_stop_bits) {
wait += m_bit_time;
TM_SERIAL_WAIT_RCV_LOOP;
}
wait += m_bit_time / 4;
if (loop_read <= 0) { break; } // exit now if not very high speed or buffer full
bool start_of_next_byte = false;
for (uint32_t i = 0; i < 12; i++) {
TM_SERIAL_WAIT_RCV_LOOP; // wait for 1/4 bits
wait += m_bit_time / 4;
if (!digitalRead(m_rx_pin)) {
// this is the start bit of the next byte
wait += m_bit_time; // we have advanced in the first 1/4 of bit, and already added 1/4 of bit so we're roughly centered. Just skip start bit.
start_of_next_byte = true;
m_bit_follow_metric++;
break; // exit loop
}
}
if (!start_of_next_byte) {
break; // exit now if no sign of next byte
}
}
// Must clear this bit in the interrupt register,
// it gets set even when interrupts are disabled
GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, 1 << m_rx_pin);
} else {
uint32_t diff;
uint32_t level;
#define LASTBIT 9
GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, 1 << m_rx_pin);
level = digitalRead(m_rx_pin);
if (!level && !ss_index) {
// start condition
ss_bstart = ESP.getCycleCount() - (m_bit_time / 4);
ss_byte = 0;
ss_index++;
//digitalWrite(1, LOW);
} else {
// now any bit changes go here
// calc bit number
diff = (ESP.getCycleCount() - ss_bstart) / m_bit_time;
//digitalWrite(1, level);
if (!level && diff > LASTBIT) {
// start bit of next byte, store and restart
// leave irq at change
for (uint32_t i = ss_index; i <= LASTBIT; i++) {
ss_byte |= (1 << i);
}
//stobyte(0,ssp->ss_byte>>1);
uint32_t next = (m_in_pos + 1) % serial_buffer_size;
if (next != (uint32_t)m_out_pos) {
m_buffer[m_in_pos] = ss_byte >> 1;
m_in_pos = next;
}
ss_bstart = ESP.getCycleCount() - (m_bit_time / 4);
ss_byte = 0;
ss_index = 1;
return;
}
if (diff >= LASTBIT) {
// bit zero was 0,
//stobyte(0,ssp->ss_byte>>1);
uint32_t next = (m_in_pos + 1) % serial_buffer_size;
if (next != (uint32_t)m_out_pos) {
m_buffer[m_in_pos] = ss_byte >> 1;
m_in_pos = next;
}
ss_byte = 0;
ss_index = 0;
} else {
// shift in
for (uint32_t i = ss_index; i < diff; i++) {
if (!level) ss_byte |= (1 << i);
}
ss_index = diff;
}
}
}
}

View File

@ -1,97 +0,0 @@
/*
TasmotaSerial.h - Implementation of software serial with hardware serial fallback for Tasmota
Copyright (C) 2021 Theo Arends
This library 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 TasmotaSerial_h
#define TasmotaSerial_h
/*********************************************************************************************\
* TasmotaSerial supports up to 115200 baud with default buffer size of 64 bytes using optional no iram
*
* Based on EspSoftwareSerial v3.4.3 by Peter Lerup (https://github.com/plerup/espsoftwareserial)
\*********************************************************************************************/
#define TM_SERIAL_BAUDRATE 9600 // Default baudrate
#define TM_SERIAL_BUFFER_SIZE 64 // Receive buffer size
#include <inttypes.h>
#include <Stream.h>
#ifdef ESP32
#include <HardwareSerial.h>
#endif
class TasmotaSerial : public Stream {
public:
TasmotaSerial(int receive_pin, int transmit_pin, int hardware_fallback = 0, int nwmode = 0, int buffer_size = TM_SERIAL_BUFFER_SIZE);
virtual ~TasmotaSerial();
bool begin(uint32_t speed = TM_SERIAL_BAUDRATE, uint32_t config = SERIAL_8N1);
bool hardwareSerial(void);
int peek(void);
size_t write(uint8_t byte) override;
int read(void) override;
size_t read(char* buffer, size_t size);
int available(void) override;
void flush(void) override;
void rxRead(void);
uint32_t getLoopReadMetric(void) const { return m_bit_follow_metric; }
#ifdef ESP32
uint32_t getUart(void) const { return m_uart; }
#endif
using Print::write;
private:
bool isValidGPIOpin(int pin);
size_t txWrite(uint8_t byte);
// Member variables
int m_rx_pin;
int m_tx_pin;
uint32_t m_stop_bits;
uint32_t ss_byte;
uint32_t ss_bstart;
uint32_t ss_index;
uint32_t m_bit_time;
uint32_t m_bit_start_time;
uint32_t m_bit_follow_metric = 0;
uint32_t m_in_pos;
uint32_t m_out_pos;
uint32_t serial_buffer_size;
bool m_valid;
bool m_nwmode;
bool m_hardserial;
bool m_hardswap;
bool m_high_speed = false;
bool m_very_high_speed = false; // above 100000 bauds
uint8_t *m_buffer;
void _fast_write(uint8_t b); // IRAM minimized version
#ifdef ESP32
HardwareSerial *TSerial;
int m_uart = 0;
#endif
};
#endif // TasmotaSerial_h

View File

@ -1,7 +0,0 @@
name=UdpListener
version=1.0
author=Ivan Grokhotkov, Stephan Hadinger
maintainer=Stephan <stephan.hadinger@gmail.com>
sentence=UdpListener optimized for static and limite memory allocation, to reduce memory footprint of receiving SSDP request, as a replacement for WifiUdp.
paragraph=This class only handles receiving UDP Multicast packets. For sending packets, use WifiUdp.
architectures=esp8266,esp32

View File

@ -1,209 +0,0 @@
/*
UdpListener.h - webserver for Tasmota
Copyright (C) 2021 Theo Arends & Stephan Hadinger
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/>.@
*/
// adapted from:
/*
UdpContext.h - UDP connection handling on top of lwIP
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* This is a stripped down version of Udp handler to avoid overflowing
* memory when lots of multicast SSDP packets arrive.
* The pbuf is freed immediately upon arrival of the packet.
*
* Packet data are kept in a statically area in RAM and keeps
* only the <n> first bytes (200 by default) of each packet.
* The number of packets treated is limited (3 by default), any
* new packet arriving is dropped.
*
* This class does only receiving multicast packets for LWIP2
*/
#ifndef UDPMULTICASTLISTENER_H
#define UDPMULTICASTLISTENER_H
#ifdef ESP8266
// #include <Arduino.h>
extern "C" {
#include <lwip/udp.h>
#include <lwip/igmp.h>
}
template <size_t PACKET_SIZE>
struct UdpPacket {
IPAddress srcaddr;
IPAddress dstaddr;
int16_t srcport;
netif* input_netif;
size_t len;
uint8_t buf[PACKET_SIZE];
};
template <size_t PACKET_SIZE>
class UdpListener
{
public:
typedef std::function<void(void)> rxhandler_t;
UdpListener(size_t packet_number)
: _pcb(0)
, _packet_number(packet_number)
, _buffers(nullptr)
, _udp_packets(0)
, _udp_ready(false)
, _udp_index(0)
{
_packet_number = packet_number;
_buffers = new UdpPacket<PACKET_SIZE>[_packet_number];
_pcb = udp_new();
}
~UdpListener()
{
udp_remove(_pcb);
_pcb = 0;
delete[] _buffers;
_buffers = nullptr;
}
void reset(void)
{
_udp_packets = 0;
_udp_index = 0;
}
bool listen(const IPAddress& addr, uint16_t port)
{
if (!_buffers) { return false; }
udp_recv(_pcb, &_s_recv, (void *) this);
err_t err = udp_bind(_pcb, addr, port);
return err == ERR_OK;
}
void disconnect()
{
udp_disconnect(_pcb);
}
bool next()
{
if (!_buffers) { return false; }
if (_udp_packets > 0) {
if (!_udp_ready) {
// we just consume the first packet
_udp_ready = true;
} else {
_udp_packets--;
_udp_index = (_udp_index + 1) % _packet_number; // advance to next buffer index in ring
if (_udp_packets == 0) {
_udp_ready = false;
}
}
} else {
_udp_ready = false;
}
return _udp_ready;
}
UdpPacket<PACKET_SIZE> * read(void)
{
if (!_buffers) { return nullptr; }
if (_udp_ready) { // we have a packet ready to consume
return &_buffers[_udp_index];
} else {
return nullptr;
}
}
private:
void _recv(udp_pcb *upcb, pbuf *pb,
const ip_addr_t *srcaddr, u16_t srcport)
{
if (!_buffers) { pbuf_free(pb); return; }
// Serial.printf(">>> _recv: _udp_packets = %d, _udp_index = %d, tot_len = %d\n", _udp_packets, _udp_index, pb->tot_len);
if (_udp_packets >= _packet_number) {
// we don't have slots anymore, drop packet
pbuf_free(pb);
return;
}
uint8_t next_slot = (_udp_index + _udp_packets) % _packet_number;
size_t packet_len = pb->tot_len;
if (packet_len > PACKET_SIZE) { packet_len = PACKET_SIZE; }
uint8_t * dst = &_buffers[next_slot].buf[0];
void* buf = pbuf_get_contiguous(pb, dst, PACKET_SIZE, packet_len, 0);
if (buf) {
if (buf != dst)
memcpy(dst, buf, packet_len);
_buffers[next_slot].len = packet_len;
_buffers[next_slot].srcaddr = srcaddr;
_buffers[next_slot].dstaddr = ip_current_dest_addr();
_buffers[next_slot].srcport = srcport;
_buffers[next_slot].input_netif = ip_current_input_netif();
_udp_packets++; // we have one packet ready
}
pbuf_free(pb); // free memory immediately
}
static void _s_recv(void *arg,
udp_pcb *upcb, pbuf *p,
const ip_addr_t *srcaddr, u16_t srcport)
{
reinterpret_cast<UdpListener*>(arg)->_recv(upcb, p, srcaddr, srcport);
}
private:
udp_pcb* _pcb;
uint8_t _packet_number;
UdpPacket<PACKET_SIZE> * _buffers;
// how many packets are ready.
int8_t _udp_packets; // number of udp packets ready to consume
bool _udp_ready; // is a packet currenlty consumed after a call to next()
// ring buffer ranges from 0..(_packet_number-1)
int8_t _udp_index; // current index in the ring buffer
};
#endif // ESP8266
#endif //UDPMULTICASTLISTENER_H

View File

@ -1,165 +0,0 @@
/*
* Copyright (C) 2019 Siara Logics (cc)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Arundale R.
*
*/
// Pre-compute c_95[] and l_95[]
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdint.h>
typedef unsigned char byte;
enum {SHX_SET1 = 0, SHX_SET1A, SHX_SET1B, SHX_SET2, SHX_SET3, SHX_SET4, SHX_SET4A};
char us_vcodes[] = {0, 2, 3, 4, 10, 11, 12, 13, 14, 30, 31};
char us_vcode_lens[] = {2, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5};
char us_sets[][11] =
{{ 0, ' ', 'e', 0, 't', 'a', 'o', 'i', 'n', 's', 'r'},
{ 0, 'l', 'c', 'd', 'h', 'u', 'p', 'm', 'b', 'g', 'w'},
{'f', 'y', 'v', 'k', 'q', 'j', 'x', 'z', 0, 0, 0},
{ 0, '9', '0', '1', '2', '3', '4', '5', '6', '7', '8'},
{'.', ',', '-', '/', '?', '+', ' ', '(', ')', '$', '@'},
{';', '#', ':', '<', '^', '*', '"', '{', '}', '[', ']'},
{'=', '%', '\'', '>', '&', '_', '!', '\\', '|', '~', '`'}};
// {{ 0, ' ', 'e', 0, 't', 'a', 'o', 'i', 'n', 's', 'r'},
// { 0, 'l', 'c', 'd', 'h', 'u', 'p', 'm', 'b', 'g', 'w'},
// {'f', 'y', 'v', 'k', 'q', 'j', 'x', 'z', 0, 0, 0},
// { 0, '9', '0', '1', '2', '3', '4', '5', '6', '7', '8'},
// {'.', ',', '-', '/', '=', '+', ' ', '(', ')', '$', '%'},
// {'&', ';', ':', '<', '>', '*', '"', '{', '}', '[', ']'},
// {'@', '?', '\'', '^', '#', '_', '!', '\\', '|', '~', '`'}};
unsigned int c_95[95] ;
unsigned char l_95[95] ;
void init_coder() {
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 11; j++) {
char c = us_sets[i][j];
if (c != 0 && c != 32) {
int ascii = c - 32;
//int prev_code = c_95[ascii];
//int prev_code_len = l_95[ascii];
switch (i) {
case SHX_SET1: // just us_vcode
c_95[ascii] = (us_vcodes[j] << (16 - us_vcode_lens[j]));
l_95[ascii] = us_vcode_lens[j];
//checkPreus_vcodes(c, prev_code, prev_code_len, c_95[ascii], l_95[ascii]);
if (c >= 'a' && c <= 'z') {
ascii -= ('a' - 'A');
//prev_code = c_95[ascii];
//prev_code_len = l_95[ascii];
c_95[ascii] = (2 << 12) + (us_vcodes[j] << (12 - us_vcode_lens[j]));
l_95[ascii] = 4 + us_vcode_lens[j];
}
break;
case SHX_SET1A: // 000 + us_vcode
c_95[ascii] = 0 + (us_vcodes[j] << (13 - us_vcode_lens[j]));
l_95[ascii] = 3 + us_vcode_lens[j];
//checkPreus_vcodes(c, prev_code, prev_code_len, c_95[ascii], l_95[ascii]);
if (c >= 'a' && c <= 'z') {
ascii -= ('a' - 'A');
//prev_code = c_95[ascii];
//prev_code_len = l_95[ascii];
c_95[ascii] = (2 << 12) + 0 + (us_vcodes[j] << (9 - us_vcode_lens[j]));
l_95[ascii] = 4 + 3 + us_vcode_lens[j];
}
break;
case SHX_SET1B: // 00110 + us_vcode
c_95[ascii] = (6 << 11) + (us_vcodes[j] << (11 - us_vcode_lens[j]));
l_95[ascii] = 5 + us_vcode_lens[j];
//checkPreus_vcodes(c, prev_code, prev_code_len, c_95[ascii], l_95[ascii]);
if (c >= 'a' && c <= 'z') {
ascii -= ('a' - 'A');
//prev_code = c_95[ascii];
//prev_code_len = l_95[ascii];
c_95[ascii] = (2 << 12) + (6 << 7) + (us_vcodes[j] << (7 - us_vcode_lens[j]));
l_95[ascii] = 4 + 5 + us_vcode_lens[j];
}
break;
case SHX_SET2: // 0011100 + us_vcode
c_95[ascii] = (28 << 9) + (us_vcodes[j] << (9 - us_vcode_lens[j]));
l_95[ascii] = 7 + us_vcode_lens[j];
break;
case SHX_SET3: // 0011101 + us_vcode
c_95[ascii] = (29 << 9) + (us_vcodes[j] << (9 - us_vcode_lens[j]));
l_95[ascii] = 7 + us_vcode_lens[j];
break;
case SHX_SET4: // 0011110 + us_vcode
c_95[ascii] = (30 << 9) + (us_vcodes[j] << (9 - us_vcode_lens[j]));
l_95[ascii] = 7 + us_vcode_lens[j];
break;
case SHX_SET4A: // 0011111 + us_vcode
c_95[ascii] = (31 << 9) + (us_vcodes[j] << (9 - us_vcode_lens[j]));
l_95[ascii] = 7 + us_vcode_lens[j];
}
//checkPreus_vcodes(c, prev_code, prev_code_len, c_95[ascii], l_95[ascii]);
}
}
}
c_95[0] = 16384;
l_95[0] = 3;
}
int main(int argv, char *args[]) {
init_coder();
printf("uint16_t c_95[95] PROGMEM = {");
for (uint8_t i = 0; i<95; i++) {
if (i) { printf(", "); }
printf("0x%04X", c_95[i]);
}
printf(" };\n");
printf("uint8_t l_95[95] PROGMEM = {");
for (uint8_t i = 0; i<95; i++) {
if (i) { printf(", "); }
printf("%6d", l_95[i]);
}
printf(" };\n");
printf("\n\n");
printf("uint16_t c_95[95] PROGMEM = {");
for (uint8_t i = 0; i<95; i++) {
if (i) { printf(", "); }
printf("%5d", c_95[i]);
}
printf(" };\n");
printf("uint8_t l_95[95] PROGMEM = {");
for (uint8_t i = 0; i<95; i++) {
if (i) { printf(", "); }
printf("%5d", l_95[i]);
}
printf(" };\n");
printf("uint16_t cl_95[95] PROGMEM = {");
for (uint8_t i = 0; i<95; i++) {
if (i) { printf(", "); }
printf("0x%04X + %2d", c_95[i], l_95[i]);
}
printf(" };\n");
}

View File

@ -1,8 +0,0 @@
name=Unishox Compressor Decompressor highly customized and optimized for ESP8266 and Tasmota
version=1.0
author=Arundale Ramanathan, Stephan Hadinger
maintainer=Arun <arun@siara.cc>, Stephan <stephan.hadinger@gmail.com>
sentence=Unishox compression for Tasmota Rules
paragraph=It is based on Unishox hybrid encoding technique. This version has specific Unicode code removed for size.
url=https://github.com/siara-cc/Unishox
architectures=esp8266,esp32

View File

@ -1,521 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python Class for compressing short strings.
This class contains a highly modified and optimized version of Unishox
for Tasmota converted in C ported to Pyhton3.
It was basically developed to individually compress and decompress small strings
(see https://github.com/siara-cc/Unishox)
In general compression utilities such as zip, gzip do not compress short strings
well and often expand them. They also use lots of memory which makes them unusable
in constrained environments like Arduino.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class Unishox:
"""
This is a highly modified and optimized version of Unishox
for Tasmota, aimed at compressing `Rules` which are typically
short strings from 50 to 500 bytes.
@author Stephan Hadinger
@revised Norbert Richter
"""
# pylint: disable=bad-continuation,bad-whitespace,line-too-long
#cl_95 = [0x4000 + 3, 0x3F80 + 11, 0x3D80 + 11, 0x3C80 + 10, 0x3BE0 + 12, 0x3E80 + 10, 0x3F40 + 11, 0x3EC0 + 10, 0x3BA0 + 11, 0x3BC0 + 11, 0x3D60 + 11, 0x3B60 + 11, 0x3A80 + 10, 0x3AC0 + 10, 0x3A00 + 9, 0x3B00 + 10, 0x38C0 + 10, 0x3900 + 10, 0x3940 + 11, 0x3960 + 11, 0x3980 + 11, 0x39A0 + 11, 0x39C0 + 11, 0x39E0 + 12, 0x39F0 + 12, 0x3880 + 10, 0x3CC0 + 10, 0x3C00 + 9, 0x3D00 + 10, 0x3E00 + 9, 0x3F00 + 10, 0x3B40 + 11, 0x3BF0 + 12, 0x2B00 + 8, 0x21C0 + 11, 0x20C0 + 10, 0x2100 + 10, 0x2600 + 7, 0x2300 + 11, 0x21E0 + 12, 0x2140 + 11, 0x2D00 + 8, 0x2358 + 13, 0x2340 + 12, 0x2080 + 10, 0x21A0 + 11, 0x2E00 + 8, 0x2C00 + 8, 0x2180 + 11, 0x2350 + 13, 0x2F80 + 9, 0x2F00 + 9, 0x2A00 + 8, 0x2160 + 11, 0x2330 + 12, 0x21F0 + 12, 0x2360 + 13, 0x2320 + 12, 0x2368 + 13, 0x3DE0 + 12, 0x3FA0 + 11, 0x3DF0 + 12, 0x3D40 + 11, 0x3F60 + 11, 0x3FF0 + 12, 0xB000 + 4, 0x1C00 + 7, 0x0C00 + 6, 0x1000 + 6, 0x6000 + 3, 0x3000 + 7, 0x1E00 + 8, 0x1400 + 7, 0xD000 + 4, 0x3580 + 9, 0x3400 + 8, 0x0800 + 6, 0x1A00 + 7, 0xE000 + 4, 0xC000 + 4, 0x1800 + 7, 0x3500 + 9, 0xF800 + 5, 0xF000 + 5, 0xA000 + 4, 0x1600 + 7, 0x3300 + 8, 0x1F00 + 8, 0x3600 + 9, 0x3200 + 8, 0x3680 + 9, 0x3DA0 + 11, 0x3FC0 + 11, 0x3DC0 + 11, 0x3FE0 + 12]
cl_95 = [0x4000 + 3, 0x3F80 + 11, 0x3D80 + 11, 0x3C80 + 10, 0x3BE0 + 12, 0x3E80 + 10, 0x3F40 + 11, 0x3EC0 + 10, 0x3BA0 + 11, 0x3BC0 + 11, 0x3D60 + 11, 0x3B60 + 11, 0x3A80 + 10, 0x3AC0 + 10, 0x3A00 + 9, 0x3B00 + 10, 0x38C0 + 10, 0x3900 + 10, 0x3940 + 11, 0x3960 + 11, 0x3980 + 11, 0x39A0 + 11, 0x39C0 + 11, 0x39E0 + 12, 0x39F0 + 12, 0x3880 + 10, 0x3CC0 + 10, 0x3C00 + 9, 0x3D00 + 10, 0x3E00 + 9, 0x3F00 + 10, 0x3B40 + 11, 0x3BF0 + 12, 0x2B00 + 8, 0x21C0 + 11, 0x20C0 + 10, 0x2100 + 10, 0x2600 + 7, 0x2300 + 11, 0x21E0 + 12, 0x2140 + 11, 0x2D00 + 8, 0x46B0 + 13, 0x2340 + 12, 0x2080 + 10, 0x21A0 + 11, 0x2E00 + 8, 0x2C00 + 8, 0x2180 + 11, 0x46A0 + 13, 0x2F80 + 9, 0x2F00 + 9, 0x2A00 + 8, 0x2160 + 11, 0x2330 + 12, 0x21F0 + 12, 0x46C0 + 13, 0x2320 + 12, 0x46D0 + 13, 0x3DE0 + 12, 0x3FA0 + 11, 0x3DF0 + 12, 0x3D40 + 11, 0x3F60 + 11, 0x3FF0 + 12, 0xB000 + 4, 0x1C00 + 7, 0x0C00 + 6, 0x1000 + 6, 0x6000 + 3, 0x3000 + 7, 0x1E00 + 8, 0x1400 + 7, 0xD000 + 4, 0x3580 + 9, 0x3400 + 8, 0x0800 + 6, 0x1A00 + 7, 0xE000 + 4, 0xC000 + 4, 0x1800 + 7, 0x3500 + 9, 0xF800 + 5, 0xF000 + 5, 0xA000 + 4, 0x1600 + 7, 0x3300 + 8, 0x1F00 + 8, 0x3600 + 9, 0x3200 + 8, 0x3680 + 9, 0x3DA0 + 11, 0x3FC0 + 11, 0x3DC0 + 11, 0x3FE0 + 12]
# enum {SHX_STATE_1 = 1, SHX_STATE_2}; // removed Unicode state
SHX_STATE_1 = 1
SHX_STATE_2 = 2
SHX_SET1 = 0
SHX_SET1A = 1
SHX_SET1B = 2
SHX_SET2 = 3
sets = [['\0', ' ', 'e', '\0', 't', 'a', 'o', 'i', 'n', 's', 'r'],
['\0', 'l', 'c', 'd', 'h', 'u', 'p', 'm', 'b', 'g', 'w'],
['f', 'y', 'v', 'k', 'q', 'j', 'x', 'z', '\0', '\0', '\0'],
['\0', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8'],
['.', ',', '-', '/', '?', '+', ' ', '(', ')', '$', '@'],
[';', '#', ':', '<', '^', '*', '"', '{', '}', '[', ']'],
['=', '%', '\'', '>', '&', '_', '!', '\\', '|', '~', '`']]
us_vcode = [2 + (0 << 3), 3 + (3 << 3), 3 + (1 << 3), 4 + (6 << 3), 0,
# 5, 6, 7, 8, 9, 10
4 + (4 << 3), 3 + (2 << 3), 4 + (8 << 3), 0, 0, 0,
# 11, 12, 13, 14, 15
4 + (7 << 3), 0, 4 + (5 << 3), 0, 5 + (9 << 3),
# 16, 17, 18, 19, 20, 21, 22, 23
0, 0, 0, 0, 0, 0, 0, 0,
# 24, 25, 26, 27, 28, 29, 30, 31
0, 0, 0, 0, 0, 0, 0, 5 + (10 << 3) ]
# 0, 1, 2, 3, 4, 5, 6, 7,
us_hcode = [1 + (1 << 3), 2 + (0 << 3), 0, 3 + (2 << 3), 0, 0, 0, 5 + (3 << 3),
# 8, 9, 10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 5 + (5 << 3),
# 16, 17, 18, 19, 20, 21, 22, 23
0, 0, 0, 0, 0, 0, 0, 5 + (4 << 3),
# 24, 25, 26, 27, 28, 29, 30, 31
0, 0, 0, 0, 0, 0, 0, 5 + (6 << 3) ]
# pylint: enable=bad-continuation,bad-whitespace
ESCAPE_MARKER = 0x2A
TERM_CODE = 0x37C0
# TERM_CODE_LEN = 10
DICT_CODE = 0x0000
DICT_CODE_LEN = 5
#DICT_OTHER_CODE = 0x0000
#DICT_OTHER_CODE_LEN = 6
RPT_CODE_TASMOTA = 0x3780
RPT_CODE_TASMOTA_LEN = 10
BACK2_STATE1_CODE = 0x2000
BACK2_STATE1_CODE_LEN = 4
#BACK_FROM_UNI_CODE = 0xFE00
#BACK_FROM_UNI_CODE_LEN = 8
LF_CODE = 0x3700
LF_CODE_LEN = 9
TAB_CODE = 0x2400
TAB_CODE_LEN = 7
ALL_UPPER_CODE = 0x2200
ALL_UPPER_CODE_LEN = 8
SW2_STATE2_CODE = 0x3800
SW2_STATE2_CODE_LEN = 7
ST2_SPC_CODE = 0x3B80
ST2_SPC_CODE_LEN = 11
BIN_CODE_TASMOTA = 0x8000
BIN_CODE_TASMOTA_LEN = 3
NICE_LEN = 5
mask = [0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF]
# pylint: disable=missing-function-docstring,invalid-name
# Input
# out = bytearray
def append_bits(self, out, ol, code, clen, state):
#print("Append bits {ol} {code} {clen} {state}".format(ol=ol, code=code, clen=clen, state=state))
if state == self.SHX_STATE_2:
# remove change state prefix
if (code >> 9) == 0x1C:
code <<= 7
clen -= 7
while clen > 0:
cur_bit = ol % 8
blen = 8 if (clen > 8) else clen
a_byte = (code >> 8) & self.mask[blen - 1]
#print("append_bits a_byte {ab} blen {blen}".format(ab=a_byte,blen=blen))
a_byte >>= cur_bit
if blen + cur_bit > 8:
blen = (8 - cur_bit)
if cur_bit == 0:
out[ol // 8] = a_byte
else:
out[ol // 8] |= a_byte
code <<= blen
ol += blen
if 0 == ol % 8: # pylint: disable=misplaced-comparison-constant
# we completed a full byte
last_c = out[(ol // 8) - 1]
if last_c in (0, self.ESCAPE_MARKER):
out[ol // 8] = 1 + last_c # increment to 0x01 or 0x2B
out[(ol // 8) -1] = self.ESCAPE_MARKER # replace old value with marker
ol += 8 # add one full byte
clen -= blen
return ol
codes = [0x82, 0xC3, 0xE5, 0xED, 0xF5] # pylint: disable=bad-whitespace
bit_len = [ 5, 7, 9, 12, 16] # pylint: disable=bad-whitespace
def encodeCount(self, out, ol, count):
#print("encodeCount ol = {ol}, count = {count}".format(ol=ol, count=count))
till = 0
base = 0
for i in range(len(self.bit_len)):
bit_len_i = self.bit_len[i]
till += (1 << bit_len_i)
if count < till:
codes_i = self.codes[i]
ol = self.append_bits(out, ol, (codes_i & 0xF8) << 8, codes_i & 0x07, 1)
#print("encodeCount append_bits ol = {ol}, code = {code}, len = {len}".format(ol=ol,code=(codes_i & 0xF8) << 8,len=codes_i & 0x07))
ol = self.append_bits(out, ol, (count - base) << (16 - bit_len_i), bit_len_i, 1)
#print("encodeCount append_bits ol = {ol}, code = {code}, len = {len}".format(ol=ol,code=(count - base) << (16 - bit_len_i),len=bit_len_i))
return ol
base = till
return ol
# Returns (int, ol, state, is_all_upper)
def matchOccurance(self, inn, len_, l_, out, ol, state, is_all_upper):
# int j, k;
longest_dist = 0
longest_len = 0
#for (j = l_ - self.NICE_LEN; j >= 0; j--) {
j = l_ - self.NICE_LEN
while j >= 0:
k = l_
#for (k = l_; k < len && j + k - l_ < l_; k++) {
while k < len_ and j + k - l_ < l_:
if inn[k] != inn[j + k - l_]:
break
k += 1
if k - l_ > self.NICE_LEN - 1:
match_len = k - l_ - self.NICE_LEN
match_dist = l_ - j - self.NICE_LEN + 1
if match_len > longest_len:
longest_len = match_len
longest_dist = match_dist
j -= 1
if longest_len:
#print("longest_len {ll}".format(ll=longest_len))
#ol_save = ol
if state == self.SHX_STATE_2 or is_all_upper:
is_all_upper = 0
state = self.SHX_STATE_1
ol = self.append_bits(out, ol, self.BACK2_STATE1_CODE, self.BACK2_STATE1_CODE_LEN, state)
ol = self.append_bits(out, ol, self.DICT_CODE, self.DICT_CODE_LEN, 1)
ol = self.encodeCount(out, ol, longest_len)
ol = self.encodeCount(out, ol, longest_dist)
#print("longest_len {ll} longest_dist {ld} ol {ols}-{ol}".format(ll=longest_len, ld=longest_dist, ol=ol, ols=ol_save))
l_ += longest_len + self.NICE_LEN
l_ -= 1
return l_, ol, state, is_all_upper
return -l_, ol, state, is_all_upper
def compress(self, inn, len_, out, len_out):
ol = 0
state = self.SHX_STATE_1
is_all_upper = 0
l = 0
while l < len_:
# for (l=0; l<len_; l++) {
c_in = inn[l]
if l and l < len_ - 4:
if c_in == inn[l - 1] and c_in == inn[l + 1] and c_in == inn[l + 2] and c_in == inn[l + 3]:
rpt_count = l + 4
while rpt_count < len_ and inn[rpt_count] == c_in:
rpt_count += 1
rpt_count -= l
if state == self.SHX_STATE_2 or is_all_upper:
is_all_upper = 0
state = self.SHX_STATE_1
ol = self.append_bits(out, ol, self.BACK2_STATE1_CODE, self.BACK2_STATE1_CODE_LEN, state) # back to lower case and Set1
ol = self.append_bits(out, ol, self.RPT_CODE_TASMOTA, self.RPT_CODE_TASMOTA_LEN, 1) # reusing CRLF for RPT
ol = self.encodeCount(out, ol, rpt_count - 4)
l += rpt_count
#l -= 1
continue
if l < (len_ - self.NICE_LEN + 1):
#l_old = l
(l, ol, state, is_all_upper) = self.matchOccurance(inn, len_, l, out, ol, state, is_all_upper)
if l > 0:
#print("matchOccurance l = {l} l_old = {lo}".format(l=l,lo=l_old))
l += 1 # for loop
continue
l = -l
if state == self.SHX_STATE_2: # if Set2
if ord(' ') <= c_in <= ord('@') or ord('[') <= c_in <= ord('`') or ord('{') <= c_in <= ord('~'):
pass
else:
state = self.SHX_STATE_1 # back to Set1 and lower case
ol = self.append_bits(out, ol, self.BACK2_STATE1_CODE, self.BACK2_STATE1_CODE_LEN, state)
is_upper = 0
if ord('A') <= c_in <= ord('Z'):
is_upper = 1
else:
if is_all_upper:
is_all_upper = 0
ol = self.append_bits(out, ol, self.BACK2_STATE1_CODE, self.BACK2_STATE1_CODE_LEN, state)
if 32 <= c_in <= 126:
if is_upper and not is_all_upper:
ll = l+5
# for (ll=l+5; ll>=l && ll<len_; ll--) {
while l <= ll < len_:
if inn[ll] < ord('A') or inn[ll] > ord('Z'):
break
ll -= 1
if ll == l-1:
ol = self.append_bits(out, ol, self.ALL_UPPER_CODE, self.ALL_UPPER_CODE_LEN, state) # CapsLock
is_all_upper = 1
if state == self.SHX_STATE_1 and ord('0') <= c_in <= ord('9'):
ol = self.append_bits(out, ol, self.SW2_STATE2_CODE, self.SW2_STATE2_CODE_LEN, state) # Switch to sticky Set2
state = self.SHX_STATE_2
c_in -= 32
if is_all_upper and is_upper:
c_in += 32
if c_in == 0 and state == self.SHX_STATE_2:
ol = self.append_bits(out, ol, self.ST2_SPC_CODE, self.ST2_SPC_CODE_LEN, state) # space from Set2 ionstead of Set1
else:
# ol = self.append_bits(out, ol, pgm_read_word(&c_95[c_in]), pgm_read_byte(&l_95[c_in]), state); // original version with c/l in split arrays
cl = self.cl_95[c_in]
cl_code = cl & 0xFFF0
cl_len = cl & 0x000F
if cl_len == 13:
cl_code = cl_code >> 1
ol = self.append_bits(out, ol, cl_code, cl_len, state)
elif c_in == 10:
ol = self.append_bits(out, ol, self.LF_CODE, self.LF_CODE_LEN, state) # LF
elif c_in == '\t':
ol = self.append_bits(out, ol, self.TAB_CODE, self.TAB_CODE_LEN, state) # TAB
else:
ol = self.append_bits(out, ol, self.BIN_CODE_TASMOTA, self.BIN_CODE_TASMOTA_LEN, state) # Binary, we reuse the Unicode marker which 3 bits instead of 9
ol = self.encodeCount(out, ol, (255 - c_in) & 0xFF)
# check that we have some headroom in the output buffer
if ol // 8 >= len_out - 4:
return -1 # we risk overflow and crash
l += 1
bits = ol % 8
if bits:
ol = self.append_bits(out, ol, self.TERM_CODE, 8 - bits, 1) # 0011 0111 1100 0000 TERM = 0011 0111 11
return (ol + 7) // 8
# return ol // 8 + 1 if (ol%8) else 0
def getBitVal(self, inn, bit_no, count):
c_in = inn[bit_no >> 3]
if bit_no >> 3 and self.ESCAPE_MARKER == inn[(bit_no >> 3) - 1]:
c_in -= 1
r = 1 << count if (c_in & (0x80 >> (bit_no % 8))) else 0
#print("getBitVal r={r}".format(r=r))
return r
# Returns:
# 0..11
# or -1 if end of stream
def getCodeIdx(self, code_type, inn, len_, bit_no_p):
code = 0
count = 0
while count < 5:
if bit_no_p >= len_:
return -1, bit_no_p
# detect marker
if self.ESCAPE_MARKER == inn[bit_no_p >> 3]:
bit_no_p += 8 # skip marker
if bit_no_p >= len_:
return -1, bit_no_p
code += self.getBitVal(inn, bit_no_p, count)
bit_no_p += 1
count += 1
code_type_code = code_type[code]
if code_type_code and (code_type_code & 0x07) == count:
#print("getCodeIdx = {r}".format(r=code_type_code >> 3))
return code_type_code >> 3, bit_no_p
#print("getCodeIdx not found = {r}".format(r=1))
return 1, bit_no_p
def getNumFromBits(self, inn, bit_no_p, count):
ret = 0
while count:
count -= 1
if self.ESCAPE_MARKER == inn[bit_no_p >> 3]:
bit_no_p += 8 # skip marker
ret += self.getBitVal(inn, bit_no_p, count)
bit_no_p += 1
# print("getNumFromBits = {r}".format(r=ret))
return ret, bit_no_p
def readCount(self, inn, bit_no_p, len_):
(idx, bit_no_p) = self.getCodeIdx(self.us_hcode, inn, len_, bit_no_p)
if idx >= 1:
idx -= 1 # we skip v = 1 (code '0') since we no more accept 2 bits encoding
if idx >= 5 or idx < 0:
return 0, bit_no_p # unsupported or end of stream
till = 0
bit_len_idx = 0
base = 0
#for (uint32_t i = 0; i <= idx; i++) {
i = 0
while i <= idx:
# for i in range(idx):
base = till
bit_len_idx = self.bit_len[i]
till += (1 << bit_len_idx)
i += 1
(count, bit_no_p) = self.getNumFromBits(inn, bit_no_p, bit_len_idx)
count = count + base
#print("readCount getNumFromBits = {count} ({bl})".format(count=count,bl=bit_len_idx))
return count, bit_no_p
def decodeRepeat(self, inn, len_, out, ol, bit_no):
#print("decodeRepeat Enter")
(dict_len, bit_no) = self.readCount(inn, bit_no, len_)
dict_len += self.NICE_LEN
(dist, bit_no) = self.readCount(inn, bit_no, len_)
dist += self.NICE_LEN - 1
#memcpy(out + ol, out + ol - dist, dict_len);
i = 0
while i < dict_len:
#for i in range(dict_len):
out[ol + i] = out[ol - dist + i]
i += 1
ol += dict_len
return ol, bit_no
def decompress(self, inn, len_, out, len_out):
ol = 0
bit_no = 0
dstate = self.SHX_SET1
is_all_upper = 0
len_ <<= 3 # *8, len_ in bits
out[ol] = 0
while bit_no < len_:
c = 0
is_upper = is_all_upper
(v, bit_no) = self.getCodeIdx(self.us_vcode, inn, len_, bit_no) # read vCode
#print("bit_no {b}. v = {v}".format(b=bit_no,v=v))
if v < 0:
break # end of stream
h = dstate # Set1 or Set2
if v == 0: # Switch which is common to Set1 and Set2, first entry
(h, bit_no) = self.getCodeIdx(self.us_hcode, inn, len_, bit_no) # read hCode
#print("bit_no {b}. h = {h}".format(b=bit_no,h=h))
if h < 0:
break # end of stream
if h == self.SHX_SET1: # target is Set1
if dstate == self.SHX_SET1: # Switch from Set1 to Set1 us UpperCase
if is_all_upper: # if CapsLock, then back to LowerCase
is_upper = 0
is_all_upper = 0
continue
(v, bit_no) = self.getCodeIdx(self.us_vcode, inn, len_, bit_no) # read again vCode
if v < 0:
break # end of stream
if v == 0:
(h, bit_no) = self.getCodeIdx(self.us_hcode, inn, len_, bit_no) # read second hCode
if h < 0:
break # end of stream
if h == self.SHX_SET1: # If double Switch Set1, the CapsLock
is_all_upper = 1
continue
is_upper = 1 # anyways, still uppercase
else:
dstate = self.SHX_SET1 # if Set was not Set1, switch to Set1
continue
elif h == self.SHX_SET2: # If Set2, switch dstate to Set2
if dstate == self.SHX_SET1:
dstate = self.SHX_SET2
continue
if h != self.SHX_SET1: # all other Sets (why not else)
(v, bit_no) = self.getCodeIdx(self.us_vcode, inn, len_, bit_no) # we changed set, now read vCode for char
if v < 0:
break # end of stream
if v == 0 and h == self.SHX_SET1A:
#print("v = 0, h = self.SHX_SET1A")
if is_upper:
(temp, bit_no) = self.readCount(inn, bit_no, len_)
out[ol] = 255 - temp # binary
ol += 1
else:
(ol, bit_no) = self.decodeRepeat(inn, len_, out, ol, bit_no) # dist
continue
if h == self.SHX_SET1 and v == 3:
# was Unicode, will do Binary instead
(temp, bit_no) = self.readCount(inn, bit_no, len_)
out[ol] = 255 - temp # binary
ol += 1
continue
if h < 7 and v < 11:
#print("h {h} v {v}".format(h=h,v=v))
c = ord(self.sets[h][v])
if ord('a') <= c <= ord('z'):
if is_upper:
c -= 32 # go to UpperCase for letters
else: # handle all other cases
if is_upper and dstate == self.SHX_SET1 and v == 1:
c = ord('\t') # If UpperCase Space, change to TAB
if h == self.SHX_SET1B:
if 8 == v: # was LF or RPT, now only LF # pylint: disable=misplaced-comparison-constant
out[ol] = ord('\n')
ol += 1
continue
if 9 == v: # was CRLF, now RPT # pylint: disable=misplaced-comparison-constant
(count, bit_no) = self.readCount(inn, bit_no, len_)
count += 4
if ol + count >= len_out:
return -1 # overflow
rpt_c = out[ol - 1]
while count:
count -= 1
out[ol] = rpt_c
ol += 1
continue
if 10 == v: # pylint: disable=misplaced-comparison-constant
break # TERM, stop decoding
out[ol] = c
ol += 1
if ol >= len_out:
return -1 # overflow
return ol
# pylint: enable=missing-function-docstring
if __name__ == "__main__":
# pylint: disable=line-too-long
UNISHOX = Unishox()
BYTES_ = bytearray(2048)
INN = bytearray(b'ON Switch1#State==1 DO Add1 1 ENDON ON Var1#State==0 DO ShutterStop1 ENDON ON Var1#State==1 DO ShutterClose1 ENDON ON Var1#State>=2 DO Var1 0 ENDON ON Shutter1#Close DO Var1 0 ENDON ON Switch2#State==1 DO Add2 1 ENDON ON Var2#State==0 DO ShutterStop1 ENDON ON Var2#State==1 DO ShutterOpen1 ENDON ON Var2#State>=2 DO Var2 0 ENDON ON Shutter1#Open DO Var2 0 ENDON')
LEN_ = UNISHOX.compress(INN, len(INN), BYTES_, len(BYTES_))
print("Compressed from {fromm} to {to} ({p}%)".format(fromm=len(INN), to=LEN_, p=(100-LEN_/len(INN)*100)))
OUT = bytearray(2048)
LEN_ = UNISHOX.decompress(BYTES_, LEN_, OUT, len(OUT))
print(str(OUT, 'utf-8').split('\x00')[0])

View File

@ -1,36 +0,0 @@
/*
UnishoxStrings.c - support library for compressed strings in Flash
Copyright (C) 2021 Theo Arends and Stephan Hadinger
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/>.
*/
#include "UnishoxStrings.h"
#include <pgmspace.h>
extern int32_t DecompressNoAlloc(const char * compressed, size_t uncompressed_size, String & content);
//
// If first byte is NULL, then the string is compressed
//
UnishoxStrings::UnishoxStrings(const char *k_msg) {
if (pgm_read_byte(k_msg) == 0) {
size_t len = pgm_read_byte(k_msg + 1) * 16;
DecompressNoAlloc(k_msg + 2, len, _decompressed);
_msg = _decompressed.c_str();
} else {
_msg = k_msg;
}
}

View File

@ -1,98 +0,0 @@
/*
UnishoxStrings.c - support library for compressed strings in Flash
Copyright (C) 2021 Theo Arends and Stephan Hadinger
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 __UNISHOX_STRINGS__
#define __UNISHOX_STRINGS__
#include <cstddef>
#include <cstdint>
#include "WString.h"
/*******************************************************************************************/
/*
* UnishoxStrings compressed literal strings
*
* To be typically used for web UI to have multiple strings like JS, CSS, HTML
* compressed in a single list of small strings. This is where Unishox shines.
*
* Strings before compression are separated with NULL chars, which makes them ready to use
* once you know the offset in the global array.
*
* The list of string is marked by an empty stings, i.e. two consecutive NULL chars
*
* To distinguish from uncompressed templates, and to indicate the global size
* the compressed array is prefixed with NULL and the uncompressed size * 16 bytes.
*
* Compressed format:
* - Byte 00 : \00 - if non-null, then it is not compressed
* - Byte 01 : <size16> - uncompressed size is <size16> * 16 bytes (always rounded up)
* - Byte [] : compressed data (does not contain NULL)
* - Byte n : \00 - final NULL
*
/*******************************************************************************************/
/*******************************************************************************************/
/*
* This class is initialzed with either a PMEM uncompressed list of strings
* or a PMEM unishox-compressed list of strings; in this case RAM is allocated
* to hold the uncompressed data, until the class gets out of scope.
*
* To encode, use https://tasmota.hadinger.fr/util
* and use the "Compress strings template with unishox"
* past the C code for the strings, and copy/paste the result
* (don't foget to rename the variable).
*
* Input:
* Each string must be terminated with an explicit NULL char "\0". The list is hence
* terminated with a double-NULL.
*
* Each string is then indexed as its byte offset in the whole template.
* The offsets are computed at the same time as the compressed version.
* You need to use the online compressor even if you don't use the comrpessed version.
*
* Indexes are marked as C++ comments starting with "//="
*
* Example input:
* con
* // start of strings
* //=STRING_1
* "This is string 1"
* "\0"
* //=STRING_2
* "This is string 2"
* "continued here"
* "\0"
* ;
*
/*******************************************************************************************/
class UnishoxStrings {
public:
UnishoxStrings(const char *k_msg);
inline const char * operator[](uint16_t i) const { return _msg + i; }
const char * _msg = nullptr;
String _decompressed;
};
#endif // __UNISHOX_STRINGS__

View File

@ -1,587 +0,0 @@
/*
* Copyright (C) 2019 Siara Logics (cc)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Arundale R.
*
*/
/*
*
* This is a highly modified and optimized version of Unishox
* for Tasmota, aimed at compressing `Rules` which are typically
* short strings from 50 to 500 bytes.
*
* - moved to C++ (but still C-style)
* - c_95[] and l_95[] are pre-computed
* - all arrays in PROGMEM
* - removed all Unicode specific code to get code smaller, Unicode is rare in rules and encoded as pure binary
* - removed prev_lines management to reduce code size, we don't track previous encodings
* - using C++ const instead of #define
* - reusing the Unicode market to encode pure binary, which is 3 bits instead of 9
* - reverse binary encoding to 255-byte, favoring short encoding for values above 127, typical of Unicode
* - remove 2 bits encoding for Counts, since it could lead to a series of more than 8 consecutive 0-bits and output NULL char.
* Minimum encoding is 5 bits, which means spending 3+1=4 more bits for values in the range 0..3
* - removed CRLF encoding and reusing entry for RPT, saving 3 bits for repeats. Note: any CR will be binary encded
* - add safeguard to the output size (len_out), note that the compress buffer needs to be 4 bytes larger than actual compressed output.
* This is needed to avoid crash, since output can have ~30 bits
* - combined c_95[] and l_95[] to a single array to save space
* - Changed mapping of some characters in Set3, Set4 and Set4A, favoring frequent characters in rules and javascript
* - Added escape mechanism to ensure we never output NULL char. The marker is 0x2A which looked rare in preliminary tests
*
* @author Stephan Hadinger
*
*/
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdint.h>
#include <pgmspace.h>
#include "unishox.h"
typedef unsigned char byte;
// we squeeze both c_95[] and l_95[] in a sinle array.
// c_95[] uses only the 3 upper nibbles (or 12 most signifcant bits), while the last nibble encodes length (3..13)
// static uint16_t cl_95[95] PROGMEM = {0x4000 + 3, 0x3F80 + 11, 0x3D80 + 11, 0x3C80 + 10, 0x3BE0 + 12, 0x3E80 + 10, 0x3F40 + 11, 0x3EC0 + 10, 0x3BA0 + 11, 0x3BC0 + 11, 0x3D60 + 11, 0x3B60 + 11, 0x3A80 + 10, 0x3AC0 + 10, 0x3A00 + 9, 0x3B00 + 10, 0x38C0 + 10, 0x3900 + 10, 0x3940 + 11, 0x3960 + 11, 0x3980 + 11, 0x39A0 + 11, 0x39C0 + 11, 0x39E0 + 12, 0x39F0 + 12, 0x3880 + 10, 0x3CC0 + 10, 0x3C00 + 9, 0x3D00 + 10, 0x3E00 + 9, 0x3F00 + 10, 0x3B40 + 11, 0x3BF0 + 12, 0x2B00 + 8, 0x21C0 + 11, 0x20C0 + 10, 0x2100 + 10, 0x2600 + 7, 0x2300 + 11, 0x21E0 + 12, 0x2140 + 11, 0x2D00 + 8, 0x2358 + 13, 0x2340 + 12, 0x2080 + 10, 0x21A0 + 11, 0x2E00 + 8, 0x2C00 + 8, 0x2180 + 11, 0x2350 + 13, 0x2F80 + 9, 0x2F00 + 9, 0x2A00 + 8, 0x2160 + 11, 0x2330 + 12, 0x21F0 + 12, 0x2360 + 13, 0x2320 + 12, 0x2368 + 13, 0x3DE0 + 12, 0x3FA0 + 11, 0x3DF0 + 12, 0x3D40 + 11, 0x3F60 + 11, 0x3FF0 + 12, 0xB000 + 4, 0x1C00 + 7, 0x0C00 + 6, 0x1000 + 6, 0x6000 + 3, 0x3000 + 7, 0x1E00 + 8, 0x1400 + 7, 0xD000 + 4, 0x3580 + 9, 0x3400 + 8, 0x0800 + 6, 0x1A00 + 7, 0xE000 + 4, 0xC000 + 4, 0x1800 + 7, 0x3500 + 9, 0xF800 + 5, 0xF000 + 5, 0xA000 + 4, 0x1600 + 7, 0x3300 + 8, 0x1F00 + 8, 0x3600 + 9, 0x3200 + 8, 0x3680 + 9, 0x3DA0 + 11, 0x3FC0 + 11, 0x3DC0 + 11, 0x3FE0 + 12 };
// Patched, for len == 13, shift 1 bit right
static uint16_t cl_95[95] PROGMEM = {0x4000 + 3, 0x3F80 + 11, 0x3D80 + 11, 0x3C80 + 10, 0x3BE0 + 12, 0x3E80 + 10, 0x3F40 + 11, 0x3EC0 + 10, 0x3BA0 + 11, 0x3BC0 + 11, 0x3D60 + 11, 0x3B60 + 11, 0x3A80 + 10, 0x3AC0 + 10, 0x3A00 + 9, 0x3B00 + 10, 0x38C0 + 10, 0x3900 + 10, 0x3940 + 11, 0x3960 + 11, 0x3980 + 11, 0x39A0 + 11, 0x39C0 + 11, 0x39E0 + 12, 0x39F0 + 12, 0x3880 + 10, 0x3CC0 + 10, 0x3C00 + 9, 0x3D00 + 10, 0x3E00 + 9, 0x3F00 + 10, 0x3B40 + 11, 0x3BF0 + 12, 0x2B00 + 8, 0x21C0 + 11, 0x20C0 + 10, 0x2100 + 10, 0x2600 + 7, 0x2300 + 11, 0x21E0 + 12, 0x2140 + 11, 0x2D00 + 8, 0x46B0 + 13, 0x2340 + 12, 0x2080 + 10, 0x21A0 + 11, 0x2E00 + 8, 0x2C00 + 8, 0x2180 + 11, 0x46A0 + 13, 0x2F80 + 9, 0x2F00 + 9, 0x2A00 + 8, 0x2160 + 11, 0x2330 + 12, 0x21F0 + 12, 0x46C0 + 13, 0x2320 + 12, 0x46D0 + 13, 0x3DE0 + 12, 0x3FA0 + 11, 0x3DF0 + 12, 0x3D40 + 11, 0x3F60 + 11, 0x3FF0 + 12, 0xB000 + 4, 0x1C00 + 7, 0x0C00 + 6, 0x1000 + 6, 0x6000 + 3, 0x3000 + 7, 0x1E00 + 8, 0x1400 + 7, 0xD000 + 4, 0x3580 + 9, 0x3400 + 8, 0x0800 + 6, 0x1A00 + 7, 0xE000 + 4, 0xC000 + 4, 0x1800 + 7, 0x3500 + 9, 0xF800 + 5, 0xF000 + 5, 0xA000 + 4, 0x1600 + 7, 0x3300 + 8, 0x1F00 + 8, 0x3600 + 9, 0x3200 + 8, 0x3680 + 9, 0x3DA0 + 11, 0x3FC0 + 11, 0x3DC0 + 11, 0x3FE0 + 12 };
// Original version with c/l separate
// uint16_t c_95[95] PROGMEM = {0x4000, 0x3F80, 0x3D80, 0x3C80, 0x3BE0, 0x3E80, 0x3F40, 0x3EC0, 0x3BA0, 0x3BC0, 0x3D60, 0x3B60, 0x3A80, 0x3AC0, 0x3A00, 0x3B00, 0x38C0, 0x3900, 0x3940, 0x3960, 0x3980, 0x39A0, 0x39C0, 0x39E0, 0x39F0, 0x3880, 0x3CC0, 0x3C00, 0x3D00, 0x3E00, 0x3F00, 0x3B40, 0x3BF0, 0x2B00, 0x21C0, 0x20C0, 0x2100, 0x2600, 0x2300, 0x21E0, 0x2140, 0x2D00, 0x2358, 0x2340, 0x2080, 0x21A0, 0x2E00, 0x2C00, 0x2180, 0x2350, 0x2F80, 0x2F00, 0x2A00, 0x2160, 0x2330, 0x21F0, 0x2360, 0x2320, 0x2368, 0x3DE0, 0x3FA0, 0x3DF0, 0x3D40, 0x3F60, 0x3FF0, 0xB000, 0x1C00, 0x0C00, 0x1000, 0x6000, 0x3000, 0x1E00, 0x1400, 0xD000, 0x3580, 0x3400, 0x0800, 0x1A00, 0xE000, 0xC000, 0x1800, 0x3500, 0xF800, 0xF000, 0xA000, 0x1600, 0x3300, 0x1F00, 0x3600, 0x3200, 0x3680, 0x3DA0, 0x3FC0, 0x3DC0, 0x3FE0 };
// uint8_t l_95[95] PROGMEM = { 3, 11, 11, 10, 12, 10, 11, 10, 11, 11, 11, 11, 10, 10, 9, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 10, 10, 9, 10, 9, 10, 11, 12, 8, 11, 10, 10, 7, 11, 12, 11, 8, 13, 12, 10, 11, 8, 8, 11, 13, 9, 9, 8, 11, 12, 12, 13, 12, 13, 12, 11, 12, 11, 11, 12, 4, 7, 6, 6, 3, 7, 8, 7, 4, 9, 8, 6, 7, 4, 4, 7, 9, 5, 5, 4, 7, 8, 8, 9, 8, 9, 11, 11, 11, 12 };
enum {SHX_STATE_1 = 1, SHX_STATE_2}; // removed Unicode state
enum {SHX_SET1 = 0, SHX_SET1A, SHX_SET1B, SHX_SET2, SHX_SET3, SHX_SET4, SHX_SET4A};
// changed mapping in Set3, Set4, Set4A to accomodate frequencies in Rules and Javascript
static char sets[][11] PROGMEM =
{{ 0, ' ', 'e', 0, 't', 'a', 'o', 'i', 'n', 's', 'r'},
{ 0, 'l', 'c', 'd', 'h', 'u', 'p', 'm', 'b', 'g', 'w'},
{'f', 'y', 'v', 'k', 'q', 'j', 'x', 'z', 0, 0, 0},
{ 0, '9', '0', '1', '2', '3', '4', '5', '6', '7', '8'},
{'.', ',', '-', '/', '?', '+', ' ', '(', ')', '$', '@'},
{';', '#', ':', '<', '^', '*', '"', '{', '}', '[', ']'},
{'=', '%', '\'', '>', '&', '_', '!', '\\', '|', '~', '`'}};
// {{ 0, ' ', 'e', 0, 't', 'a', 'o', 'i', 'n', 's', 'r'},
// { 0, 'l', 'c', 'd', 'h', 'u', 'p', 'm', 'b', 'g', 'w'},
// {'f', 'y', 'v', 'k', 'q', 'j', 'x', 'z', 0, 0, 0},
// { 0, '9', '0', '1', '2', '3', '4', '5', '6', '7', '8'},
// {'.', ',', '-', '/', '=', '+', ' ', '(', ')', '$', '%'},
// {'&', ';', ':', '<', '>', '*', '"', '{', '}', '[', ']'},
// {'@', '?', '\'', '^', '#', '_', '!', '\\', '|', '~', '`'}};
// Decoder is designed for using less memory, not speed
// Decode lookup table for code index and length
// First 2 bits 00, Next 3 bits indicate index of code from 0,
// last 3 bits indicate code length in bits
// 0, 1, 2, 3, 4,
static char us_vcode[32] PROGMEM =
{2 + (0 << 3), 3 + (3 << 3), 3 + (1 << 3), 4 + (6 << 3), 0,
// 5, 6, 7, 8, 9, 10
4 + (4 << 3), 3 + (2 << 3), 4 + (8 << 3), 0, 0, 0,
// 11, 12, 13, 14, 15
4 + (7 << 3), 0, 4 + (5 << 3), 0, 5 + (9 << 3),
// 16, 17, 18, 19, 20, 21, 22, 23
0, 0, 0, 0, 0, 0, 0, 0,
// 24, 25, 26, 27, 28, 29, 30, 31
0, 0, 0, 0, 0, 0, 0, 5 + (10 << 3)};
// 0, 1, 2, 3, 4, 5, 6, 7,
static char us_hcode[32] PROGMEM =
{1 + (1 << 3), 2 + (0 << 3), 0, 3 + (2 << 3), 0, 0, 0, 5 + (3 << 3),
// 8, 9, 10, 11, 12, 13, 14, 15,
0, 0, 0, 0, 0, 0, 0, 5 + (5 << 3),
// 16, 17, 18, 19, 20, 21, 22, 23
0, 0, 0, 0, 0, 0, 0, 5 + (4 << 3),
// 24, 25, 26, 27, 28, 29, 30, 31
0, 0, 0, 0, 0, 0, 0, 5 + (6 << 3)};
static const char ESCAPE_MARKER = 0x2A; // Escape any null char
static const uint16_t TERM_CODE = 0x37C0; // 0b0011011111000000
static const uint16_t TERM_CODE_LEN = 10;
static const uint16_t DICT_CODE = 0x0000;
static const uint16_t DICT_CODE_LEN = 5;
static const uint16_t DICT_OTHER_CODE = 0x0000; // not used
static const uint16_t DICT_OTHER_CODE_LEN = 6;
// const uint16_t RPT_CODE = 0x2370;
// const uint16_t RPT_CODE_LEN = 13;
static const uint16_t RPT_CODE_TASMOTA = 0x3780;
static const uint16_t RPT_CODE_TASMOTA_LEN = 10;
static const uint16_t BACK2_STATE1_CODE = 0x2000; // 0010 = back to lower case
static const uint16_t BACK2_STATE1_CODE_LEN = 4;
static const uint16_t BACK_FROM_UNI_CODE = 0xFE00;
static const uint16_t BACK_FROM_UNI_CODE_LEN = 8;
// const uint16_t CRLF_CODE = 0x3780;
// const uint16_t CRLF_CODE_LEN = 10;
static const uint16_t LF_CODE = 0x3700;
static const uint16_t LF_CODE_LEN = 9;
static const uint16_t TAB_CODE = 0x2400;
static const uint16_t TAB_CODE_LEN = 7;
// const uint16_t UNI_CODE = 0x8000; // Unicode disabled
// const uint16_t UNI_CODE_LEN = 3;
// const uint16_t UNI_STATE_SPL_CODE = 0xF800;
// const uint16_t UNI_STATE_SPL_CODE_LEN = 5;
// const uint16_t UNI_STATE_DICT_CODE = 0xFC00;
// const uint16_t UNI_STATE_DICT_CODE_LEN = 7;
// const uint16_t CONT_UNI_CODE = 0x2800;
// const uint16_t CONT_UNI_CODE_LEN = 7;
static const uint16_t ALL_UPPER_CODE = 0x2200;
static const uint16_t ALL_UPPER_CODE_LEN = 8;
static const uint16_t SW2_STATE2_CODE = 0x3800;
static const uint16_t SW2_STATE2_CODE_LEN = 7;
static const uint16_t ST2_SPC_CODE = 0x3B80;
static const uint16_t ST2_SPC_CODE_LEN = 11;
static const uint16_t BIN_CODE_TASMOTA = 0x8000;
static const uint16_t BIN_CODE_TASMOTA_LEN = 3;
// const uint16_t BIN_CODE = 0x2000;
// const uint16_t BIN_CODE_LEN = 9;
#define NICE_LEN 5
// uint16_t mask[] PROGMEM = {0x8000, 0xC000, 0xE000, 0xF000, 0xF800, 0xFC00, 0xFE00, 0xFF00};
static const uint8_t mask[] PROGMEM = {0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF};
void Unishox::append_bits(unsigned int code, int clen) {
// Serial.printf("append_bits code = 0x%08X, clen %d\n", code, clen);
byte cur_bit;
byte blen;
unsigned char a_byte;
if (state == SHX_STATE_2) {
// remove change state prefix
if ((code >> 9) == 0x1C) {
code <<= 7;
clen -= 7;
}
}
while (clen > 0) {
cur_bit = ol % 8;
blen = (clen > 8 ? 8 : clen);
a_byte = (code >> 8) & pgm_read_word(&mask[blen - 1]);
a_byte >>= cur_bit;
if (blen + cur_bit > 8)
blen = (8 - cur_bit);
if (out) { // if out == nullptr, then we are in dry-run mode
if (cur_bit == 0)
out[ol >> 3] = a_byte;
else
out[ol >> 3] |= a_byte;
}
code <<= blen;
ol += blen;
if ((out) && (0 == ol % 8)) { // if out == nullptr, dry-run mode. We miss the escaping of characters in the length
// we completed a full byte
char last_c = out[(ol / 8) - 1];
if ((0 == last_c) || (ESCAPE_MARKER == last_c)) {
out[ol >> 3] = 1 + last_c; // increment to 0x01 or 0x2B
out[(ol >>3) -1] = ESCAPE_MARKER; // replace old value with marker
ol += 8; // add one full byte
}
}
clen -= blen;
}
}
// First five bits are code and Last three bits of codes represent length
// removing last 2 bytes, unused, we will never have values above 600 bytes
// const byte codes[7] = {0x01, 0x82, 0xC3, 0xE5, 0xED, 0xF5, 0xFD};
// const byte bit_len[7] = {2, 5, 7, 9, 12, 16, 17};
// const uint16_t adder[7] = {0, 4, 36, 164, 676, 4772, 0};
byte codes[] PROGMEM = { 0x82, 0xC3, 0xE5, 0xED, 0xF5 };
byte bit_len[] PROGMEM = { 5, 7, 9, 12, 16 };
// uint16_t adder[7] PROGMEM = { 0, 32, 160, 672, 4768 }; // no more used
void Unishox::encodeCount(int32_t count) {
int till = 0;
int base = 0;
for (uint32_t i = 0; i < sizeof(bit_len); i++) {
uint32_t bit_len_i = pgm_read_byte(&bit_len[i]);
till += (1 << bit_len_i);
if (count < till) {
byte codes_i = pgm_read_byte(&codes[i]);
append_bits((codes_i & 0xF8) << 8, codes_i & 0x07);
// ol = append_bits(out, ol, (count - pgm_read_word(&adder[i])) << (16 - bit_len_i), bit_len_i, 1);
append_bits((count - base) << (16 - bit_len_i), bit_len_i);
return;
}
base = till;
}
return;
}
bool Unishox::matchOccurance(void) {
int32_t j, k;
uint32_t longest_dist = 0;
uint32_t longest_len = 0;
for (j = l - NICE_LEN; j >= 0; j--) {
for (k = l; k < len && j + k - l < l; k++) {
if (in[k] != in[j + k - l])
break;
}
if (k - l > NICE_LEN - 1) {
uint32_t match_len = k - l - NICE_LEN;
uint32_t match_dist = l - j - NICE_LEN + 1;
if (match_len > longest_len) {
longest_len = match_len;
longest_dist = match_dist;
}
}
}
if (longest_len) {
if (state == SHX_STATE_2 || is_all_upper) {
is_all_upper = 0;
state = SHX_STATE_1;
append_bits(BACK2_STATE1_CODE, BACK2_STATE1_CODE_LEN);
}
append_bits(DICT_CODE, DICT_CODE_LEN);
encodeCount(longest_len);
encodeCount(longest_dist);
l += longest_len + NICE_LEN - 1;
return true;
}
return false;
}
// Compress a buffer.
// Inputs:
// - in: non-null pointer to a buffer of bytes to be compressed. Progmem is not valid. Null bytes are valid.
// - len: size of the input buffer. 0 is valid for empty buffer
// - out: pointer to output buffer. out is nullptr, the compressor does a dry-run and reports the compressed size without writing bytes
// - len_out: length in bytes of the output buffer.
// Output:
// - if >= 0: size of the compressed buffer. The output buffer does not contain NULL bytes, and it is not NULL terminated
// - if < 0: an error occured, most certainly the output buffer was not large enough
int32_t Unishox::unishox_compress(const char *p_in, size_t p_len, char *p_out, size_t p_len_out) {
in = p_in;
len = p_len;
out = p_out;
len_out = p_len_out;
char *ptr;
byte bits;
int ll;
char c_in, c_next;
byte is_upper;
ol = 0;
state = SHX_STATE_1;
is_all_upper = 0;
for (l=0; l<len; l++) {
c_in = in[l];
if (l && l < len - 4) {
if (c_in == in[l - 1] && c_in == in[l + 1] && c_in == in[l + 2] && c_in == in[l + 3]) { // check for repeat
int rpt_count = l + 4;
while (rpt_count < len && in[rpt_count] == c_in)
rpt_count++;
rpt_count -= l;
if (state == SHX_STATE_2 || is_all_upper) {
is_all_upper = 0;
state = SHX_STATE_1;
append_bits(BACK2_STATE1_CODE, BACK2_STATE1_CODE_LEN); // back to lower case and Set1
}
// ol = append_bits(out, ol, RPT_CODE, RPT_CODE_LEN, 1);
append_bits(RPT_CODE_TASMOTA, RPT_CODE_TASMOTA_LEN); // reusing CRLF for RPT
encodeCount(rpt_count - 4);
l += rpt_count - 1;
continue;
}
}
if (l < (len - NICE_LEN + 1)) {
if (matchOccurance()) {
continue;
}
}
if (state == SHX_STATE_2) { // if Set2
if ((c_in >= ' ' && c_in <= '@') ||
(c_in >= '[' && c_in <= '`') ||
(c_in >= '{' && c_in <= '~')) {
} else {
state = SHX_STATE_1; // back to Set1 and lower case
append_bits(BACK2_STATE1_CODE, BACK2_STATE1_CODE_LEN);
}
}
is_upper = 0;
if (c_in >= 'A' && c_in <= 'Z')
is_upper = 1;
else {
if (is_all_upper) {
is_all_upper = 0;
append_bits(BACK2_STATE1_CODE, BACK2_STATE1_CODE_LEN);
}
}
c_next = 0;
if (l+1 < len)
c_next = in[l+1];
if (c_in >= 32 && c_in <= 126) {
if (is_upper && !is_all_upper) {
for (ll=l+5; ll>=l && ll<len; ll--) {
if (in[ll] < 'A' || in[ll] > 'Z')
break;
}
if (ll == l-1) {
append_bits(ALL_UPPER_CODE, ALL_UPPER_CODE_LEN); // CapsLock
is_all_upper = 1;
}
}
if (state == SHX_STATE_1 && c_in >= '0' && c_in <= '9') {
append_bits(SW2_STATE2_CODE, SW2_STATE2_CODE_LEN); // Switch to sticky Set2
state = SHX_STATE_2;
}
c_in -= 32;
if (is_all_upper && is_upper)
c_in += 32;
if (c_in == 0 && state == SHX_STATE_2)
append_bits(ST2_SPC_CODE, ST2_SPC_CODE_LEN); // space from Set2 ionstead of Set1
else {
// Serial.printf("Encode %c %d\n", c_in + 32, c_in);
uint16_t cl = pgm_read_word(&cl_95[c_in]);
uint16_t cl_code = cl & 0xFFF0;
uint8_t cl_len = cl & 0x000F;
if (13 == cl_len) {
cl_code >>= 1;
}
append_bits(cl_code, cl_len);
}
} else if (c_in == 10) {
append_bits(LF_CODE, LF_CODE_LEN); // LF
} else if (c_in == '\t') {
append_bits(TAB_CODE, TAB_CODE_LEN); // TAB
} else {
append_bits(BIN_CODE_TASMOTA, BIN_CODE_TASMOTA_LEN); // Binary, we reuse the Unicode marker which 3 bits instead of 9
encodeCount((unsigned char) 255 - c_in);
}
// check that we have some headroom in the output buffer
if (ol / 8 >= len_out - 4) {
return -1; // we risk overflow and crash
}
}
bits = ol % 8;
if (bits) {
state = SHX_STATE_1;
append_bits(TERM_CODE, 8 - bits); // 0011 0111 1100 0000 TERM = 0011 0111 11
}
return ol / 8; // we already arrived to a byte boundary
// return ol/8+(ol%8?1:0);
}
uint32_t Unishox::getNextBit(void) {
if (8 == bit_no) {
if (byte_no >= len) {
in_eof = true;
return 1; // return only 1s, which appends 'r' in worst case
}
byte_in = pgm_read_byte(&in[byte_no++]);
if (ESCAPE_MARKER == byte_in) {
byte_in = pgm_read_byte(&in[byte_no++]) - 1; // we shouldn't need to test if byte_no >= len, because it should not be possible to end with ESCAPE_MARKER
}
bit_no = 0;
}
// Serial.printf("getNextBit %d\n", byte_in & (0x80 >> bit_no) ? 1 : 0);
return byte_in & (0x80 >> bit_no++) ? 1 : 0;
}
// Returns:
// 0..11
// or -1 if end of stream
int32_t Unishox::getCodeIdx(const char *code_type) {
int32_t code = 0;
int32_t count = 0;
do {
if (in_eof) return -1; // invalid state
code += getNextBit() << count;
count++;
uint8_t code_type_code = pgm_read_byte(&code_type[code]);
if (code_type_code && (code_type_code & 0x07) == count) {
return code_type_code >> 3;
}
} while (count < 5);
return -1; // skip if code not found
}
int32_t Unishox::getNumFromBits(uint32_t count) {
int ret = 0;
while (count--) {
ret += getNextBit() << count;
}
if (in_eof) return 0;
return ret;
}
// const byte bit_len[7] = {5, 2, 7, 9, 12, 16, 17};
// const uint16_t adder[7] = {4, 0, 36, 164, 676, 4772, 0};
// byte bit_len[7] PROGMEM = { 5, 7, 9, 12, 16 };
// byte bit_len_read[7] PROGMEM = {5, 2, 7, 9, 12, 16 };
// uint16_t adder_read[7] PROGMEM = {4, 0, 36, 164, 676, 4772, 0};
// uint16_t adder_read[] PROGMEM = {0, 0, 32, 160, 672, 4768 };
// byte bit_len[7] PROGMEM = { 5, 7, 9, 12, 16 };
// uint16_t adder_read[] PROGMEM = {0, 32, 160, 672, 4768 };
// Code size optimized, recalculate adder[] like in encodeCount
uint32_t Unishox::readCount(void) {
int32_t idx = getCodeIdx(us_hcode);
if ((1 == idx) || (idx >= sizeof(bit_len)) || (idx < 0)) return 0; // unsupported or end of stream
if (idx >= 1) idx--; // we skip v = 1 (code '0') since we no more accept 2 bits encoding
int base;
int till = 0;
byte bit_len_idx; // bit_len[0]
for (uint32_t i = 0; i <= idx; i++) {
base = till;
bit_len_idx = pgm_read_byte(&bit_len[i]);
till += (1 << bit_len_idx);
}
int count = getNumFromBits(bit_len_idx) + base;
return count;
}
void Unishox::decodeRepeat(void) {
uint32_t dict_len = readCount() + NICE_LEN;
uint32_t dist = readCount() + NICE_LEN - 1;
if (ol + dict_len <= len_out) {
memcpy(out + ol, out + ol - dist, dict_len);
ol += dict_len;
}
}
int32_t Unishox::unishox_decompress(const char *p_in, size_t p_len, char *p_out, size_t p_len_out) {
in = p_in;
len = p_len;
out = p_out;
len_out = p_len_out;
in_eof = false;
ol = 0;
bit_no = 8; // force load of first byte, pretending we expired the last one
byte_no = 0;
dstate = SHX_SET1;
is_all_upper = 0;
out[ol] = 0;
// while ((byte_no << 3) + bit_no - 8 < len) {
while (!in_eof) {
if (ol >= len_out) {
break;
}
int32_t h, v;
char c = 0;
byte is_upper = is_all_upper;
v = getCodeIdx(us_vcode); // read vCode
if (v < 0) break; // end of stream
h = dstate; // Set1 or Set2
if (v == 0) { // Switch which is common to Set1 and Set2, first entry
h = getCodeIdx(us_hcode); // read hCode
if (h < 0) break; // end of stream
if (h == SHX_SET1) { // target is Set1
if (dstate == SHX_SET1) { // Switch from Set1 to Set1 us UpperCase
if (is_all_upper) { // if CapsLock, then back to LowerCase
is_upper = is_all_upper = 0;
continue;
}
v = getCodeIdx(us_vcode); // read again vCode
if (v < 0) break; // end of stream
if (v == 0) {
h = getCodeIdx(us_hcode); // read second hCode
if (h < 0) break; // end of stream
if (h == SHX_SET1) { // If double Switch Set1, the CapsLock
is_all_upper = 1;
continue;
}
}
is_upper = 1; // anyways, still uppercase
} else {
dstate = SHX_SET1; // if Set was not Set1, switch to Set1
continue;
}
} else
if (h == SHX_SET2) { // If Set2, switch dstate to Set2
if (dstate == SHX_SET1) // TODO: is this test useful, there are only 2 states possible
dstate = SHX_SET2;
continue;
}
if (h != SHX_SET1) { // all other Sets (why not else)
v = getCodeIdx(us_vcode); // we changed set, now read vCode for char
if (v < 0) break; // end of stream
}
}
if (v == 0 && h == SHX_SET1A) {
if (is_upper) {
out[ol++] = 255 - readCount(); // binary
} else {
decodeRepeat(); // dist
}
continue;
}
if (h == SHX_SET1 && v == 3) {
// was Unicode, will do Binary instead
out[ol++] = 255 - readCount(); // binary
continue;
}
if (h < 7 && v < 11) // TODO: are these the actual limits? Not 11x7 ?
c = pgm_read_byte(&sets[h][v]);
if (c >= 'a' && c <= 'z') {
if (is_upper)
c -= 32; // go to UpperCase for letters
} else { // handle all other cases
if (is_upper && dstate == SHX_SET1 && v == 1)
c = '\t'; // If UpperCase Space, change to TAB
if (h == SHX_SET1B) {
if (8 == v) { // was LF or RPT, now only LF
out[ol++] = '\n';
continue;
}
if (9 == v) { // was CRLF, now RPT
uint32_t count = readCount() + 4;
if (ol + count >= len_out) {
return -1; // overflow
}
char rpt_c = out[ol - 1];
while (count--)
out[ol++] = rpt_c;
continue;
}
if (10 == v) {
break; // TERM, stop decoding
}
}
}
// Serial.printf(">>>>>>>>>>>>>>>>>>>>>> Out = %c\n", c);
out[ol++] = c;
}
if (ol > len_out) {
return -1; // overflow
} else {
return ol;
}
}

View File

@ -1,62 +0,0 @@
/*
* Copyright (C) 2019 Siara Logics (cc)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Arundale R.
*
*/
#ifndef unishox
#define unishox
class Unishox {
public:
Unishox() {};
int32_t unishox_decompress(const char *in, size_t len, char *out, size_t len_out);
int32_t unishox_compress(const char *in, size_t len, char *out, size_t len_out);
private:
void append_bits(unsigned int code, int clen);
void encodeCount(int32_t count);
bool matchOccurance(void);
uint32_t getNextBit(void);
int32_t getCodeIdx(const char *code_type);
uint32_t readCount(void);
void decodeRepeat(void);
int32_t getNumFromBits(uint32_t count);
inline void writeOut(char c) { out[ol++] = c; }
int32_t l;
uint32_t ol;
int32_t bit_no;
uint32_t byte_no;
bool in_eof; // have we reached end of file for compressed input
const char * in;
char * out;
size_t len;
size_t len_out;
uint8_t dstate;
unsigned char byte_in;
uint8_t state;
uint8_t is_all_upper;
};
#endif

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2016 Densaugeo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,9 +0,0 @@
CXX ?= g++
CFLAGS ?= -Wall -I src
test: catch.cpp catch.hpp src/base64.hpp
$(CXX) $(CFLAGS) catch.cpp -o catch
./catch
clean:
rm catch

View File

@ -1,44 +0,0 @@
# base64_arduino
Base64 encoder/decoder for arduino repo
[![npm](https://img.shields.io/npm/l/express.svg)]()
[![Build Status](https://travis-ci.org/Densaugeo/base64_arduino.svg?branch=master)](https://travis-ci.org/Densaugeo/base64_arduino)
## Installation
Add base64.cpp and base64.hpp to your project folder or library search path, put `#include "base64.hpp"` in your source, and pass base64.cpp to your compiler
## Usage
~~~
unsigned char binary[] = {133, 244, 117, 206, 178, 195};
unsigned char base64[9];
unsigned int base64_length = encode_base64(binary, 6, base64);
printf("%d\n", base64_length); // Prints "8"
printf((char *) base64); // Prints "hfR1zrLD"
~~~
~~~
unsigned char base64[] = "hfR1zrLD";
unsigned char binary[6];
unsigned int binary_length = decode_base64(base64, binary);
printf("[%d, %d, %d, %d, %d, %d]\n", // Prints "[133, 244, 117, 206, 178, 195]"
binary[0], binary[1], binary[2],
binary[3], binary[4], binary[5]);
printf("%d\n", binary_length); // Prints "6"
~~~
## Details
Uses common web conventions - '+' for 62, '/' for 63, '=' for padding. Note that invalid base64 characters are interpreted as padding.
Can be compiled as C, uses .*pp extensions because it is usually used in C++ projects and is tested for C++.
## License
MIT

View File

@ -1,465 +0,0 @@
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "base64.hpp"
TEST_CASE("encode_base64_length()", "[]") {
SECTION("Zero length") {
REQUIRE(encode_base64_length(0) == 0);
}
SECTION("Divisible by 3 (no padding)") {
REQUIRE(encode_base64_length(3) == 4);
REQUIRE(encode_base64_length(6) == 8);
REQUIRE(encode_base64_length(60) == 80);
}
SECTION("Not divisible by 3 (padded)") {
REQUIRE(encode_base64_length(1) == 4);
REQUIRE(encode_base64_length(2) == 4);
REQUIRE(encode_base64_length(4) == 8);
REQUIRE(encode_base64_length(5) == 8);
REQUIRE(encode_base64_length(7) == 12);
REQUIRE(encode_base64_length(256) == 344);
}
SECTION("Large") {
REQUIRE(encode_base64_length(65536) == 87384);
}
}
TEST_CASE("encode_base64()", "[]") {
unsigned char actual_base64[100];
SECTION("Zero length") {
unsigned char binary_0[] = {};
encode_base64(binary_0, 0, actual_base64); // Should give 'AQIDBUNDQQgEIIY4'
REQUIRE(memcmp(actual_base64, "", 1) == 0);
}
SECTION("Length 1 (single section padded)") {
unsigned char binary_0[] = {0};
encode_base64(binary_0, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "AA==", 5) == 0);
unsigned char binary_1[] = {3};
encode_base64(binary_1, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "Aw==", 5) == 0);
unsigned char binary_2[] = {8};
encode_base64(binary_2, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "CA==", 5) == 0);
unsigned char binary_3[] = {145};
encode_base64(binary_3, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "kQ==", 5) == 0);
unsigned char binary_4[] = {56};
encode_base64(binary_4, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "OA==", 5) == 0);
unsigned char binary_5[] = {54};
encode_base64(binary_5, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "Ng==", 5) == 0);
unsigned char binary_6[] = {181};
encode_base64(binary_6, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "tQ==", 5) == 0);
unsigned char binary_7[] = {79};
encode_base64(binary_7, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "Tw==", 5) == 0);
unsigned char binary_8[] = {115};
encode_base64(binary_8, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "cw==", 5) == 0);
unsigned char binary_9[] = {255};
encode_base64(binary_9, 1, actual_base64);
REQUIRE(memcmp(actual_base64, "/w==", 5) == 0);
}
SECTION("Length 2 (single section padded)") {
unsigned char binary_0[] = {0, 0};
encode_base64(binary_0, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "AAA=", 5) == 0);
unsigned char binary_1[] = {49, 42};
encode_base64(binary_1, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "MSo=", 5) == 0);
unsigned char binary_2[] = {133, 38};
encode_base64(binary_2, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "hSY=", 5) == 0);
unsigned char binary_3[] = {61, 127};
encode_base64(binary_3, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "PX8=", 5) == 0);
unsigned char binary_4[] = {109, 80};
encode_base64(binary_4, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "bVA=", 5) == 0);
unsigned char binary_5[] = {47, 213};
encode_base64(binary_5, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "L9U=", 5) == 0);
unsigned char binary_6[] = {172, 205};
encode_base64(binary_6, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "rM0=", 5) == 0);
unsigned char binary_7[] = {191, 240};
encode_base64(binary_7, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "v/A=", 5) == 0);
unsigned char binary_8[] = {107, 248};
encode_base64(binary_8, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "a/g=", 5) == 0);
unsigned char binary_9[] = {255, 255};
encode_base64(binary_9, 2, actual_base64);
REQUIRE(memcmp(actual_base64, "//8=", 5) == 0);
}
SECTION("Length 3 (single section no padding)") {
unsigned char binary_0[] = {0, 0, 0};
encode_base64(binary_0, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "AAAA", 5) == 0);
unsigned char binary_1[] = {151, 167, 18};
encode_base64(binary_1, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "l6cS", 5) == 0);
unsigned char binary_2[] = {23, 174, 50};
encode_base64(binary_2, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "F64y", 5) == 0);
unsigned char binary_3[] = {143, 205, 227};
encode_base64(binary_3, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "j83j", 5) == 0);
unsigned char binary_4[] = {60, 18, 186};
encode_base64(binary_4, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "PBK6", 5) == 0);
unsigned char binary_5[] = {100, 34, 201};
encode_base64(binary_5, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "ZCLJ", 5) == 0);
unsigned char binary_6[] = {52, 83, 129};
encode_base64(binary_6, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "NFOB", 5) == 0);
unsigned char binary_7[] = {241, 202, 185};
encode_base64(binary_7, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "8cq5", 5) == 0);
unsigned char binary_8[] = {149, 190, 208};
encode_base64(binary_8, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "lb7Q", 5) == 0);
unsigned char binary_9[] = {255, 255, 255};
encode_base64(binary_9, 3, actual_base64);
REQUIRE(memcmp(actual_base64, "////", 5) == 0);
}
SECTION("Length divisible by 3 (no padding)") {
unsigned char binary_0[] = {117, 213, 35, 151, 133, 255};
encode_base64(binary_0, 6, actual_base64);
REQUIRE(memcmp(actual_base64, "ddUjl4X/", 9) == 0);
unsigned char binary_1[] = {90, 95, 209, 235, 58, 255};
encode_base64(binary_1, 6, actual_base64);
REQUIRE(memcmp(actual_base64, "Wl/R6zr/", 9) == 0);
unsigned char binary_2[] = {133, 244, 117, 206, 178, 195, 249, 84, 248};
encode_base64(binary_2, 9, actual_base64);
REQUIRE(memcmp(actual_base64, "hfR1zrLD+VT4", 13) == 0);
unsigned char binary_3[] = {7, 27, 226, 144, 59, 237, 79, 62, 191};
encode_base64(binary_3, 9, actual_base64);
REQUIRE(memcmp(actual_base64, "BxvikDvtTz6/", 13) == 0);
unsigned char binary_4[] = {99, 225, 39, 195, 8, 43, 209, 151, 8, 43, 195, 183};
encode_base64(binary_4, 12, actual_base64);
REQUIRE(memcmp(actual_base64, "Y+Enwwgr0ZcIK8O3", 17) == 0);
unsigned char binary_5[] = {171, 65, 164, 64, 60, 221, 46, 226, 252, 167, 250, 252};
encode_base64(binary_5, 12, actual_base64);
REQUIRE(memcmp(actual_base64, "q0GkQDzdLuL8p/r8", 17) == 0);
unsigned char binary_6[] = {248, 127, 14, 241, 93, 177, 152, 46, 255, 127, 92, 84, 56, 59, 152, 132, 113, 115, 252, 70, 190, 224, 130, 155, 86, 172, 159, 162, 30, 127};
encode_base64(binary_6, 30, actual_base64);
REQUIRE(memcmp(actual_base64, "+H8O8V2xmC7/f1xUODuYhHFz/Ea+4IKbVqyfoh5/", 41) == 0);
unsigned char binary_7[] = {157, 12, 248, 83, 148, 156, 196, 30, 186, 28, 52, 192, 171, 142, 6, 105, 128, 131, 89, 5, 3, 131, 215, 192, 87, 215, 244, 141, 127, 17};
encode_base64(binary_7, 30, actual_base64);
REQUIRE(memcmp(actual_base64, "nQz4U5ScxB66HDTAq44GaYCDWQUDg9fAV9f0jX8R", 41) == 0);
unsigned char binary_8[] = {180, 179, 175, 132, 162, 219, 3, 18, 96, 162, 214, 232, 49, 120, 59, 133, 102, 93, 67, 34, 186, 28, 6, 28, 195, 69, 249, 44, 140, 115, 55, 215, 68, 99, 130, 160, 32, 181, 172, 125, 144, 8, 21, 119, 60, 213, 156, 230, 243, 87, 101, 167, 136, 94, 242, 174, 239, 81, 67, 101};
encode_base64(binary_8, 60, actual_base64);
REQUIRE(memcmp(actual_base64, "tLOvhKLbAxJgotboMXg7hWZdQyK6HAYcw0X5LIxzN9dEY4KgILWsfZAIFXc81Zzm81dlp4he8q7vUUNl", 81) == 0);
unsigned char binary_9[] = {165, 186, 12, 82, 241, 34, 63, 218, 215, 28, 105, 126, 37, 69, 255, 36, 235, 103, 194, 236, 81, 115, 192, 61, 247, 128, 43, 38, 58, 140, 208, 9, 34, 145, 252, 209, 150, 227, 35, 241, 46, 25, 170, 198, 191, 87, 43, 206, 250, 199, 158, 193, 96, 249, 79, 142, 39, 216, 36, 236};
encode_base64(binary_9, 60, actual_base64);
REQUIRE(memcmp(actual_base64, "pboMUvEiP9rXHGl+JUX/JOtnwuxRc8A994ArJjqM0AkikfzRluMj8S4Zqsa/VyvO+seewWD5T44n2CTs", 81) == 0);
}
SECTION("Length not divisible by 3 (padded)") {
unsigned char binary_0[] = {216, 183, 235, 10};
encode_base64(binary_0, 4, actual_base64);
REQUIRE(memcmp(actual_base64, "2LfrCg==", 9) == 0);
unsigned char binary_1[] = {7, 254, 182, 49, 158};
encode_base64(binary_1, 5, actual_base64);
REQUIRE(memcmp(actual_base64, "B/62MZ4=", 9) == 0);
unsigned char binary_2[] = {71, 58, 223, 154, 93, 69, 18};
encode_base64(binary_2, 7, actual_base64);
REQUIRE(memcmp(actual_base64, "Rzrfml1FEg==", 13) == 0);
unsigned char binary_3[] = {226, 127, 31, 206, 19, 75, 35, 80};
encode_base64(binary_3, 8, actual_base64);
REQUIRE(memcmp(actual_base64, "4n8fzhNLI1A=", 13) == 0);
unsigned char binary_4[] = {5, 36, 50, 78, 218, 198, 242, 85, 235, 72, 78, 139, 103};
encode_base64(binary_4, 13, actual_base64);
REQUIRE(memcmp(actual_base64, "BSQyTtrG8lXrSE6LZw==", 21) == 0);
unsigned char binary_5[] = {161, 176, 49, 33, 148, 150, 94, 252, 21, 249, 106, 49, 216, 124, 219, 233, 133, 102, 32, 182, 193};
encode_base64(binary_5, 21, actual_base64);
REQUIRE(memcmp(actual_base64, "obAxIZSWXvwV+Wox2Hzb6YVmILbB", 29) == 0);
unsigned char binary_6[] = {136, 116, 151, 174, 215, 54, 64, 218, 197, 148, 149, 17, 183, 59, 177, 54, 172, 135, 192, 202, 183, 3, 254, 51, 83, 217};
encode_base64(binary_6, 26, actual_base64);
REQUIRE(memcmp(actual_base64, "iHSXrtc2QNrFlJURtzuxNqyHwMq3A/4zU9k=", 37) == 0);
unsigned char binary_7[] = {181, 16, 71, 30, 145, 101, 21, 170, 45, 24, 201, 78, 83, 31, 175, 132, 127, 108, 88, 7, 37, 154, 196, 139, 87, 68, 243, 6, 180, 36, 89, 10, 67, 73};
encode_base64(binary_7, 34, actual_base64);
REQUIRE(memcmp(actual_base64, "tRBHHpFlFaotGMlOUx+vhH9sWAclmsSLV0TzBrQkWQpDSQ==", 49) == 0);
unsigned char binary_8[] = {24, 6, 234, 175, 34, 198, 47, 173, 234, 158, 106, 203, 80, 171, 218, 163, 60, 105, 183, 152, 73, 142, 190, 107, 189, 223, 215, 169, 63, 169, 163, 29, 9, 134, 235, 107, 35, 5, 16, 50, 7};
encode_base64(binary_8, 41, actual_base64);
REQUIRE(memcmp(actual_base64, "GAbqryLGL63qnmrLUKvaozxpt5hJjr5rvd/XqT+pox0JhutrIwUQMgc=", 57) == 0);
unsigned char binary_9[] = {220, 92, 67, 95, 157, 76, 162, 210, 224, 202, 136, 157, 104, 178, 103, 81, 35, 103, 244, 71, 92, 25, 69, 64, 61, 232, 198, 108, 217, 106, 63, 103, 234, 39, 156, 108, 4, 101, 212, 198, 57, 223, 75, 132, 160, 26, 193, 139, 16, 89, 12, 45, 183, 133, 33};
encode_base64(binary_9, 55, actual_base64);
REQUIRE(memcmp(actual_base64, "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ==", 77) == 0);
}
}
TEST_CASE("decode_base64_length()", "[]") {
SECTION("Zero length") {
REQUIRE(decode_base64_length((unsigned char*) "") == 0);
}
SECTION("Divisible by 4 (no padding)") {
REQUIRE(decode_base64_length((unsigned char*) "AAAA") == 3);
REQUIRE(decode_base64_length((unsigned char*) "////") == 3);
REQUIRE(decode_base64_length((unsigned char*) "Y+Enwwgr0ZcIK8O3") == 12);
REQUIRE(decode_base64_length((unsigned char*) "tLOvhKLbAxJgotboMXg7hWZdQyK6HAYcw0X5LIxzN9dEY4KgILWsfZAIFXc81Zzm81dlp4he8q7vUUNl") == 60);
}
SECTION("Not divisible by 4 (padded)") {
REQUIRE(decode_base64_length((unsigned char*) "AA==") == 1);
REQUIRE(decode_base64_length((unsigned char*) "Aw==") == 1);
REQUIRE(decode_base64_length((unsigned char*) "a/g=") == 2);
REQUIRE(decode_base64_length((unsigned char*) "//8=") == 2);
REQUIRE(decode_base64_length((unsigned char*) "4n8fzhNLI1A=") == 8);
REQUIRE(decode_base64_length((unsigned char*) "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ==") == 55);
}
SECTION("Not divisible by 4 (padding missing)") {
REQUIRE(decode_base64_length((unsigned char*) "AA") == 1);
REQUIRE(decode_base64_length((unsigned char*) "Aw") == 1);
REQUIRE(decode_base64_length((unsigned char*) "a/g") == 2);
REQUIRE(decode_base64_length((unsigned char*) "//8") == 2);
REQUIRE(decode_base64_length((unsigned char*) "4n8fzhNLI1A") == 8);
REQUIRE(decode_base64_length((unsigned char*) "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ") == 55);
}
SECTION("Padding in middle cuts off string") {
REQUIRE(decode_base64_length((unsigned char*) "AA==4n8fzhNL") == 1);
REQUIRE(decode_base64_length((unsigned char*) "Aw=4n8fzhNL") == 1);
REQUIRE(decode_base64_length((unsigned char*) "a/g=4n8fzhNL==") == 2);
REQUIRE(decode_base64_length((unsigned char*) "//8=4n8fzhNL") == 2);
REQUIRE(decode_base64_length((unsigned char*) "4n8fzhNLI1A=4n8fzhNL====") == 8);
REQUIRE(decode_base64_length((unsigned char*) "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ==4n8fzhNL") == 55);
}
SECTION("Extra padding is ignored") {
REQUIRE(decode_base64_length((unsigned char*) "Aw========") == 1);
REQUIRE(decode_base64_length((unsigned char*) "a/g=======") == 2);
REQUIRE(decode_base64_length((unsigned char*) "Aw========") == 1);
REQUIRE(decode_base64_length((unsigned char*) "a/g==========") == 2);
REQUIRE(decode_base64_length((unsigned char*) "4n8fzhNLI1A===========") == 8);
REQUIRE(decode_base64_length((unsigned char*) "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ=========") == 55);
}
SECTION("Non-base64 characcters are interpreted as padding") {
REQUIRE(decode_base64_length((unsigned char*) "Aw:;") == 1);
REQUIRE(decode_base64_length((unsigned char*) "Aw`'@") == 1);
REQUIRE(decode_base64_length((unsigned char*) "a/g~") == 2);
REQUIRE(decode_base64_length((unsigned char*) "a/g[|") == 2);
REQUIRE(decode_base64_length((unsigned char*) "4n8fzhNLI1A]") == 8);
REQUIRE(decode_base64_length((unsigned char*) "Y+Enwwgr0ZcIK8O3{}") == 12);
REQUIRE(decode_base64_length((unsigned char*) "AA-^4n8fzhNL") == 1);
}
}
TEST_CASE("decode_base64()", "[]") {
unsigned char actual_binary[100];
// Zero length case ignored, because it is verified to return no data in decode_base64_length()
SECTION("Divisible by 4 (no padding)") {
unsigned char expected_binary_0[] = {0, 0, 0};
decode_base64((unsigned char*) "AAAA", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_0, 3) == 0);
unsigned char expected_binary_1[] = {255, 255, 255};
decode_base64((unsigned char*) "////", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_1, 3) == 0);
unsigned char expected_binary_2[] = {99, 225, 39, 195, 8, 43, 209, 151, 8, 43, 195, 183};
decode_base64((unsigned char*) "Y+Enwwgr0ZcIK8O3", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_2, 12) == 0);
unsigned char expected_binary_3[] = {180, 179, 175, 132, 162, 219, 3, 18, 96, 162, 214, 232, 49, 120, 59, 133, 102, 93, 67, 34, 186, 28, 6, 28, 195, 69, 249, 44, 140, 115, 55, 215, 68, 99, 130, 160, 32, 181, 172, 125, 144, 8, 21, 119, 60, 213, 156, 230, 243, 87, 101, 167, 136, 94, 242, 174, 239, 81, 67, 101};
decode_base64((unsigned char*) "tLOvhKLbAxJgotboMXg7hWZdQyK6HAYcw0X5LIxzN9dEY4KgILWsfZAIFXc81Zzm81dlp4he8q7vUUNl", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_3, 60) == 0);
}
SECTION("Not divisible by 4 (padded)") {
unsigned char expected_binary_0[] = {0};
decode_base64((unsigned char*) "AA==", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_0, 1) == 0);
unsigned char expected_binary_1[] = {3};
decode_base64((unsigned char*) "Aw==", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_1, 1) == 0);
unsigned char expected_binary_2[] = {107, 248};
decode_base64((unsigned char*) "a/g=", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_2, 2) == 0);
unsigned char expected_binary_3[] = {255, 255};
decode_base64((unsigned char*) "//8=", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_3, 2) == 0);
unsigned char expected_binary_4[] = {226, 127, 31, 206, 19, 75, 35, 80};
decode_base64((unsigned char*) "4n8fzhNLI1A=", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_4, 8) == 0);
unsigned char expected_binary_5[] = {220, 92, 67, 95, 157, 76, 162, 210, 224, 202, 136, 157, 104, 178, 103, 81, 35, 103, 244, 71, 92, 25, 69, 64, 61, 232, 198, 108, 217, 106, 63, 103, 234, 39, 156, 108, 4, 101, 212, 198, 57, 223, 75, 132, 160, 26, 193, 139, 16, 89, 12, 45, 183, 133, 33};
decode_base64((unsigned char*) "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ==", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_5, 55) == 0);
}
SECTION("Not divisible by 4 (padding missing)") {
unsigned char expected_binary_0[] = {0};
decode_base64((unsigned char*) "AA", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_0, 1) == 0);
unsigned char expected_binary_1[] = {3};
decode_base64((unsigned char*) "Aw", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_1, 1) == 0);
unsigned char expected_binary_2[] = {107, 248};
decode_base64((unsigned char*) "a/g", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_2, 2) == 0);
unsigned char expected_binary_3[] = {255, 255};
decode_base64((unsigned char*) "//8", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_3, 2) == 0);
unsigned char expected_binary_4[] = {226, 127, 31, 206, 19, 75, 35, 80};
decode_base64((unsigned char*) "4n8fzhNLI1A", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_4, 8) == 0);
unsigned char expected_binary_5[] = {220, 92, 67, 95, 157, 76, 162, 210, 224, 202, 136, 157, 104, 178, 103, 81, 35, 103, 244, 71, 92, 25, 69, 64, 61, 232, 198, 108, 217, 106, 63, 103, 234, 39, 156, 108, 4, 101, 212, 198, 57, 223, 75, 132, 160, 26, 193, 139, 16, 89, 12, 45, 183, 133, 33};
decode_base64((unsigned char*) "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_5, 55) == 0);
}
SECTION("Padding in middle cuts off string") {
unsigned char expected_binary_0[] = {0};
decode_base64((unsigned char*) "AA==4n8fzhNL", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_0, 1) == 0);
unsigned char expected_binary_1[] = {3};
decode_base64((unsigned char*) "Aw=4n8fzhNL", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_1, 1) == 0);
unsigned char expected_binary_2[] = {107, 248};
decode_base64((unsigned char*) "a/g=4n8fzhNL==", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_2, 2) == 0);
unsigned char expected_binary_3[] = {255, 255};
decode_base64((unsigned char*) "//8=4n8fzhNL", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_3, 2) == 0);
unsigned char expected_binary_4[] = {226, 127, 31, 206, 19, 75, 35, 80};
decode_base64((unsigned char*) "4n8fzhNLI1A=4n8fzhNL====", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_4, 8) == 0);
unsigned char expected_binary_5[] = {220, 92, 67, 95, 157, 76, 162, 210, 224, 202, 136, 157, 104, 178, 103, 81, 35, 103, 244, 71, 92, 25, 69, 64, 61, 232, 198, 108, 217, 106, 63, 103, 234, 39, 156, 108, 4, 101, 212, 198, 57, 223, 75, 132, 160, 26, 193, 139, 16, 89, 12, 45, 183, 133, 33};
decode_base64((unsigned char*) "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ==4n8fzhNL", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_5, 55) == 0);
}
SECTION("Extra padding is ignored") {
unsigned char expected_binary_0[] = {3};
decode_base64((unsigned char*) "Aw========", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_0, 1) == 0);
unsigned char expected_binary_1[] = {107, 248};
decode_base64((unsigned char*) "a/g=======", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_1, 2) == 0);
unsigned char expected_binary_2[] = {3};
decode_base64((unsigned char*) "Aw========", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_2, 1) == 0);
unsigned char expected_binary_3[] = {107, 248};
decode_base64((unsigned char*) "a/g==========", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_3, 2) == 0);
unsigned char expected_binary_4[] = {226, 127, 31, 206, 19, 75, 35, 80};
decode_base64((unsigned char*) "4n8fzhNLI1A===========", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_4, 8) == 0);
unsigned char expected_binary_5[] = {220, 92, 67, 95, 157, 76, 162, 210, 224, 202, 136, 157, 104, 178, 103, 81, 35, 103, 244, 71, 92, 25, 69, 64, 61, 232, 198, 108, 217, 106, 63, 103, 234, 39, 156, 108, 4, 101, 212, 198, 57, 223, 75, 132, 160, 26, 193, 139, 16, 89, 12, 45, 183, 133, 33};
decode_base64((unsigned char*) "3FxDX51MotLgyoidaLJnUSNn9EdcGUVAPejGbNlqP2fqJ5xsBGXUxjnfS4SgGsGLEFkMLbeFIQ=========", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_5, 55) == 0);
}
SECTION("Non-base64 characcters are interpreted as padding") {
unsigned char expected_binary_0[] = {3};
decode_base64((unsigned char*) "Aw==", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_0, 1) == 0);
unsigned char expected_binary_1[] = {3};
decode_base64((unsigned char*) "Aw===", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_1, 1) == 0);
unsigned char expected_binary_2[] = {107, 248};
decode_base64((unsigned char*) "a/g=", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_2, 2) == 0);
unsigned char expected_binary_3[] = {107, 248};
decode_base64((unsigned char*) "a/g==", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_3, 2) == 0);
unsigned char expected_binary_4[] = {226, 127, 31, 206, 19, 75, 35, 80};
decode_base64((unsigned char*) "4n8fzhNLI1A=", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_4, 8) == 0);
unsigned char expected_binary_5[] = {99, 225, 39, 195, 8, 43, 209, 151, 8, 43, 195, 183};
decode_base64((unsigned char*) "Y+Enwwgr0ZcIK8O3==", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_5, 12) == 0);
unsigned char expected_binary_6[] = {0};
decode_base64((unsigned char*) "AA==4n8fzhNL", actual_binary);
REQUIRE(memcmp(actual_binary, expected_binary_6, 1) == 0);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +0,0 @@
name=base64
version=1.1.1
author=Densaugeo <use@git.hub>
maintainer=Densaugeo <use@git.hub>
sentence=Base64 encoder/decoder for arduino repo
paragraph=Uses common web conventions - '+' for 62, '/' for 63, '=' for padding. Note that invalid base64 characters are interpreted as padding.
category=Communication
url=https://github.com/Densaugeo/base64_arduino
architectures=*

View File

@ -1,195 +0,0 @@
/**
* Base64 encoding and decoding of strings. Uses '+' for 62, '/' for 63, '=' for padding
*/
#ifndef BASE64_H_INCLUDED
#define BASE64_H_INCLUDED
/* binary_to_base64:
* Description:
* Converts a single byte from a binary value to the corresponding base64 character
* Parameters:
* v - Byte to convert
* Returns:
* ascii code of base64 character. If byte is >= 64, then there is not corresponding base64 character
* and 255 is returned
*/
unsigned char binary_to_base64(unsigned char v);
/* base64_to_binary:
* Description:
* Converts a single byte from a base64 character to the corresponding binary value
* Parameters:
* c - Base64 character (as ascii code)
* Returns:
* 6-bit binary value
*/
unsigned char base64_to_binary(unsigned char c);
/* encode_base64_length:
* Description:
* Calculates length of base64 string needed for a given number of binary bytes
* Parameters:
* input_length - Amount of binary data in bytes
* Returns:
* Number of base64 characters needed to encode input_length bytes of binary data
*/
unsigned int encode_base64_length(unsigned int input_length);
/* decode_base64_length:
* Description:
* Calculates number of bytes of binary data in a base64 string
* Parameters:
* input - Base64-encoded null-terminated string
* Returns:
* Number of bytes of binary data in input
*/
unsigned int decode_base64_length(unsigned char input[]);
/* encode_base64:
* Description:
* Converts an array of bytes to a base64 null-terminated string
* Parameters:
* input - Pointer to input data
* input_length - Number of bytes to read from input pointer
* output - Pointer to output string. Null terminator will be added automatically
* Returns:
* Length of encoded string in bytes (not including null terminator)
*/
unsigned int encode_base64(unsigned char input[], unsigned int input_length, unsigned char output[]);
/* decode_base64:
* Description:
* Converts a base64 null-terminated string to an array of bytes
* Parameters:
* input - Pointer to input string
* output - Pointer to output array
* Returns:
* Number of bytes in the decoded binary
*/
unsigned int decode_base64(unsigned char input[], unsigned char output[]);
unsigned char binary_to_base64(unsigned char v) {
// Capital letters - 'A' is ascii 65 and base64 0
if(v < 26) return v + 'A';
// Lowercase letters - 'a' is ascii 97 and base64 26
if(v < 52) return v + 71;
// Digits - '0' is ascii 48 and base64 52
if(v < 62) return v - 4;
// '+' is ascii 43 and base64 62
if(v == 62) return '+';
// '/' is ascii 47 and base64 63
if(v == 63) return '/';
return 64;
}
unsigned char base64_to_binary(unsigned char c) {
// Capital letters - 'A' is ascii 65 and base64 0
if('A' <= c && c <= 'Z') return c - 'A';
// Lowercase letters - 'a' is ascii 97 and base64 26
if('a' <= c && c <= 'z') return c - 71;
// Digits - '0' is ascii 48 and base64 52
if('0' <= c && c <= '9') return c + 4;
// '+' is ascii 43 and base64 62
if(c == '+') return 62;
// '/' is ascii 47 and base64 63
if(c == '/') return 63;
return 255;
}
unsigned int encode_base64_length(unsigned int input_length) {
return (input_length + 2)/3*4;
}
unsigned int decode_base64_length(unsigned char input[]) {
unsigned char *start = input;
while(base64_to_binary(input[0]) < 64) {
++input;
}
unsigned int input_length = input - start;
unsigned int output_length = input_length/4*3;
switch(input_length % 4) {
default: return output_length;
case 2: return output_length + 1;
case 3: return output_length + 2;
}
}
unsigned int encode_base64(unsigned char input[], unsigned int input_length, unsigned char output[]) {
unsigned int full_sets = input_length/3;
// While there are still full sets of 24 bits...
for(unsigned int i = 0; i < full_sets; ++i) {
output[0] = binary_to_base64( input[0] >> 2);
output[1] = binary_to_base64((input[0] & 0x03) << 4 | input[1] >> 4);
output[2] = binary_to_base64((input[1] & 0x0F) << 2 | input[2] >> 6);
output[3] = binary_to_base64( input[2] & 0x3F);
input += 3;
output += 4;
}
switch(input_length % 3) {
case 0:
output[0] = '\0';
break;
case 1:
output[0] = binary_to_base64( input[0] >> 2);
output[1] = binary_to_base64((input[0] & 0x03) << 4);
output[2] = '=';
output[3] = '=';
output[4] = '\0';
break;
case 2:
output[0] = binary_to_base64( input[0] >> 2);
output[1] = binary_to_base64((input[0] & 0x03) << 4 | input[1] >> 4);
output[2] = binary_to_base64((input[1] & 0x0F) << 2);
output[3] = '=';
output[4] = '\0';
break;
}
return encode_base64_length(input_length);
}
unsigned int decode_base64(unsigned char input[], unsigned char output[]) {
unsigned int output_length = decode_base64_length(input);
// While there are still full sets of 24 bits...
for(unsigned int i = 2; i < output_length; i += 3) {
output[0] = base64_to_binary(input[0]) << 2 | base64_to_binary(input[1]) >> 4;
output[1] = base64_to_binary(input[1]) << 4 | base64_to_binary(input[2]) >> 2;
output[2] = base64_to_binary(input[2]) << 6 | base64_to_binary(input[3]);
input += 4;
output += 3;
}
switch(output_length % 3) {
case 1:
output[0] = base64_to_binary(input[0]) << 2 | base64_to_binary(input[1]) >> 4;
break;
case 2:
output[0] = base64_to_binary(input[0]) << 2 | base64_to_binary(input[1]) >> 4;
output[1] = base64_to_binary(input[1]) << 4 | base64_to_binary(input[2]) >> 2;
break;
}
return output_length;
}
#endif // ifndef

View File

@ -1,73 +0,0 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
typedef enum __dpt_1_001
{
DPT_1_001_OFF = 0x00,
DPT_1_001_ON = 0x01,
} dpt_1_001_t;
typedef enum __dpt_2_001
{
DPT_2_001_NO_OFF = 0b00,
DPT_2_001_NO_ON = 0b01,
DPT_2_001_YES_OFF = 0b10,
DPT_2_001_YES_ON = 0b11,
} dpt_2_001_t;
typedef enum __dpt_3_007
{
DPT_3_007_DECREASE_STOP = 0x00,
DPT_3_007_DECREASE_100 = 0x01,
DPT_3_007_DECREASE_50 = 0x02,
DPT_3_007_DECREASE_25 = 0x03,
DPT_3_007_DECREASE_12 = 0x04,
DPT_3_007_DECREASE_6 = 0x05,
DPT_3_007_DECREASE_3 = 0x06,
DPT_3_007_DECREASE_1 = 0x07,
DPT_3_007_INCREASE_STOP = 0x08,
DPT_3_007_INCREASE_100 = 0x09,
DPT_3_007_INCREASE_50 = 0x0A,
DPT_3_007_INCREASE_25 = 0x0B,
DPT_3_007_INCREASE_12 = 0x0C,
DPT_3_007_INCREASE_6 = 0x0D,
DPT_3_007_INCREASE_3 = 0x0E,
DPT_3_007_INCREASE_1 = 0x0F,
} dpt_3_007_t;
typedef enum __weekday
{
DPT_10_001_WEEKDAY_NODAY = 0,
DPT_10_001_WEEKDAY_MONDAY = 1,
DPT_10_001_WEEKDAY_TUESDAY = 2,
DPT_10_001_WEEKDAY_WEDNESDAY = 3,
DPT_10_001_WEEKDAY_THURSDAY = 4,
DPT_10_001_WEEKDAY_FRIDAY = 5,
DPT_10_001_WEEKDAY_SATURDAY = 6,
DPT_10_001_WEEKDAY_SUNDAY = 7,
} weekday_t;
typedef struct __time_of_day
{
weekday_t weekday;
uint8_t hours;
uint8_t minutes;
uint8_t seconds;
} time_of_day_t;
typedef struct __date
{
uint8_t day;
uint8_t month;
uint8_t year;
} date_t;
typedef struct __color
{
uint8_t red;
uint8_t green;
uint8_t blue;
} color_t;

View File

@ -1,600 +0,0 @@
/**
* esp-knx-ip library for KNX/IP communication on an ESP8266
* Author: Nico Weichbrodt <envy>
* License: MIT
*/
#ifndef ESP_KNX_IP_H
#define ESP_KNX_IP_H
/**
* CONFIG
* All MAX_ values must not exceed 255 (1 byte, except MAC_CONFIG_SPACE which can go up to 2 bytes, so 0xffff in theory) and must not be negative!
* Config space is restriced by EEPROM_SIZE (default 1024).
* Required EEPROM size is 8 + MAX_GA_CALLBACKS * 3 + 2 + MAX_CONFIG_SPACE which is 552 by default
*/
#define EEPROM_SIZE 1024 // [Default 1024]
#define MAX_CALLBACK_ASSIGNMENTS 10 // [Default 10] Maximum number of group address callbacks that can be stored
#define MAX_CALLBACKS 10 // [Default 10] Maximum number of callbacks that can be stored
#define MAX_CONFIGS 20 // [Default 20] Maximum number of config items that can be stored
#define MAX_CONFIG_SPACE 0x0200 // [Default 0x0200] Maximum number of bytes that can be stored for custom config
#define MAX_FEEDBACKS 20 // [Default 20] Maximum number of feedbacks that can be shown
// Callbacks
#define ALLOW_MULTIPLE_CALLBACKS_PER_ADDRESS 1 // [Default 0] Set to 1 to always test all assigned callbacks. This allows for multiple callbacks being assigned to the same address. If disabled, only the first assigned will be called.
// Webserver related
#define USE_BOOTSTRAP 0 // [Default 1] Set to 1 to enable use of bootstrap CSS for nicer webconfig. CSS is loaded from bootstrapcdn.com. Set to 0 to disable
#define ROOT_PREFIX "/knx" // [Default ""] This gets prepended to all webserver paths, default is empty string "". Set this to "/knx" if you want the config to be available on http://<ip>/knx
#define DISABLE_EEPROM_BUTTONS 1 // [Default 0] Set to 1 to disable the EEPROM buttons in the web ui.
#define DISABLE_REBOOT_BUTTON 1 // [Default 0] Set to 1 to disable the reboot button in the web ui.
#define DISABLE_RESTORE_BUTTON 1 // [Default 0] Set to 1 to disable the "restore defaults" button in the web ui.
// These values normally don't need adjustment
#ifndef MULTICAST_IP
#define MULTICAST_IP IPAddress(224, 0, 23, 12) // [Default IPAddress(224, 0, 23, 12)]
#else
#warning USING CUSTOM MULTICAST_IP
#endif
#ifndef MULTICAST_PORT
#define MULTICAST_PORT 3671 // [Default 3671]
#else
#warning USING CUSTOM MULTICAST_PORT
#endif
#define SEND_CHECKSUM 0
// Uncomment to enable printing out debug messages.
//#define ESP_KNX_DEBUG
/**
* END CONFIG
*/
#include "Arduino.h"
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include "DPT.h"
#define EEPROM_MAGIC (0xDEADBEEF00000000 + (MAX_CONFIG_SPACE) + (MAX_CALLBACK_ASSIGNMENTS << 16) + (MAX_CALLBACKS << 8))
// Define where debug output will be printed.
#ifndef DEBUG_PRINTER
#define DEBUG_PRINTER Serial
#endif
// Setup debug printing macros.
#ifdef ESP_KNX_DEBUG
#define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); }
#define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); }
#else
#define DEBUG_PRINT(...) {}
#define DEBUG_PRINTLN(...) {}
#endif
#define __ROOT_PATH ROOT_PREFIX"/"
#define __REGISTER_PATH ROOT_PREFIX"/register"
#define __DELETE_PATH ROOT_PREFIX"/delete"
#define __PHYS_PATH ROOT_PREFIX"/phys"
#define __EEPROM_PATH ROOT_PREFIX"/eeprom"
#define __CONFIG_PATH ROOT_PREFIX"/config"
#define __FEEDBACK_PATH ROOT_PREFIX"/feedback"
#define __RESTORE_PATH ROOT_PREFIX"/restore"
#define __REBOOT_PATH ROOT_PREFIX"/reboot"
/**
* Different service types, we are mainly interested in KNX_ST_ROUTING_INDICATION
*/
typedef enum __knx_service_type
{
KNX_ST_SEARCH_REQUEST = 0x0201,
KNX_ST_SEARCH_RESPONSE = 0x0202,
KNX_ST_DESCRIPTION_REQUEST = 0x0203,
KNX_ST_DESCRIPTION_RESPONSE = 0x0204,
KNX_ST_CONNECT_REQUEST = 0x0205,
KNX_ST_CONNECT_RESPONSE = 0x0206,
KNX_ST_CONNECTIONSTATE_REQUEST = 0x0207,
KNX_ST_CONNECTIONSTATE_RESPONSE = 0x0208,
KNX_ST_DISCONNECT_REQUEST = 0x0209,
KNX_ST_DISCONNECT_RESPONSE = 0x020A,
KNX_ST_DEVICE_CONFIGURATION_REQUEST = 0x0310,
KNX_ST_DEVICE_CONFIGURATION_ACK = 0x0311,
KNX_ST_TUNNELING_REQUEST = 0x0420,
KNX_ST_TUNNELING_ACK = 0x0421,
KNX_ST_ROUTING_INDICATION = 0x0530,
KNX_ST_ROUTING_LOST_MESSAGE = 0x0531,
KNX_ST_ROUTING_BUSY = 0x0532,
// KNX_ST_RLOG_START = 0x0600,
// KNX_ST_RLOG_END = 0x06FF,
KNX_ST_REMOTE_DIAGNOSTIC_REQUEST = 0x0740,
KNX_ST_REMOTE_DIAGNOSTIC_RESPONSE = 0x0741,
KNX_ST_REMOTE_BASIC_CONFIGURATION_REQUEST = 0x0742,
KNX_ST_REMOTE_RESET_REQUEST = 0x0743,
// KNX_ST_OBJSRV_START = 0x0800,
// KNX_ST_OBJSRV_END = 0x08FF,
} knx_service_type_t;
/**
* Differnt command types, first three are of main interest
*/
typedef enum __knx_command_type
{
KNX_CT_READ = 0x00,
KNX_CT_ANSWER = 0x01,
KNX_CT_WRITE = 0x02,
KNX_CT_INDIVIDUAL_ADDR_WRITE = 0x03,
KNX_CT_INDIVIDUAL_ADDR_REQUEST = 0x04,
KNX_CT_INDIVIDUAL_ADDR_RESPONSE = 0x05,
KNX_CT_ADC_READ = 0x06,
KNX_CT_ADC_ANSWER = 0x07,
KNX_CT_MEM_READ = 0x08,
KNX_CT_MEM_ANSWER = 0x09,
KNX_CT_MEM_WRITE = 0x0A,
//KNX_CT_UNKNOWN = 0x0B,
KNX_CT_MASK_VERSION_READ = 0x0C,
KNX_CT_MASK_VERSION_RESPONSE = 0x0D,
KNX_CT_RESTART = 0x0E,
KNX_CT_ESCAPE = 0x0F,
} knx_command_type_t;
/**
* cEMI message types, mainly KNX_MT_L_DATA_IND is interesting
*/
typedef enum __knx_cemi_msg_type
{
KNX_MT_L_DATA_REQ = 0x11,
KNX_MT_L_DATA_IND = 0x29,
KNX_MT_L_DATA_CON = 0x2E,
} knx_cemi_msg_type_t;
/**
* TCPI communication type
*/
typedef enum __knx_communication_type {
KNX_COT_UDP = 0x00, // Unnumbered Data Packet
KNX_COT_NDP = 0x01, // Numbered Data Packet
KNX_COT_UCD = 0x02, // Unnumbered Control Data
KNX_COT_NCD = 0x03, // Numbered Control Data
} knx_communication_type_t;
/**
* acpi for KNX_COT_NCD
*/
typedef enum __knx_cot_ncd_ack_type {
KNX_COT_NCD_ACK = 0x10, // Inform positively reception of the Previouly received telegram
KNX_COT_NCD_NACK = 0x11, // Inform negatively reception of the Previouly received telegram
} knx_cot_ncd_ack_type_t;
/**
* KNX/IP header
*/
typedef struct __knx_ip_pkt
{
uint8_t header_len; // Should always be 0x06
uint8_t protocol_version; // Should be version 1.0, transmitted as 0x10
uint16_t service_type; // See knx_service_type_t
union
{
struct {
uint8_t first_byte;
uint8_t second_byte;
} bytes;
uint16_t len;
} total_len; // header_len + rest of pkt. This is a bit weird as the spec says this: If the total number of bytes transmitted is greater than 252 bytes, the first “Total Length” byte is set to FF (255). Only in this case the second byte includes additional length information
uint8_t pkt_data[]; // This is of type cemi_msg_t
} knx_ip_pkt_t;
typedef struct __cemi_addi
{
uint8_t type_id;
uint8_t len;
uint8_t data[];
} cemi_addi_t;
typedef union __address
{
uint16_t value;
struct
{
uint8_t high;
uint8_t low;
} bytes;
struct __attribute__((packed))
{
uint8_t line:3;
uint8_t area:5;
uint8_t member;
} ga;
struct __attribute__((packed))
{
uint8_t line:4;
uint8_t area:4;
uint8_t member;
} pa;
uint8_t array[2];
} address_t;
typedef struct __cemi_service
{
union
{
struct
{
// Struct is reversed due to bit order
uint8_t confirm:1; // 0 = no error, 1 = error
uint8_t ack:1; // 0 = no ack, 1 = ack
uint8_t priority:2; // 0 = system, 1 = high, 2 = urgent/alarm, 3 = normal
uint8_t system_broadcast:1; // 0 = system broadcast, 1 = broadcast
uint8_t repeat:1; // 0 = repeated telegram, 1 = not repeated telegram
uint8_t reserved:1; // always zero
uint8_t frame_type:1; // 0 = extended, 1 = standard
} bits;
uint8_t byte;
} control_1;
union
{
struct
{
// Struct is reversed due to bit order
uint8_t extended_frame_format:4;
uint8_t hop_count:3;
uint8_t dest_addr_type:1; // 0 = individual, 1 = group
} bits;
uint8_t byte;
} control_2;
address_t source;
address_t destination;
uint8_t data_len; // length of data, excluding the tpci byte
struct
{
uint8_t apci:2; // If tpci.comm_type == KNX_COT_UCD or KNX_COT_NCD, then this is apparently control data?
uint8_t tpci_seq_number:4;
uint8_t tpci_comm_type:2; // See knx_communication_type_t
} pci;
uint8_t data[];
} cemi_service_t;
typedef struct __cemi_msg
{
uint8_t message_code;
uint8_t additional_info_len;
union
{
// cemi_addi_t additional_info[]; // Errors in GCC 10.1
cemi_addi_t additional_info[10]; // Changed to arbitrary number to fix compilation
cemi_service_t service_information;
} data;
} cemi_msg_t;
typedef enum __config_type
{
CONFIG_TYPE_UNKNOWN,
CONFIG_TYPE_INT,
CONFIG_TYPE_BOOL,
CONFIG_TYPE_STRING,
CONFIG_TYPE_OPTIONS,
CONFIG_TYPE_GA,
} config_type_t;
typedef enum __feedback_type
{
FEEDBACK_TYPE_UNKNOWN,
FEEDBACK_TYPE_INT,
FEEDBACK_TYPE_FLOAT,
FEEDBACK_TYPE_BOOL,
FEEDBACK_TYPE_ACTION,
} feedback_type_t;
typedef enum __config_flags
{
CONFIG_FLAGS_NO_FLAGS = 0,
CONFIG_FLAGS_VALUE_SET = 1,
} config_flags_t;
typedef enum __slot_flags
{
SLOT_FLAGS_EMPTY = 0, // Empty slots have no flags
SLOT_FLAGS_USED = 1,
} slot_flags_t;
typedef struct __message
{
knx_command_type_t ct;
address_t received_on;
uint8_t data_len;
uint8_t *data;
} message_t;
typedef bool (*enable_condition_t)(void);
typedef void (*callback_fptr_t)(message_t const &msg, void *arg);
typedef void (*feedback_action_fptr_t)(void *arg);
typedef uint8_t callback_id_t;
#define CALLBACK_ID_MAX UINT8_MAX
typedef uint8_t callback_assignment_id_t;
#define CALLBACK_ASSIGNMENT_ID_MAX UINT8_MAX
typedef uint8_t config_id_t;
typedef uint8_t feedback_id_t;
typedef struct __option_entry
{
char const *name;
uint8_t value;
} option_entry_t;
typedef struct __config
{
config_type_t type;
String name;
uint8_t offset;
uint8_t len;
enable_condition_t cond;
union {
option_entry_t *options;
} data;
} config_t;
extern char const *string_defaults[];
#define STRING_DEFAULT_DO_THIS (string_defaults[0])
#define STRING_DEFAULT_TRUE (string_defaults[1])
#define STRING_DEFAULT_FALSE (string_defaults[2])
#define STRING_DEFAULT_EMPTY (string_defaults[3])
typedef struct __feedback_float_options
{
uint8_t precision;
char const *prefix;
char const *suffix;
} feedback_float_options_t;
typedef struct __feedback_bool_options
{
char const *true_text;
char const *false_text;
} feedback_bool_options_t;
typedef struct __feedback_action_options
{
void *arg;
char const *btn_text;
} feedback_action_options_t;
typedef struct __feedback
{
feedback_type_t type;
String name;
enable_condition_t cond;
void *data;
union {
feedback_bool_options_t bool_options;
feedback_float_options_t float_options;
feedback_action_options_t action_options;
} options;
} feedback_t;
typedef struct __callback
{
uint8_t slot_flags;
callback_fptr_t fkt;
enable_condition_t cond;
void *arg;
String name;
} callback_t;
typedef struct __callback_assignment
{
uint8_t slot_flags;
address_t address;
callback_id_t callback_id;
} callback_assignment_t;
// FastPrecisePowf from tasmota/support_float.ino
//extern float FastPrecisePowf(const float x, const float y);
class ESPKNXIP {
public:
ESPKNXIP();
void load();
void start();
void start(ESP8266WebServer *srv);
void loop();
void save_to_eeprom();
void restore_from_eeprom();
callback_id_t callback_register(String name, callback_fptr_t cb, void *arg = nullptr, enable_condition_t cond = nullptr);
callback_assignment_id_t callback_assign(callback_id_t id, address_t val);
void callback_deregister(callback_id_t id);
void callback_unassign(callback_assignment_id_t id);
void physical_address_set(address_t const &addr);
address_t physical_address_get();
// Configuration functions
config_id_t config_register_string(String name, uint8_t len, String _default, enable_condition_t cond = nullptr);
config_id_t config_register_int(String name, int32_t _default, enable_condition_t cond = nullptr);
config_id_t config_register_bool(String name, bool _default, enable_condition_t cond = nullptr);
config_id_t config_register_options(String name, option_entry_t *options, uint8_t _default, enable_condition_t cond = nullptr);
config_id_t config_register_ga(String name, enable_condition_t cond = nullptr);
String config_get_string(config_id_t id);
int32_t config_get_int(config_id_t id);
bool config_get_bool(config_id_t id);
uint8_t config_get_options(config_id_t id);
address_t config_get_ga(config_id_t id);
void config_set_string(config_id_t id, String val);
void config_set_int(config_id_t id, int32_t val);
void config_set_bool(config_id_t, bool val);
void config_set_options(config_id_t id, uint8_t val);
void config_set_ga(config_id_t id, address_t const &val);
// Feedback functions
feedback_id_t feedback_register_int(String name, int32_t *value, enable_condition_t cond = nullptr);
feedback_id_t feedback_register_float(String name, float *value, uint8_t precision = 2, char const *prefix = nullptr, char const *suffix = nullptr, enable_condition_t cond = nullptr);
feedback_id_t feedback_register_bool(String name, bool *value, char const *true_text = nullptr, char const *false_text = nullptr, enable_condition_t cond = nullptr);
feedback_id_t feedback_register_action(String name, feedback_action_fptr_t value, char const *btn_text = nullptr, void *arg = nullptr, enable_condition_t = nullptr);
// Send functions
void send(address_t const &receiver, knx_command_type_t ct, uint8_t data_len, uint8_t *data);
void send_1bit(address_t const &receiver, knx_command_type_t ct, uint8_t bit);
void send_2bit(address_t const &receiver, knx_command_type_t ct, uint8_t twobit);
void send_4bit(address_t const &receiver, knx_command_type_t ct, uint8_t fourbit);
void send_1byte_int(address_t const &receiver, knx_command_type_t ct, int8_t val);
void send_1byte_uint(address_t const &receiver, knx_command_type_t ct, uint8_t val);
void send_2byte_int(address_t const &receiver, knx_command_type_t ct, int16_t val);
void send_2byte_uint(address_t const &receiver, knx_command_type_t ct, uint16_t val);
void send_2byte_float(address_t const &receiver, knx_command_type_t ct, float val);
void send_3byte_time(address_t const &receiver, knx_command_type_t ct, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds);
void send_3byte_time(address_t const &receiver, knx_command_type_t ct, time_of_day_t const &time) { send_3byte_time(receiver, ct, time.weekday, time.hours, time.minutes, time.seconds); }
void send_3byte_date(address_t const &receiver, knx_command_type_t ct, uint8_t day, uint8_t month, uint8_t year);
void send_3byte_date(address_t const &receiver, knx_command_type_t ct, date_t const &date) { send_3byte_date(receiver, ct, date.day, date.month, date.year); }
void send_3byte_color(address_t const &receiver, knx_command_type_t ct, uint8_t red, uint8_t green, uint8_t blue);
void send_3byte_color(address_t const &receiver, knx_command_type_t ct, color_t const &color) { send_3byte_color(receiver, ct, color.red, color.green, color.blue); }
void send_4byte_int(address_t const &receiver, knx_command_type_t ct, int32_t val);
void send_4byte_uint(address_t const &receiver, knx_command_type_t ct, uint32_t val);
void send_4byte_float(address_t const &receiver, knx_command_type_t ct, float val);
void send_14byte_string(address_t const &receiver, knx_command_type_t ct, const char *val);
void write_1bit(address_t const &receiver, uint8_t bit) { send_1bit(receiver, KNX_CT_WRITE, bit); }
void write_2bit(address_t const &receiver, uint8_t twobit) { send_2bit(receiver, KNX_CT_WRITE, twobit); }
void write_4bit(address_t const &receiver, uint8_t fourbit) { send_4bit(receiver, KNX_CT_WRITE, fourbit); }
void write_1byte_int(address_t const &receiver, int8_t val) { send_1byte_int(receiver, KNX_CT_WRITE, val); }
void write_1byte_uint(address_t const &receiver, uint8_t val) { send_1byte_uint(receiver, KNX_CT_WRITE, val); }
void write_2byte_int(address_t const &receiver, int16_t val) { send_2byte_int(receiver, KNX_CT_WRITE, val); }
void write_2byte_uint(address_t const &receiver, uint16_t val) { send_2byte_uint(receiver, KNX_CT_WRITE, val); }
void write_2byte_float(address_t const &receiver, float val) { send_2byte_float(receiver, KNX_CT_WRITE, val); }
void write_3byte_time(address_t const &receiver, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds) { send_3byte_time(receiver, KNX_CT_WRITE, weekday, hours, minutes, seconds); }
void write_3byte_time(address_t const &receiver, time_of_day_t const &time) { send_3byte_time(receiver, KNX_CT_WRITE, time.weekday, time.hours, time.minutes, time.seconds); }
void write_3byte_date(address_t const &receiver, uint8_t day, uint8_t month, uint8_t year) { send_3byte_date(receiver, KNX_CT_WRITE, day, month, year); }
void write_3byte_date(address_t const &receiver, date_t const &date) { send_3byte_date(receiver, KNX_CT_WRITE, date.day, date.month, date.year); }
void write_3byte_color(address_t const &receiver, uint8_t red, uint8_t green, uint8_t blue) { send_3byte_color(receiver, KNX_CT_WRITE, red, green, blue); }
void write_3byte_color(address_t const &receiver, color_t const &color) { send_3byte_color(receiver, KNX_CT_WRITE, color); }
void write_4byte_int(address_t const &receiver, int32_t val) { send_4byte_int(receiver, KNX_CT_WRITE, val); }
void write_4byte_uint(address_t const &receiver, uint32_t val) { send_4byte_uint(receiver, KNX_CT_WRITE, val); }
void write_4byte_float(address_t const &receiver, float val) { send_4byte_float(receiver, KNX_CT_WRITE, val);}
void write_14byte_string(address_t const &receiver, const char *val) { send_14byte_string(receiver, KNX_CT_WRITE, val); }
void answer_1bit(address_t const &receiver, uint8_t bit) { send_1bit(receiver, KNX_CT_ANSWER, bit); }
void answer_2bit(address_t const &receiver, uint8_t twobit) { send_2bit(receiver, KNX_CT_ANSWER, twobit); }
void answer_4bit(address_t const &receiver, uint8_t fourbit) { send_4bit(receiver, KNX_CT_ANSWER, fourbit); }
void answer_1byte_int(address_t const &receiver, int8_t val) { send_1byte_int(receiver, KNX_CT_ANSWER, val); }
void answer_1byte_uint(address_t const &receiver, uint8_t val) { send_1byte_uint(receiver, KNX_CT_ANSWER, val); }
void answer_2byte_int(address_t const &receiver, int16_t val) { send_2byte_int(receiver, KNX_CT_ANSWER, val); }
void answer_2byte_uint(address_t const &receiver, uint16_t val) { send_2byte_uint(receiver, KNX_CT_ANSWER, val); }
void answer_2byte_float(address_t const &receiver, float val) { send_2byte_float(receiver, KNX_CT_ANSWER, val); }
void answer_3byte_time(address_t const &receiver, uint8_t weekday, uint8_t hours, uint8_t minutes, uint8_t seconds) { send_3byte_time(receiver, KNX_CT_ANSWER, weekday, hours, minutes, seconds); }
void answer_3byte_time(address_t const &receiver, time_of_day_t const &time) { send_3byte_time(receiver, KNX_CT_ANSWER, time.weekday, time.hours, time.minutes, time.seconds); }
void answer_3byte_date(address_t const &receiver, uint8_t day, uint8_t month, uint8_t year) { send_3byte_date(receiver, KNX_CT_ANSWER, day, month, year); }
void answer_3byte_date(address_t const &receiver, date_t const &date) { send_3byte_date(receiver, KNX_CT_ANSWER, date.day, date.month, date.year); }
void answer_3byte_color(address_t const &receiver, uint8_t red, uint8_t green, uint8_t blue) { send_3byte_color(receiver, KNX_CT_ANSWER, red, green, blue); }
void answer_3byte_color(address_t const &receiver, color_t const &color) { send_3byte_color(receiver, KNX_CT_ANSWER, color); }
void answer_4byte_int(address_t const &receiver, int32_t val) { send_4byte_int(receiver, KNX_CT_ANSWER, val); }
void answer_4byte_uint(address_t const &receiver, uint32_t val) { send_4byte_uint(receiver, KNX_CT_ANSWER, val); }
void answer_4byte_float(address_t const &receiver, float val) { send_4byte_float(receiver, KNX_CT_ANSWER, val);}
void answer_14byte_string(address_t const &receiver, const char *val) { send_14byte_string(receiver, KNX_CT_ANSWER, val); }
bool data_to_bool(uint8_t *data);
int8_t data_to_1byte_int(uint8_t *data);
uint8_t data_to_1byte_uint(uint8_t *data);
int16_t data_to_2byte_int(uint8_t *data);
uint16_t data_to_2byte_uint(uint8_t *data);
float data_to_2byte_float(uint8_t *data);
color_t data_to_3byte_color(uint8_t *data);
time_of_day_t data_to_3byte_time(uint8_t *data);
date_t data_to_3byte_data(uint8_t *data);
int32_t data_to_4byte_int(uint8_t *data);
uint32_t data_to_4byte_uint(uint8_t *data);
float data_to_4byte_float(uint8_t *data);
static address_t GA_to_address(uint8_t area, uint8_t line, uint8_t member)
{
// Yes, the order is correct, see the struct definition above
address_t tmp = {.ga={line, area, member}};
return tmp;
}
static address_t PA_to_address(uint8_t area, uint8_t line, uint8_t member)
{
// Yes, the order is correct, see the struct definition above
address_t tmp = {.pa={line, area, member}};
return tmp;
}
private:
void __start();
void __loop_knx();
// Webserver functions
void __loop_webserver();
void __handle_root();
void __handle_register();
void __handle_delete();
void __handle_set();
#if !DISABLE_EEPROM_BUTTONS
void __handle_eeprom();
#endif
void __handle_config();
void __handle_feedback();
#if !DISABLE_RESTORE_BUTTONS
void __handle_restore();
#endif
#if !DISABLE_REBOOT_BUTTONS
void __handle_reboot();
#endif
void __config_set_flags(config_id_t id, config_flags_t flags);
void __config_set_string(config_id_t id, String &val);
void __config_set_int(config_id_t id, int32_t val);
void __config_set_bool(config_id_t id, bool val);
void __config_set_options(config_id_t id, uint8_t val);
void __config_set_ga(config_id_t id, address_t const &val);
bool __callback_is_id_valid(callback_id_t id);
callback_assignment_id_t __callback_register_assignment(address_t address, callback_id_t id);
void __callback_delete_assignment(callback_assignment_id_t id);
//static inline float pow(float a, float b) { return FastPrecisePowf(a, b); }
ESP8266WebServer *server;
address_t physaddr;
WiFiUDP udp;
callback_assignment_id_t registered_callback_assignments;
callback_assignment_id_t free_callback_assignment_slots;
callback_assignment_t callback_assignments[MAX_CALLBACK_ASSIGNMENTS];
callback_id_t registered_callbacks;
callback_id_t free_callback_slots;
callback_t callbacks[MAX_CALLBACKS];
config_id_t registered_configs;
uint8_t custom_config_data[MAX_CONFIG_SPACE];
uint8_t custom_config_default_data[MAX_CONFIG_SPACE];
config_t custom_configs[MAX_CONFIGS];
feedback_id_t registered_feedbacks;
feedback_t feedbacks[MAX_FEEDBACKS];
uint16_t __ntohs(uint16_t);
};
// Global "singleton" object
extern ESPKNXIP knx;
#endif

View File

@ -1 +0,0 @@
KNX header files. Workaround to exclude KNX library when not needed

View File

@ -1,195 +0,0 @@
# JSMN lightweight JSON parser for Tasmota
Intro: this library uses the JSMN in-place JSON parser.
See https://github.com/zserge/jsmn and https://zserge.com/jsmn/
It is proposed as a replacement for ArduinoJson. It has less features, does only parsing but does it in a very efficient way.
## Benefits
First, the memory impact is very low: 4 bytes per token and no need to add an extra buffer for values.
Second, the code is much smaller than ArduinoJson by 5-7KB.
## How to use
`{"Device":"0x1234","Power":true,"Temperature":25.5}`
The JSON above is split into 8 tokens, and requires 32 bytes of dynamic memory.
- Token 0: `OBJECT`, size=3: `{"Device":"0x1234","Power":true,"Temperature":25.5}`
- Token 1: `KEY`: `Device`
- Token 2: `STRING`: `0x1234`
- Token 3: `KEY`: `Power`
- Token 4: `BOOL_TRUE`: `true`
- Token 5: `KEY`: `Temperature`
- Token 6: `FLOAT`: `25.5`
- Token 7: `INVALID`
If what you need is to parse a JSON Object for values with default values:
```
#include "JsonParser.h"
char json_buffer[] = "{\"Device\":\"0x1234\",\"Power\":true,\"Temperature\":25.6}";
JsonParser parser(json_buffer);
JsonParserObject root = parser.getRootObject();
if (!root) { ResponseCmndChar_P(PSTR("Invalid JSON")); return; }
uint16_t d = root.getUInt(PSTR("DEVICE"), 0xFFFF); // case insensitive
bool b = root.getBool(PSTR("Power"), false);
float f = root.getFloat(PSTR("Temperature), -100);
```
Alternative pattern, if you want to test the existence of the attribute first:
```
#include "JsonParser.h"
char json_buffer[] = "{\"Device\":\"0x1234\",\"Power\":true,\"Temperature\":25.6}";
JsonParser parser(json_buffer);
JsonParserObject root = parser.getRootObject();
if (!root) { ResponseCmndChar_P(PSTR("Invalid JSON")); return; }
JsonParserToken val = root[PSTR("DEVICE")];
if (val) {
d = val.getUInt();
}
val = root[PSTR("Power")];
if (val) {
b = val.getBool();
}
val = root[PSTR("Temperature)];
if (val) {
f = val.getFloat();
}
```
WARNING: never use the following form:
```
JsonParserObject root = JsonParser(json_buffer).getRootObject();
```
In this case, the `JsonParser` object is temporary and destroyed at the end of the expression. Setting the JsonParser to a local variable ensures that the lifetime of the object is extended to the end of the scope.
## Types and conversion
JSMN relies on the concept of JSON Tokens `JsonParserToken`. Tokens do not hold any data, but point to token boundaries in JSON string instead. Every jsmn token has a type, which indicates the type of corresponding JSON token. JSMN for Tasmota extends the type from JSMN to ease further parsing.
Types are:
- `INVALID` invalid token or end of stream, see Error Handling below
- `OBJECT` a JSON sub-object, `size()` contains the number of key/values of the object
- `ARRAY` a JSON array, `size()` contains the number of sub values
- `STRING` a JSON string, return the sub-string, unescaped, without surrounding quotes. UTF-8 is supported.
- `PRIMITIVE` an unrecognized JSON token, consider as an error
- `KEY` a JSON key in an object as a string
- `NULL` a JSON `null` value, automatically converted to `0` or `""`
- `BOOL_FALSE` a JSON `false` value, automatically converted to `0` or `""`
- `BOOL_TRUE` a JSON `true` value, automatically converted to `1` or `""`
- `UINT` a JSON unsigned int
- `INT` a JSON negative int
- `FLOAT` a JSON floating point value, i.e. a numerical value containing a decimal ot `.`
Note: values are converted in this priority: 1/ `UINT`, 2/ `INT`, 3/ `FLOAT`.
`JsonParserToken` support the following getters:
- `getBool()`: returns true if 'true' or non-zero int (default false)
- `getUInt()`: converts to unsigned int (default 0), boolean true is 1
- `getInt()`: converts to signed int (default 0), boolean true is 1
- `getULong()`: converts to unsigned 64 bits (default 0), boolean is 1
- `getStr()`: converts to string (default "")
There are variants of the same function for which you can choose the default values. Remember that using a getter if the token type is INVALID returns the default value.
Conversion to `OBJECT` or `ARRAY`:
- `getObject()`: converts token to `OBJECT` or `INVALID`
- `getArray()`: converts token to `ARRAY` or `INVALID`
For `JsonParserKey`:
- `getValue()`: returns the value token associated to the key
## Checking Token types
Type checking for `JsonParserToken`:
- `isSingleToken()` returns `true` for a single level token, `false` for `OBJECT`, `ARRAY` and `INVALID`
- `isKey()` returns `true` for a `KEY` within an `OBJECT`
- `isStr()` returns `true` for `STRING` (note: other types can still be read as strings with `getStr()`)
- `isNull()` returns `true` for `NULL`
- `isBool()` returns `true` for `BOOL_FALSE` or `BOOL_TRUE`
- `isUInt()` returns `true` for `UINT` (see below for number conversions)
- `isInt()` returns `true` for `INT` (see below for number conversions)
- `isFloat()` returns `true` for `FLOAT` (see below for number conversions)
- `isNum()` returns `true` for any numerical value, i.e. `UINT`, `INT` or `FLOAT`
- `isObject()` returns `true` for `OBJECT`
- `isArray()` returns `true` for `ARRAY`
- `isValid()` returns `true`for any type except `INVALID`
JSMN for Tasmota provides sub-classes:
- `JsonParserKey` of type `KEY` or `INVALID`, used as a return value for Object iterators
- `JsonParserObject` of type `OBJECT` or `INVALID`, providing iterators
- `JsonParserArray` of type `ARRAY` or `INVALID`, providing iterators
Converting from Token to Object or Array is done with `token.getObject()` or `token.getArray()`. If the conversion is invalid, the resulting object has type `INVALID` (see Error Handling).
## Iterators and accessors for Objects and Arrays
The `JsonParserObject` provides an easy to use iterator:
```
JsonParserToken obj = <...>
for (auto key : obj) {
// key is of type JsonParserKey
JsonParserToken valie = key.getValue(); // retrieve the value associated to key
}
```
If the object contains only one element, you can retrieve it with `obj.getFirstElement()`.
You can access any key with `obj["Key"]`. Note: the search is on purpose **case insensitive** as it is the norm in Tasmota. The search string can be in PROGMEM. If the token is not found, it is of type `INVALID`.
The `JsonParserArray` provides an easy to use iterator:
```
JsonParserArray arr = <...>
for (auto elt : arr) {
// elt is of type JsonParserToken
}
```
You can access any element in the array with the `[]` operator. Ex: `arr[0]` fof first element. If the index is invalid, the token has type `INVALID`.
## Memory
The `JsonParserToken` fits in 32 bits, so it can be freely returned or copied without any penalty of object copying. Hence it doesn't need the `const` modifier either, since it is always passed by value.
## Error handling
This library uses a `zero error` pattern. This means that calls never report any error nor throw exceptions. If something wrong happens (bad JSON, token not found...), function return an **Invalid Token**. You can call any function on an Invalid Token, they will always return the same Invalid Token (aka fixed point).
You can easily test if the current token is invalid with the following:
Short version:
```
if (token) { /* token is valid */ }
```
Long version:
```
if (token->isValiid()) { /* token is valid */ }
```
This pattern allows to cascade calls and check only the final result:
```
char json_buffer[] = "<json>";
JsonParserObject json = JsonParser(json_buffer).getRootObject();
JsonParserToken zbstatus_tok = json["ZbStatus"];
JsonParserObject zbstatus = zbstatus_tok.getObject();
if (zbstatus) { /* do some stuff */
// reaching this point means: JSON is valid, there is a root object, there is a `ZbStatus` key and it contains a sub-object
}
```
Warning: there is an explicit convert to `bool` to allow the short version. Be careful, `(bool)token` is equivalent to `token->isValid()`, it is **NOT** equivalent to `token->getBool()`.
## Limits
Please keep in mind the current limits for this library:
- Maximum JSON buffer size 2047 bytes
- Maximum 63 JSON tokens
- No support for exponent in floats (i.e. `1.0e3` is invalid)
These limits shouldn't be a problem since buffers in Tasmota are limited to 1.2KB. The support for exponent in floats is commented out and can be added if needed (slight increase in Flash size)

View File

@ -1,8 +0,0 @@
name=JSMN JSON parser customized and optimized for ESP8266 and Tasmota
version=1.0
author=Serge Zaitsev, Stephan Hadinger
maintainer=Stephan <stephan.hadinger@gmail.com>
sentence=Lightweight in-place JSON parser
paragraph=
url=https://github.com/zserge/jsmn
architectures=esp8266,esp32

View File

@ -1,192 +0,0 @@
/*
JsonGenerator.cpp - lightweight JSON parser
Copyright (C) 2021 Stephan Hadinger
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/>.
*/
#include "JsonGenerator.h"
/*********************************************************************************************\
* JSON Generator for Arrays
\*********************************************************************************************/
void JsonGeneratorArray::pre(void) {
// remove trailing ']'
val.remove(val.length()-1);
if (val.length() > 1) { // if not empty, prefix with comma
val += ',';
}
}
// void JsonGeneratorArray::post(void) {
// val += ']';
// }
// Add signed int (32 bits)
void JsonGeneratorArray::add(int32_t uval32) {
pre();
val += uval32;
post();
}
// Add unsigned int (32 bits)
void JsonGeneratorArray::add(uint32_t uval32) {
pre();
val += uval32;
post();
}
// Add a raw string, that will not be escaped.
// Can be used to add a sub-array, sub-object or 'null', 'true', 'false' values
void JsonGeneratorArray::addStrRaw(const char * sval) {
pre();
val += sval;
post();
}
// Add a JSON String (will be escaped)
void JsonGeneratorArray::addStr(const char * sval) {
pre();
val += '"';
val += EscapeJSONString(sval).c_str();
val += '"';
post();
}
/*********************************************************************************************\
* JSON Generator for Objects
\*********************************************************************************************/
void JsonGeneratorObject::pre(const char * key) {
// remove trailing '}'
val.remove(val.length()-1);
if (val.length() > 1) { // if not empty, prefix with comma
val += ',';
}
val += '"';
val += EscapeJSONString(key);
val += '"';
val += ':';
}
// void JsonGeneratorObject::post(void) {
// val += '}';
// }
// Add signed int (32 bits)
void JsonGeneratorObject::add(const char* key, int32_t uval32) {
pre(key);
val += uval32;
post();
}
// Add unsigned int (32 bits)
void JsonGeneratorObject::add(const char* key, uint32_t uval32) {
pre(key);
val += uval32;
post();
}
void JsonGeneratorObject::add(const char* key, const String & str) {
pre(key);
val += '"';
val += EscapeJSONString(str.c_str()).c_str();
val += '"';
post();
}
// Add up to 32 bits hex value
void JsonGeneratorObject::addHex32(const char* key, uint32_t uval32) {
char hex[16];
snprintf_P(hex, sizeof(hex), PSTR("\"0x%8X\""), uval32);
addStrRaw(key, hex);
}
// Add a raw string, that will not be escaped.
// Can be used to add a sub-array, sub-object or 'null', 'true', 'false' values
void JsonGeneratorObject::addStrRaw(const char* key, const char * sval) {
pre(key);
val += sval;
post();
}
// Add a JSON String (will be escaped)
void JsonGeneratorObject::addStr(const char* key, const char * sval) {
pre(key);
val += '"';
val += EscapeJSONString(sval).c_str();
val += '"';
post();
}
/*********************************************************************************************\
* JSON Generator for Arrays
\*********************************************************************************************/
// does the character needs to be escaped, and if so with which character
static char EscapeJSONChar(char c) {
if ((c == '\"') || (c == '\\')) {
return c;
}
if (c == '\n') { return 'n'; }
if (c == '\t') { return 't'; }
if (c == '\r') { return 'r'; }
if (c == '\f') { return 'f'; }
if (c == '\b') { return 'b'; }
return 0;
}
String EscapeJSONString(const char *str) {
// As this function is used in ResponseCmndChar() and ResponseCmndIdxChar()
// it needs to be PROGMEM safe!
String r("");
if (nullptr == str) { return r; }
bool needs_escape = false;
size_t len_out = 1;
const char* c = str;
char ch = '.';
while (ch != '\0') {
ch = pgm_read_byte(c++);
if (EscapeJSONChar(ch)) {
len_out++;
needs_escape = true;
}
len_out++;
}
if (needs_escape) {
// we need to escape some chars
// allocate target buffer
r.reserve(len_out);
c = str;
char *d = r.begin();
char ch = '.';
while (ch != '\0') {
ch = pgm_read_byte(c++);
char c2 = EscapeJSONChar(ch);
if (c2) {
*d++ = '\\';
*d++ = c2;
} else {
*d++ = ch;
}
}
*d = 0; // add NULL terminator
r = (char*) r.begin(); // assign the buffer to the string
} else {
r = FPSTR(str);
}
return r;
}

View File

@ -1,73 +0,0 @@
/*
JsonGenerator.h - lightweight JSON generator
Copyright (C) 2021 Stephan Hadinger
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 __JSON_GENERATOR__
#define __JSON_GENERATOR__
#include <Arduino.h>
#include <string.h>
#include <stdlib.h>
extern String EscapeJSONString(const char *str);
/*********************************************************************************************\
* JSON Generator for Arrays
\*********************************************************************************************/
class JsonGeneratorArray {
public:
JsonGeneratorArray(): val(F("[]")) {} // start with empty array
void add(uint32_t uval32);
void add(int32_t uval32);
void addStrRaw(const char * sval);
void addStr(const char * sval);
inline String &toString(void) { return val; }
protected:
void pre(void);
void post(void) { val += ']'; }
String val;
};
/*********************************************************************************************\
* JSON Generator for Objects
\*********************************************************************************************/
class JsonGeneratorObject {
public:
JsonGeneratorObject(): val(F("{}")) {} // start with empty object
void add(const char* key, uint32_t uval32);
void add(const char* key, int32_t uval32);
void add(const char* key, const String & str);
void addHex32(const char* key, uint32_t uval32);
void addStrRaw(const char* key, const char * sval);
void addStr(const char* key, const char * sval);
inline String &toString(void) { return val; }
protected:
void pre(const char * key);
void post(void) { val += '}'; }
String val;
};
#endif // __JSON_PARSER__

View File

@ -1,552 +0,0 @@
/*
JsonParser.cpp - lightweight JSON parser
Copyright (C) 2021 Stephan Hadinger
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/>.
*/
#include "JsonParser.h"
#include <Arduino.h>
/*********************************************************************************************\
* Utilities
\*********************************************************************************************/
const char * k_current_json_buffer = "";
// returns nibble value or -1 if not an hex digit
static int32_t asc2byte(char chr) {
if (chr >= '0' && chr <= '9') { return chr - '0'; }
else if (chr >= 'A' && chr <= 'F') { return chr + 10 - 'A'; }
else if (chr >= 'a' && chr <= 'f') { return chr + 10 - 'a'; }
return -1;
}
/*********************************************************************************************\
* Lightweight String to Float, because atof() or strtof() takes 10KB
*
* To remove code, exponents are not parsed
* (commented out below, just in case we need them after all)
*
* Moved to double to be able to parse 32 bits int as well without loss in accuracy
\*********************************************************************************************/
// Inspired from https://searchcode.com/codesearch/view/22115068/
double JsonParserToken::json_strtof(const char* s) {
const char* p = s;
double value = 0.;
int32_t sign = +1;
double factor;
uint32_t base = 10; // support hex mode if start with Ox or OX
// unsigned int expo;
while (isspace(*p)){ // skip any leading white-spaces
p++;
}
switch (*p) {
case '-': sign = -1; // no break on purpose
case '+': p++;
default : break;
}
if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) { // detect hex mode
base = 16;
p += 2;
}
int32_t v; // temp nibble value
while ((v = asc2byte(*p)) >= 0) {
value = value * base + v;
p++;
}
if (*p == '.' ) {
factor = 1.0f;
p++;
while ((v = asc2byte(*p)) >= 0) {
factor /= base;
value += v * factor;
p++;
}
}
// if ( (*p | 32) == 'e' ) {
// expo = 0;
// factor = 10.L;
// switch (*++p) { // ja hier weiß ich nicht, was mindestens nach einem 'E' folgenden MUSS.
// case '-': factor = 0.1;
// case '+': p++;
// break;
// case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
// break;
// default : value = 0.L;
// p = s;
// goto done;
// }
// while ( (unsigned int)(*p - '0') < 10u )
// expo = 10 * expo + (*p++ - '0');
// while ( 1 ) {
// if ( expo & 1 )
// value *= factor;
// if ( (expo >>= 1) == 0 )
// break;
// factor *= factor;
// }
// }
// done:
// if ( endptr != NULL )
// *endptr = (char*)p;
return value * sign;
}
/*********************************************************************************************\
* Read-only JSON token object, fits in 32 bits
\*********************************************************************************************/
void JsonParserToken::skipToken(void) {
// printf("skipToken type = %d %s\n", t->type, json_string + t->start);
switch (t->type) {
case JSMN_OBJECT:
skipObject();
break;
case JSMN_ARRAY:
skipArray();
break;
case JSMN_STRING:
case JSMN_PRIMITIVE:
case JSMN_KEY:
case JSMN_NULL:
case JSMN_BOOL_FALSE:
case JSMN_BOOL_TRUE:
case JSMN_FLOAT:
case JSMN_INT:
case JSMN_UINT:
t++; // skip 1 token
break;
case JSMN_INVALID:
default:
break; // end of stream, stop advancing
}
}
void JsonParserToken::skipArray(void) {
if (t->type == JSMN_ARRAY) {
size_t obj_size = t->size;
t++; // array root
if (t->type == JSMN_INVALID) { return; }
for (uint32_t i=0; i<obj_size; i++) {
skipToken();
}
}
}
// skip to right after the current Object
void JsonParserToken::skipObject(void) {
if (t->type == JSMN_OBJECT) {
size_t obj_size = t->size;
t++; // object root
if (t->type == JSMN_INVALID) { return; }
for (uint32_t i=0; i<obj_size; i++) {
t++; // skip Key
if (t->type == JSMN_INVALID) { return; }
skipToken();
}
}
}
/*********************************************************************************************\
* JsonParserArray
\*********************************************************************************************/
JsonParserArray::JsonParserArray(const jsmntok_t * token) : JsonParserToken(token) {
if (t->type != JSMN_ARRAY) {
t = &token_bad;
}
}
JsonParserArray::JsonParserArray(const JsonParserToken token) : JsonParserToken(token.t) {
if (t->type != JSMN_ARRAY) {
t = &token_bad;
}
}
JsonParserArray::const_iterator::const_iterator(const JsonParserArray t): tok(t), remaining(0) {
if (tok.t == &token_bad) { tok.t = nullptr; }
if (nullptr != tok.t) {
// ASSERT type == JSMN_ARRAY by constructor
remaining = tok.t->size;
tok.nextOne(); // skip array root token
}
}
JsonParserArray::const_iterator JsonParserArray::const_iterator::const_iterator::operator++() {
if (remaining <= 1) { tok.t = nullptr; }
else {
remaining--;
tok.skipToken(); // munch value
if (tok.t->type == JSMN_INVALID) { tok.t = nullptr; } // unexpected end of stream
}
return *this;
}
JsonParserToken JsonParserArray::operator[](int32_t i) const {
if ((i >= 0) && (i < t->size)) {
uint32_t index = 0;
for (const auto elt : *this) {
if (i == index) {
return elt;
}
index++;
}
}
// fallback
return JsonParserToken(&token_bad);
}
/*********************************************************************************************\
* JsonParserObject
\*********************************************************************************************/
JsonParserObject::JsonParserObject(const jsmntok_t * token) : JsonParserToken(token) {
if (t->type != JSMN_OBJECT) {
t = &token_bad;
}
}
JsonParserObject::JsonParserObject(const JsonParserToken token) : JsonParserToken(token.t) {
if (t->type != JSMN_OBJECT) {
t = &token_bad;
}
}
JsonParserKey JsonParserObject::getFirstElement(void) const {
if (t->size > 0) {
return JsonParserKey(t+1); // return next element and cast to Key
} else {
return JsonParserKey(&token_bad);
}
}
JsonParserObject::const_iterator::const_iterator(const JsonParserObject t): tok(t), remaining(0) {
if (tok.t == &token_bad) { tok.t = nullptr; }
if (nullptr != tok.t) {
// ASSERT type == JSMN_OBJECT by constructor
remaining = tok.t->size;
tok.nextOne();
}
}
JsonParserObject::const_iterator JsonParserObject::const_iterator::operator++() {
if (remaining <= 1) { tok.t = nullptr; }
else {
remaining--;
tok.nextOne(); // munch key
if (tok.t->type == JSMN_INVALID) { tok.t = nullptr; } // unexpected end of stream
tok.skipToken(); // munch value
if (tok.t->type == JSMN_INVALID) { tok.t = nullptr; } // unexpected end of stream
}
return *this;
}
/*********************************************************************************************\
* JsonParserKey
\*********************************************************************************************/
JsonParserKey::JsonParserKey(const jsmntok_t * token) : JsonParserToken(token) {
if (t->type != JSMN_KEY) {
t = &token_bad;
}
}
JsonParserKey::JsonParserKey(const JsonParserToken token) : JsonParserToken(token.t) {
if (t->type != JSMN_KEY) {
t = &token_bad;
}
}
JsonParserToken JsonParserKey::getValue(void) const {
return JsonParserToken(t+1);
}
/*********************************************************************************************\
* Implementation for JSON Parser
\*********************************************************************************************/
// fall-back token object when parsing failed
const jsmntok_t token_bad = { JSMN_INVALID, 0, 0, 0 };
JsonParser::JsonParser(char * json_in) :
_size(0),
_token_len(0),
_tokens(nullptr),
_json(nullptr)
{
parse(json_in);
}
JsonParser::~JsonParser() {
this->free();
}
const JsonParserObject JsonParser::getRootObject(void) const {
return JsonParserObject(&_tokens[0]);
}
const JsonParserToken JsonParser::operator[](int32_t i) const {
if ((_token_len > 0) && (i < _token_len)) {
return JsonParserToken(&_tokens[i]);
} else {
return JsonParserToken(&token_bad);
}
}
// pointer arithmetic
// ptrdiff_t JsonParser::index(JsonParserToken token) const {
// return token.t - _tokens;
// }
bool JsonParserToken::getBool(bool val) const {
if (t->type == JSMN_INVALID) { return val; }
if (t->type == JSMN_BOOL_TRUE) return true;
if (t->type == JSMN_BOOL_FALSE) return false;
if (isSingleToken()) return strtol(&k_current_json_buffer[t->start], nullptr, 0) != 0;
return false;
}
int32_t JsonParserToken::getInt(int32_t val) const {
if (t->type == JSMN_INVALID) { return val; }
if (t->type == JSMN_BOOL_TRUE) return 1;
if (isSingleToken()) return strtol(&k_current_json_buffer[t->start], nullptr, 0);
return 0;
}
uint32_t JsonParserToken::getUInt(uint32_t val) const {
if (t->type == JSMN_INVALID) { return val; }
if (t->type == JSMN_BOOL_TRUE) return 1;
if (isSingleToken()) return strtoul(&k_current_json_buffer[t->start], nullptr, 0);
return 0;
}
uint64_t JsonParserToken::getULong(uint64_t val) const {
if (t->type == JSMN_INVALID) { return val; }
if (t->type == JSMN_BOOL_TRUE) return 1;
if (isSingleToken()) return strtoull(&k_current_json_buffer[t->start], nullptr, 0);
return 0;
}
float JsonParserToken::getFloat(float val) const {
if (t->type == JSMN_INVALID) { return val; }
if (t->type == JSMN_BOOL_TRUE) return 1;
if (isSingleToken()) return json_strtof(&k_current_json_buffer[t->start]);
return 0;
}
const char * JsonParserToken::getStr(const char * val) const {
if (t->type == JSMN_INVALID) { return val; }
if (t->type == JSMN_NULL) return "null";
return (t->type >= JSMN_STRING) ? &k_current_json_buffer[t->start] : val;
}
JsonParserObject JsonParserToken::getObject(void) const { return JsonParserObject(*this); }
JsonParserArray JsonParserToken::getArray(void) const { return JsonParserArray(*this); }
bool JsonParserToken::getBool(void) const { return getBool(false); }
int32_t JsonParserToken::getInt(void) const { return getInt(0); }
uint32_t JsonParserToken::getUInt(void) const { return getUInt(0); }
uint64_t JsonParserToken::getULong(void) const { return getULong(0); }
float JsonParserToken::getFloat(void) const { return getFloat(0); }
const char * JsonParserToken::getStr(void) const { return getStr(""); }
int32_t JsonParserObject::getInt(const char * needle, int32_t val) const {
return (*this)[needle].getInt(val);
}
uint32_t JsonParserObject::getUInt(const char * needle, uint32_t val) const {
return (*this)[needle].getUInt(val);
}
uint64_t JsonParserObject::getULong(const char * needle, uint64_t val) const {
return (*this)[needle].getULong(val);
}
float JsonParserObject::getFloat(const char * needle, float val) const {
return (*this)[needle].getFloat(val);
}
const char * JsonParserObject::getStr(const char * needle, const char * val) const {
return (*this)[needle].getStr(val);
}
const char * JsonParserObject::getStr(const char * needle) const {
return getStr(needle, "");
}
void JsonParser::parse(char * json_in) {
k_current_json_buffer = "";
if (nullptr == json_in) { return; }
_json = json_in;
k_current_json_buffer = _json;
size_t json_len = strlen(json_in);
if (_size == 0) {
// first run is used to count tokens before allocation
jsmn_init(&this->_parser);
int32_t _token_len = jsmn_parse(&this->_parser, json_in, json_len, nullptr, 0);
if (_token_len <= 0) { return; }
_size = _token_len + 1;
}
allocate();
jsmn_init(&this->_parser);
_token_len = jsmn_parse(&this->_parser, json_in, json_len, _tokens, _size);
// TODO error checking
if (_token_len >= 0) {
postProcess(json_len);
}
}
// post process the parsing by pre-munching extended types
void JsonParser::postProcess(size_t json_len) {
// add an end marker
if (_size > _token_len) {
_tokens[_token_len].type = JSMN_INVALID;
_tokens[_token_len].start = json_len;
_tokens[_token_len].len = 0;
_tokens[_token_len].size = 0;
}
for (uint32_t i=0; i<_token_len; i++) {
jsmntok_t & tok = _tokens[i];
if (tok.type >= JSMN_STRING) {
// we modify to null-terminate the primitive
_json[tok.start + tok.len] = 0;
}
if (tok.type == JSMN_STRING) {
if (tok.size == 1) { tok.type = JSMN_KEY; }
else { json_unescape(&_json[tok.start]); }
} else if (tok.type == JSMN_PRIMITIVE) {
if (tok.len >= 0) {
// non-null string
char c0 = _json[tok.start];
switch (c0) {
case 'n':
case 'N':
tok.type = JSMN_NULL;
break;
case 't':
case 'T':
tok.type = JSMN_BOOL_TRUE;
break;
case 'f':
case 'F':
tok.type = JSMN_BOOL_FALSE;
break;
case '-':
case '0'...'9':
// look if there is a '.' in the string
if (nullptr != memchr(&_json[tok.start], '.', tok.len)) {
tok.type = JSMN_FLOAT;
} else if (c0 == '-') {
tok.type = JSMN_INT;
} else {
tok.type = JSMN_UINT;
}
break;
default:
tok.type = JSMN_PRIMITIVE;
break;
}
} else {
tok.type = JSMN_PRIMITIVE;
}
}
}
}
JsonParserToken JsonParserObject::operator[](const char * needle) const {
// key can be in PROGMEM
if ((!this->isValid()) || (nullptr == needle) || (0 == pgm_read_byte(needle))) {
return JsonParserToken(&token_bad);
}
// if needle == "?" then we return the first valid key
bool wildcard = (strcmp_P("?", needle) == 0);
for (const auto key : *this) {
if (wildcard) { return key.getValue(); }
if (0 == strcasecmp_P(key.getStr(), needle)) { return key.getValue(); }
}
// if not found
return JsonParserToken(&token_bad);
}
JsonParserToken JsonParserObject::operator[](const String & needle) const {
return (*this)[needle.c_str()];
}
JsonParserToken JsonParserObject::findStartsWith(const char * needle) const {
// key can be in PROGMEM
if ((!this->isValid()) || (nullptr == needle) || (0 == pgm_read_byte(needle))) {
return JsonParserToken(&token_bad);
}
String needle_s((const __FlashStringHelper *)needle);
needle_s.toLowerCase();
for (const auto key : *this) {
String key_s(key.getStr());
key_s.toLowerCase();
if (key_s.startsWith(needle_s)) {
return key.getValue();
}
}
// if not found
return JsonParserToken(&token_bad);
}
const char * JsonParserObject::findConstCharNull(const char * needle) const {
const char * r = (*this)[needle].getStr();
if (*r == 0) { r = nullptr; } // if empty string
return r;
}
// JsonParserToken JsonParser::find(JsonParserObject obj, const char *needle, bool case_sensitive) const {
// // key can be in PROGMEM
// if ((!obj.isValid()) || (nullptr == needle) || (0 == pgm_read_byte(needle))) {
// return JsonParserToken(&token_bad);
// }
// // if needle == "?" then we return the first valid key
// bool wildcard = (strcmp_P("?", needle) == 0);
// for (const auto key : obj) {
// if (wildcard) { return key.getValue(); }
// if (case_sensitive) {
// if (0 == strcmp_P(this->getStr(key), needle)) { return key.getValue(); }
// } else {
// if (0 == strcasecmp_P(this->getStr(key), needle)) { return key.getValue(); }
// }
// }
// // if not found
// return JsonParserToken(&token_bad);
// }
void JsonParser::free(void) {
if (nullptr != _tokens) {
delete[] _tokens; // TODO
_tokens = nullptr;
}
}
void JsonParser::allocate(void) {
this->free();
if (_size != 0) {
_tokens = new jsmntok_t[_size];
}
}

View File

@ -1,269 +0,0 @@
/*
JsonParser.h - lightweight JSON parser
Copyright (C) 2021 Stephan Hadinger
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 __JSON_PARSER__
#define __JSON_PARSER__
#include "jsmn.h"
#include <string.h>
#include <stdlib.h>
#include <Arduino.h>
// #define strcmp_P(x, y) strcmp(x,y)
// #define strcasecmp_P(x,y) strcasecmp(x,y)
// #define pgm_read_byte(x) (*(uint8_t*)(x))
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#endif
/*********************************************************************************************\
* Utilities
\*********************************************************************************************/
// The code uses a zero-error approach. Functions never return an error code nor an exception.
// In case an operation fails, it returns an "Invalid Token".
// To know if a token is valid, use the `isValid()` method or just use it in an if statement.
//
// Internally, the bad token is a pointer to a constant token of type JSMN_INVALID
// fall-back token object when parsing failed
const extern jsmntok_t token_bad;
// To reduce code size, the current buffer is stored in a global variable.
// This prevents all calls to add this parameter on the stack and reduces code size.
// The caveat is that code is not re-entrant.
// If you ever intermix two or more JSON parsers, use `parser->setCurrent()` before further calls
//
// the current json buffer being used, for convenience
// Warning: this makes code non-reentrant.
extern const char * k_current_json_buffer;
/*********************************************************************************************\
* Read-only JSON token object, fits in 32 bits
\*********************************************************************************************/
// forward class declarations
class JsonParserObject;
class JsonParserArray;
class JsonParserToken {
public:
// constructor
// If parameter is null, we use the Invalid Token instead.
JsonParserToken(const jsmntok_t * token) : t(token) {
if (nullptr == t) { t = &token_bad; }
}
JsonParserToken() : t(&token_bad) { }
// no explicit destructor (not needed)
inline bool isValid(void) const { return t->type != JSMN_INVALID; }
inline size_t size(void) const { return t->size; }
inline bool isSingleToken(void) const { return (t->type >= JSMN_STRING); }
inline bool isKey(void) const { return (t->type == JSMN_KEY); }
inline bool isStr(void) const { return (t->type == JSMN_STRING); }
inline bool isNull(void) const { return (t->type == JSMN_NULL); }
inline bool isBool(void) const { return (t->type == JSMN_BOOL_TRUE) || (t->type == JSMN_BOOL_FALSE); }
inline bool isFloat(void) const { return (t->type == JSMN_FLOAT); }
inline bool isInt(void) const { return (t->type == JSMN_INT); }
inline bool isUint(void) const { return (t->type == JSMN_UINT); }
inline bool isNum(void) const { return (t->type >= JSMN_FLOAT) && (t->type <= JSMN_UINT); }
inline bool isObject(void) const { return (t->type == JSMN_OBJECT); }
inline bool isArray(void) const { return (t->type == JSMN_ARRAY); }
// move to token immediately after in the buffer
void nextOne(void) { if (t->type != JSMN_INVALID) { t++; } }
// conversion operators
// Warning - bool does not test for Boolean value but for validity, i.e. equivalent to token.valid()
inline explicit operator bool() const { return t->type != JSMN_INVALID; };
// all the following conversion will try to give a meaninful value
// if the content is not of the right type or the token is invalid, returns the 'default'
bool getBool(void) const; // true if 'true' or non-zero int (default false)
int32_t getInt(void) const; // convert to int (default 0)
uint32_t getUInt(void) const; // convert to unsigned int (default 0)
uint64_t getULong(void) const; // convert to unsigned 64 bits (default 0)
float getFloat(void) const; // convert to float (default 0), does not support exponent
const char * getStr(void) const; // convert to string (default "")
// same as above, but you can choose the default value
bool getBool(bool val) const;
int32_t getInt(int32_t val) const;
uint32_t getUInt(uint32_t val) const;
uint64_t getULong(uint64_t val) const;
float getFloat(float val) const;
const char * getStr(const char * val) const;
// convert to JsonParserObject or JsonParserArray, or Invalid Token if not allowed
JsonParserObject getObject(void) const;
JsonParserArray getArray(void) const;
// general parser from string to int/hex/float
static double json_strtof(const char* s);
public:
// the following should be 'protected' but then it can't be accessed by iterators
const jsmntok_t * t;
// skip the next Token as a whole (i.e. skip an entire array)
void skipToken(void);
protected:
// skip the next token knowing it's an array
void skipArray(void);
// skip the next token knowing it's an object
void skipObject(void);
};
/*********************************************************************************************\
* Subclass for Key
\*********************************************************************************************/
class JsonParserKey : public JsonParserToken {
public:
JsonParserKey(const jsmntok_t * token);
explicit JsonParserKey(const JsonParserToken token);
// get the value token associated to the key
JsonParserToken getValue(void) const;
};
/*********************************************************************************************\
* Subclass for Object
\*********************************************************************************************/
class JsonParserObject : public JsonParserToken {
public:
JsonParserObject(const jsmntok_t * token);
JsonParserObject(const JsonParserToken token);
JsonParserObject() : JsonParserToken() { }
// find key with name, case-insensitive, '?' matches any key. Returns Invalid Token if not found
JsonParserToken operator[](const char * needle) const;
JsonParserToken operator[](const String & needle) const;
// find a key starting with `needle`, case insensitive
JsonParserToken findStartsWith(const char * needle) const;
// find a key, case-insensitive, return nullptr if not found (instead of "")
const char * findConstCharNull(const char * needle) const;
// all-in-one methods: search for key (case insensitive), convert value and set default
int32_t getInt(const char *, int32_t) const;
uint32_t getUInt(const char *, uint32_t) const;
uint64_t getULong(const char *, uint64_t) const;
float getFloat(const char *, float) const;
const char * getStr(const char *, const char *) const;
const char * getStr(const char *) const;
// get first element (key)
JsonParserKey getFirstElement(void) const;
//
// const iterator
//
class const_iterator {
public:
const_iterator(const JsonParserObject t);
const_iterator operator++();
bool operator!=(const_iterator & other) const { return tok.t != other.tok.t; }
const JsonParserKey operator*() const { return JsonParserKey(tok); }
private:
JsonParserToken tok;
size_t remaining;
};
const_iterator begin() const { return const_iterator(*this); } // start with 'head'
const_iterator end() const { return const_iterator(JsonParserObject(&token_bad)); } // end with null pointer
};
/*********************************************************************************************\
* Subclass for Array
\*********************************************************************************************/
class JsonParserArray : public JsonParserToken {
public:
JsonParserArray(const jsmntok_t * token);
JsonParserArray(const JsonParserToken token);
JsonParserArray() : JsonParserToken() { }
// get the element if index `i` from 0 to `size() - 1`
JsonParserToken operator[](int32_t i) const;
//
// const iterator
//
class const_iterator {
public:
const_iterator(const JsonParserArray t);
const_iterator operator++();
bool operator!=(const_iterator & other) const { return tok.t != other.tok.t; }
const JsonParserToken operator*() const { return tok; }
private:
JsonParserToken tok;
size_t remaining;
};
const_iterator begin() const { return const_iterator(*this); } // start with 'head'
const_iterator end() const { return const_iterator(JsonParserArray(&token_bad)); } // end with null pointer
};
/*********************************************************************************************\
* JSON Parser
\*********************************************************************************************/
class JsonParser {
public:
// constructor, parse the json buffer
// Warning: the buffer is modified in the process (in-place parsing)
// Input: `json_in` can be nullptr, but CANNOT be in PROGMEM (remember we need to change characters in-place)
JsonParser(char * json_in);
// destructor
~JsonParser();
// set the current buffer for attribute access (i.e. set the global)
void setCurrent(void) { k_current_json_buffer = _json; }
// test if the parsing was successful
inline explicit operator bool() const { return _token_len > 0; }
const JsonParserToken getRoot(void) { return JsonParserToken(&_tokens[0]); }
// const JsonParserObject getRootObject(void) { return JsonParserObject(&_tokens[0]); }
const JsonParserObject getRootObject(void) const;
// pointer arithmetic
// ptrdiff_t index(JsonParserToken token) const;
protected:
uint16_t _size; // size of tokens buffer
int16_t _token_len; // how many tokens have been parsed
jsmntok_t * _tokens; // pointer to token buffer
jsmn_parser _parser; // jmsn_parser structure
char * _json; // json buffer
// disallocate token buffer
void free(void);
// allocate token buffer of size _size
void allocate(void);
// access tokens by index
const JsonParserToken operator[](int32_t i) const;
// parse
void parse(char * json_in);
// post-process parsing: insert NULL chars to split strings, compute a more precise token type
void postProcess(size_t json_len);
};
#endif // __JSON_PARSER__

View File

@ -1,458 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2010 Serge Zaitsev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "jsmn.h"
#define JSMN_STRICT // force strict mode
const uint32_t JSMN_START_MAX = (1U << JSMN_START_B) - 1;
const uint32_t JSMN_LEN_MAX = (1U << JSMN_LEN_B) - 1;
/**
* Allocates a fresh unused token from the token pool.
*/
static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, jsmntok_t *tokens,
const size_t num_tokens) {
jsmntok_t *tok;
if (parser->toknext >= num_tokens) {
return NULL;
}
tok = &tokens[parser->toknext++];
tok->start = JSMN_START_MAX;
tok->len = JSMN_LEN_MAX;
tok->size = 0;
return tok;
}
/**
* Fills token type and boundaries.
*/
static void jsmn_fill_token(jsmntok_t *token, const jsmntype_t type,
const int start, const int len) {
token->type = type;
token->start = start;
token->len = len;
token->size = 0;
}
/**
* Fills next available token with JSON primitive.
*/
static int jsmn_parse_primitive(jsmn_parser *parser, const char *js,
const size_t len, jsmntok_t *tokens,
const size_t num_tokens) {
jsmntok_t *token;
int start;
start = parser->pos;
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
switch (js[parser->pos]) {
#ifndef JSMN_STRICT
/* In strict mode primitive must be followed by "," or "}" or "]" */
case ':':
#endif
case '\t':
case '\r':
case '\n':
case ' ':
case ',':
case ']':
case '}':
goto found;
default:
/* to quiet a warning from gcc*/
break;
}
if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
parser->pos = start;
return JSMN_ERROR_INVAL;
}
}
#ifdef JSMN_STRICT
/* In strict mode primitive must be followed by a comma/object/array */
parser->pos = start;
return JSMN_ERROR_PART;
#endif
found:
if (tokens == NULL) {
parser->pos--;
return 0;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL) {
parser->pos = start;
return JSMN_ERROR_NOMEM;
}
jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos - start);
parser->pos--;
return 0;
}
/**
* Fills next token with JSON string.
*/
static int jsmn_parse_string(jsmn_parser *parser, const char *js,
const size_t len, jsmntok_t *tokens,
const size_t num_tokens) {
jsmntok_t *token;
int start = parser->pos;
parser->pos++;
/* Skip starting quote */
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
char c = js[parser->pos];
/* Quote: end of string */
if (c == '\"') {
if (tokens == NULL) {
return 0;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL) {
parser->pos = start;
return JSMN_ERROR_NOMEM;
}
jsmn_fill_token(token, JSMN_STRING, start + 1, parser->pos - start - 1);
return 0;
}
/* Backslash: Quoted symbol expected */
if (c == '\\' && parser->pos + 1 < len) {
int i;
parser->pos++;
switch (js[parser->pos]) {
/* Allowed escaped symbols */
case '\"':
case '/':
case '\\':
case 'b':
case 'f':
case 'r':
case 'n':
case 't':
break;
/* Allows escaped symbol \uXXXX */
case 'u':
parser->pos++;
for (i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0';
i++) {
/* If it isn't a hex character we have an error */
if (!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
(js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
(js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
parser->pos = start;
return JSMN_ERROR_INVAL;
}
parser->pos++;
}
parser->pos--;
break;
/* Unexpected symbol */
default:
parser->pos = start;
return JSMN_ERROR_INVAL;
}
}
}
parser->pos = start;
return JSMN_ERROR_PART;
}
/**
* Parse JSON string and fill tokens.
*/
JSMN_API int jsmn_parse(jsmn_parser *parser, const char *js, const size_t len,
jsmntok_t *tokens, const unsigned int num_tokens) {
int r;
int i;
jsmntok_t *token;
int count = parser->toknext;
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
char c;
jsmntype_t type;
c = js[parser->pos];
switch (c) {
case '{':
case '[':
count++;
if (tokens == NULL) {
break;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL) {
return JSMN_ERROR_NOMEM;
}
if (parser->toksuper != -1) {
jsmntok_t *t = &tokens[parser->toksuper];
#ifdef JSMN_STRICT
/* In strict mode an object or array can't become a key */
if (t->type == JSMN_OBJECT) {
return JSMN_ERROR_INVAL;
}
#endif
t->size++;
}
token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
token->start = parser->pos;
parser->toksuper = parser->toknext - 1;
break;
case '}':
case ']':
if (tokens == NULL) {
break;
}
type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
for (i = parser->toknext - 1; i >= 0; i--) {
token = &tokens[i];
if ((token->start != JSMN_START_MAX) && (token->len == JSMN_LEN_MAX)) {
if (token->type != type) {
return JSMN_ERROR_INVAL;
}
parser->toksuper = -1;
token->len = parser->pos + 1 - token->start;
break;
}
}
/* Error if unmatched closing bracket */
if (i == -1) {
return JSMN_ERROR_INVAL;
}
for (; i >= 0; i--) {
token = &tokens[i];
if ((token->start != JSMN_START_MAX) && (token->len == JSMN_LEN_MAX)) {
parser->toksuper = i;
break;
}
}
break;
case '\"':
r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
if (r < 0) {
return r;
}
count++;
if (parser->toksuper != -1 && tokens != NULL) {
tokens[parser->toksuper].size++;
}
break;
case '\t':
case '\r':
case '\n':
case ' ':
break;
case ':':
parser->toksuper = parser->toknext - 1;
break;
case ',':
if (tokens != NULL && parser->toksuper != -1 &&
tokens[parser->toksuper].type != JSMN_ARRAY &&
tokens[parser->toksuper].type != JSMN_OBJECT) {
for (i = parser->toknext - 1; i >= 0; i--) {
if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) {
if ((tokens[i].start != JSMN_START_MAX) && (tokens[i].len == JSMN_LEN_MAX)) {
parser->toksuper = i;
break;
}
}
}
}
break;
#ifdef JSMN_STRICT
/* In strict mode primitives are: numbers and booleans */
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 't':
case 'f':
case 'n':
// Add uppercase variants
case 'T':
case 'F':
case 'N':
/* And they must not be keys of the object */
if (tokens != NULL && parser->toksuper != -1) {
const jsmntok_t *t = &tokens[parser->toksuper];
if (t->type == JSMN_OBJECT ||
(t->type == JSMN_STRING && t->size != 0)) {
return JSMN_ERROR_INVAL;
}
}
#else
/* In non-strict mode every unquoted value is a primitive */
default:
#endif
r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
if (r < 0) {
return r;
}
count++;
if (parser->toksuper != -1 && tokens != NULL) {
tokens[parser->toksuper].size++;
}
break;
#ifdef JSMN_STRICT
/* Unexpected char in strict mode */
default:
return JSMN_ERROR_INVAL;
#endif
}
}
if (tokens != NULL) {
for (i = parser->toknext - 1; i >= 0; i--) {
/* Unmatched opened object or array */
if ((tokens[i].start != JSMN_START_MAX) && (tokens[i].len == JSMN_LEN_MAX)) {
return JSMN_ERROR_PART;
}
}
}
return count;
}
/**
* Creates a new parser based over a given buffer with an array of tokens
* available.
*/
JSMN_API void jsmn_init(jsmn_parser *parser) {
parser->pos = 0;
parser->toknext = 0;
parser->toksuper = -1;
}
//
// Json in-place string unescape
// inpired from https://github.com/mjansson/json/blob/master/json.h
//
//! Define a bitmask with the given number of bits set to 1
#define JSON_BITMASK(numbits) ((1U << (numbits)) - 1)
static uint32_t json_get_num_bytes_as_utf8(uint32_t val) {
if (val >= 0x04000000) return 6;
else if (val >= 0x00200000) return 5;
else if (val >= 0x00010000) return 4;
else if (val >= 0x00000800) return 3;
else if (val >= 0x00000080) return 2;
return 1;
}
static uint32_t json_encode_utf8(char* str, uint32_t val) {
if (val < 0x80) {
*str = (char)val;
return 1;
}
//Get number of _extra_ bytes
uint32_t num = json_get_num_bytes_as_utf8(val) - 1;
*str++ = (char)((0x80U | (JSON_BITMASK(num) << (7U - num))) |
((val >> (6U * num)) & JSON_BITMASK(6U - num)));
for (uint32_t j = 1; j <= num; ++j)
*str++ = (char)(0x80U | ((val >> (6U * (num - j))) & 0x3F));
return num + 1;
}
void json_unescape(char* string) {
size_t outlength = 0;
uint32_t hexval, numbytes;
char c;
for (uint32_t i = 0; (c = string[i]) != 0; i++) {
if ('\\' == c) {
c = string[++i];
switch (c) {
case 0:
string[outlength++] = 0;
return; // end of stream
case '\"':
case '/':
case '\\':
string[outlength++] = c;
break;
case 'b':
string[outlength++] = '\b';
break;
case 'f':
string[outlength++] = '\f';
break;
case 'r':
string[outlength++] = '\r';
break;
case 'n':
string[outlength++] = '\n';
break;
case 't':
string[outlength++] = '\t';
break;
case 'u':
{
uint32_t hexval = 0;
for (uint32_t j = 0; j < 4; ++j) {
char val = string[++i];
if (0 == val) {
string[outlength++] = 0;
return; // we reached end of string
}
uint32_t uival = 0;
if ((val >= 'a') && (val <= 'f'))
uival = 10 + (val - 'a');
else if ((val >= 'A') && (val <= 'F'))
uival = 10 + (val - 'A');
else if ((val >= '0') && (val <= '9'))
uival = val - '0';
hexval |= uival << (3 - j);
}
numbytes = json_get_num_bytes_as_utf8(hexval);
outlength += json_encode_utf8(string + outlength, hexval);
}
break;
default:
break;
}
}
else {
string[outlength++] = c;
}
}
string[outlength++] = 0;
}

View File

@ -1,118 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2010 Serge Zaitsev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef JSMN_H
#define JSMN_H
#include <stddef.h>
#include <stdint.h>
// #ifdef JSMN_STATIC
// #define JSMN_API static
// #else
#define JSMN_API extern
// #endif
/**
* JSON type identifier. Basic types are:
* o Object
* o Array
* o String
* o Other primitive: number, boolean (true/false) or null
*/
typedef enum {
// end market
JSMN_INVALID = 0, // type == 0 is invalid
JSMN_OBJECT = 1,
JSMN_ARRAY = 2,
JSMN_STRING = 3,
JSMN_PRIMITIVE = 4,
// new types created during post-processing
JSMN_KEY = 5, // JSMN_STRING with size 1
JSMN_NULL = 6, // JSMN_PRIMITIVE starting with 'n'
JSMN_BOOL_FALSE = 7, // JSMN_PRIMITIVE starting with 'f' or 'F'
JSMN_BOOL_TRUE = 8, // JSMN_PRIMITIVE starting with 't' or 'T'
JSMN_FLOAT = 9, // JSMN_PRIMITIVE starting with '.', '-', '0-9' and containing a '.'
JSMN_INT = 10, // JSMN_PRIMITIVE starting with '-', '0-9' and not containing a '.'
JSMN_UINT = 11, // JSMN_PRIMITIVE starting with '0-9' and not containing a '.'
} jsmntype_t;
enum jsmnerr {
/* Not enough tokens were provided */
JSMN_ERROR_NOMEM = -1,
/* Invalid character inside JSON string */
JSMN_ERROR_INVAL = -2,
/* The string is not a full JSON packet, more bytes expected */
JSMN_ERROR_PART = -3
};
/**
* JSON token description.
* type type (object, array, string etc.)
* start start position in JSON data string
* end end position in JSON data string
*/
// size of bitfield, sum is 32
#define JSMN_TYPE_B 4
#define JSMN_SIZE_B 6 // max 63 items per level (ex: max 63 keys per object)
#define JSMN_START_B 11 // max 2KB input buffer
#define JSMN_LEN_B 11 // max 2KB per item
typedef struct jsmntok {
jsmntype_t type : JSMN_TYPE_B;
unsigned int size : JSMN_SIZE_B;
unsigned int start : JSMN_START_B;
unsigned int len : JSMN_LEN_B;
} jsmntok_t;
/**
* JSON parser. Contains an array of token blocks available. Also stores
* the string being parsed now and current position in that string.
*/
typedef struct jsmn_parser {
unsigned int pos; /* offset in the JSON string */
unsigned int toknext; /* next token to allocate */
int toksuper; /* superior token node, e.g. parent object or array */
} jsmn_parser;
/**
* Create JSON parser over an array of tokens
*/
JSMN_API void jsmn_init(jsmn_parser *parser);
/**
* Run JSON parser. It parses a JSON data string into and array of tokens, each
* describing
* a single JSON object.
*/
JSMN_API int jsmn_parse(jsmn_parser *parser, const char *js, const size_t len,
jsmntok_t *tokens, const unsigned int num_tokens);
/**
*
* In-place json unescape
*
*/
void json_unescape(char* string);
#endif /* JSMN_H */

View File

@ -1,55 +0,0 @@
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "../src/JsonParser.h"
static char test_simple[] = "{\"Device\":\"0x9C33\",\"Illuminance\":42,\"Occupancy\":1,\"Endpoint\":1,\"LinkQuality\":59}";
static char test_moderate[] = "{\"ZbReceived\":{\"Prez\":{\"Device\":\"0x9C33\",\"Illuminance\":42,\"Occupancy\":1,\"Endpoint\":1,\"LinkQuality\":59}}}";
static char test_complex[] = "{\"ZbStatus3\":[{\"Device\":\"0x7869\",\"INT\":-3,\"Name\":\"Tilt\",\"IEEEAddr\":\"0x00158D00031310F4\",\"ModelId\":\"lumi.vibration.aq1\",\"Manufacturer\":\"LUMI\",\"Endpoints\":{\"0x01\":{\"ProfileId\":\"0x0104\",\"ClustersIn\":[\"0x0000\",\"0x0003\",\"0x0019\",\"0x0101\"],\"ClustersOut\":[\"0x0000\",\"0x0004\",\"0x0003\",\"0x0005\",\"0x0019\",\"0x0101\"]},\"0x02\":{\"ProfileId\":\"0x0000\\ta\",\"ClustersIn\":[2],\"ClustersOut\":[-3,0.4,5.8]}}}]}";
int main(int argc, char* argv[]) {
printf("Starting... sizeof = %lu / %lu\n", sizeof(jsmntok_t), sizeof(JsonParserToken));
// char * json_str = test_complex;
char * json_str = test_simple;
// JsonParser parser(64); // size for 64 tokens
int r = parser.parse(json_str);
printf("r = %d\n", r);
for (uint32_t i=0; i<r; i++) {
JsonParserToken token = parser[i];
uint32_t start = token.t->start;
uint32_t len = token.t->len;
printf("Tok[%2d]= type=%s, start=%d, len=%d, size=%d, str ='%s'\n", i, JSMNTypeName(token.t->type), start, len, token.t->size, (token.t->type >= JSMN_STRING || 1) ? &json_str[start] : "");
}
printf("==================\n");
JsonParserObject root = parser.getRootObject();
for (const auto key : root) {
// printf("Index = %ld\n", parser.index(key));
JsonParserToken value = key.getValue();
printf("Key = %s, Val type = %s\n", parser.getStr(key), JSMNTypeName(value.t->type));
if (value.isArray()) {
for (const auto arr_val : JsonParserArray(value)) {
printf("Array = %s, type = %s\n", parser.getStr(arr_val), JSMNTypeName(arr_val.t->type));
}
} else {
printf("Value = %s\n", parser.getStr(value));
}
}
// root.nextOne();
// printf("Index = %ld\n", parser.index(root));
// root.skipObject();
// printf("Index = %ld\n", parser.index(root));
JsonParserToken oc = parser.GetCaseInsensitive(root, "occupancy");
printf("Looking for 'Occupancy': %s, %d\n", parser.getStr(oc), parser.getInt(oc));
JsonParserToken oc2 = parser.GetCaseInsensitive(root, "occupanc");
printf("Looking for 'Occupanc': %s, %d\n", parser.getStr(oc2), parser.getInt(oc2));
}

View File

@ -1,5 +0,0 @@
tests/bin
.pioenvs
.piolibdeps
.clang_complete
.gcc-flags.json

View File

@ -1,7 +0,0 @@
sudo: false
language: cpp
compiler:
- g++
script: cd tests && make && make test
os:
- linux

View File

@ -1,85 +0,0 @@
2.8
* Add setBufferSize() to override MQTT_MAX_PACKET_SIZE
* Add setKeepAlive() to override MQTT_KEEPALIVE
* Add setSocketTimeout() to overide MQTT_SOCKET_TIMEOUT
* Added check to prevent subscribe/unsubscribe to empty topics
* Declare wifi mode prior to connect in ESP example
* Use `strnlen` to avoid overruns
* Support pre-connected Client objects
2.7
* Fix remaining-length handling to prevent buffer overrun
* Add large-payload API - beginPublish/write/publish/endPublish
* Add yield call to improve reliability on ESP
* Add Clean Session flag to connect options
* Add ESP32 support for functional callback signature
* Various other fixes
2.4
* Add MQTT_SOCKET_TIMEOUT to prevent it blocking indefinitely
whilst waiting for inbound data
* Fixed return code when publishing >256 bytes
2.3
* Add publish(topic,payload,retained) function
2.2
* Change code layout to match Arduino Library reqs
2.1
* Add MAX_TRANSFER_SIZE def to chunk messages if needed
* Reject topic/payloads that exceed MQTT_MAX_PACKET_SIZE
2.0
* Add (and default to) MQTT 3.1.1 support
* Fix PROGMEM handling for Intel Galileo/ESP8266
* Add overloaded constructors for convenience
* Add chainable setters for server/callback/client/stream
* Add state function to return connack return code
1.9
* Do not split MQTT packets over multiple calls to _client->write()
* API change: All constructors now require an instance of Client
to be passed in.
* Fixed example to match 1.8 api changes - dpslwk
* Added username/password support - WilHall
* Added publish_P - publishes messages from PROGMEM - jobytaffey
1.8
* KeepAlive interval is configurable in PubSubClient.h
* Maximum packet size is configurable in PubSubClient.h
* API change: Return boolean rather than int from various functions
* API change: Length parameter in message callback changed
from int to unsigned int
* Various internal tidy-ups around types
1.7
* Improved keepalive handling
* Updated to the Arduino-1.0 API
1.6
* Added the ability to publish a retained message
1.5
* Added default constructor
* Fixed compile error when used with arduino-0021 or later
1.4
* Fixed connection lost handling
1.3
* Fixed packet reading bug in PubSubClient.readPacket
1.2
* Fixed compile error when used with arduino-0016 or later
1.1
* Reduced size of library
* Added support for Will messages
* Clarified licensing - see LICENSE.txt
1.0
* Only Quality of Service (QOS) 0 messaging is supported
* The maximum message size, including header, is 128 bytes
* The keepalive interval is set to 30 seconds
* No support for Will messages

View File

@ -1,20 +0,0 @@
Copyright (c) 2008-2020 Nicholas O'Leary
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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