Compare commits
37
Commits
fbebe9f4f9
..
cpp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24dd5ffb15 | ||
|
|
94e300f6ad | ||
|
|
59eb37cad5 | ||
|
|
af82cb4c4a | ||
|
|
995b05f538 | ||
|
|
762ec338bc | ||
|
|
4cd3bc7973 | ||
|
|
47f4eba0d6 | ||
|
|
d32f3d69cf | ||
|
|
4b623bb156 | ||
|
|
9a04d28ecf | ||
|
|
89f996096c | ||
|
|
df43820acd | ||
|
|
97df6e3cbe | ||
|
|
08d7277204 | ||
|
|
495da4e366 | ||
|
|
940d1d0a77 | ||
|
|
20d1af7177 | ||
|
|
3286c4002d | ||
|
|
68eb547ec4 | ||
|
|
8403df531d | ||
|
|
088fe161a8 | ||
|
|
c9895df512 | ||
|
|
39a84696c3 | ||
|
|
c7560b2e87 | ||
|
|
ea21563900 | ||
|
|
a97f6c7c2c | ||
|
|
1fdb2c9441 | ||
|
|
3e718f7432 | ||
|
|
85490a3bd0 | ||
|
|
94266d5a7c | ||
|
|
55a97ac51c | ||
|
|
794f1a2841 | ||
|
|
8f8bc894a9 | ||
|
|
2a768376d0 | ||
|
|
170a0e05ab | ||
|
|
4879fcfe90 |
No files matched your search
@@ -0,0 +1,8 @@
|
|||||||
|
# The following lines of boilerplate have to be in your project's CMakeLists
|
||||||
|
# in this exact order for cmake to work correctly
|
||||||
|
cmake_minimum_required(VERSION 3.22)
|
||||||
|
|
||||||
|
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||||
|
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
|
||||||
|
idf_build_set_property(MINIMAL_BUILD ON)
|
||||||
|
project(led_driver)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# Top-level Makefile for the led_strip ESP-IDF project.
|
||||||
|
# Thin wrapper around idf.py. Runs on Linux, macOS (bash) and Windows (GNU make with cmd.exe or sh).
|
||||||
|
#
|
||||||
|
# Override any variable on the command line, for example:
|
||||||
|
# make flash PORT=/dev/ttyUSB0 # Linux
|
||||||
|
# make flash PORT=/dev/cu.usbmodem101 # macOS
|
||||||
|
# make flash PORT=COM4 # Windows
|
||||||
|
|
||||||
|
ifeq ($(OS),Windows_NT)
|
||||||
|
HOST_OS := windows
|
||||||
|
HOME_DIR := $(USERPROFILE)
|
||||||
|
DEFAULT_PORT := COM3
|
||||||
|
else
|
||||||
|
HOST_OS := $(shell uname -s)
|
||||||
|
HOME_DIR := $(HOME)
|
||||||
|
ifeq ($(HOST_OS),Darwin)
|
||||||
|
DEFAULT_PORT := /dev/cu.usbmodem101
|
||||||
|
else
|
||||||
|
DEFAULT_PORT := /dev/ttyACM0
|
||||||
|
endif
|
||||||
|
endif
|
||||||
|
|
||||||
|
IDF_PATH ?= $(HOME_DIR)/.espressif/v6.1/esp-idf
|
||||||
|
IDF_PYTHON_ENV_PATH ?= $(HOME_DIR)/.espressif/python_env/idf6.1_py3.12_env
|
||||||
|
PORT ?= $(DEFAULT_PORT)
|
||||||
|
|
||||||
|
export IDF_PATH
|
||||||
|
export IDF_PYTHON_ENV_PATH
|
||||||
|
|
||||||
|
# Run idf.py in a shell that has sourced ESP-IDF's environment script (sets PATH and toolchains).
|
||||||
|
ifeq ($(HOST_OS),windows)
|
||||||
|
define idf
|
||||||
|
cmd /c "$(subst /,\,$(IDF_PATH))\export.bat && idf.py $(1)"
|
||||||
|
endef
|
||||||
|
else
|
||||||
|
define idf
|
||||||
|
bash -c '. "$(IDF_PATH)/export.sh" >/dev/null 2>&1 && idf.py $(1)'
|
||||||
|
endef
|
||||||
|
endif
|
||||||
|
|
||||||
|
.PHONY: all build flash monitor flash-monitor menuconfig clean fullclean help
|
||||||
|
|
||||||
|
all: build
|
||||||
|
|
||||||
|
build:
|
||||||
|
$(call idf,build)
|
||||||
|
|
||||||
|
flash: build
|
||||||
|
$(call idf,-p $(PORT) flash)
|
||||||
|
|
||||||
|
monitor:
|
||||||
|
$(call idf,-p $(PORT) monitor)
|
||||||
|
|
||||||
|
flash-monitor: build
|
||||||
|
$(call idf,-p $(PORT) flash monitor)
|
||||||
|
|
||||||
|
menuconfig:
|
||||||
|
$(call idf,menuconfig)
|
||||||
|
|
||||||
|
clean:
|
||||||
|
$(call idf,clean)
|
||||||
|
|
||||||
|
fullclean:
|
||||||
|
$(call idf,fullclean)
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo Targets:
|
||||||
|
@echo build Build the firmware
|
||||||
|
@echo flash Build, then flash to the board on PORT
|
||||||
|
@echo monitor Open the serial monitor on PORT
|
||||||
|
@echo flash-monitor Build, flash, then open the serial monitor
|
||||||
|
@echo menuconfig Open the project configuration menu
|
||||||
|
@echo clean Remove build outputs
|
||||||
|
@echo fullclean Delete the build directory entirely
|
||||||
|
@echo help Show this help
|
||||||
|
|
||||||
|
# Over-the-air update over Wi-Fi (the access point or the home network): make ota HOST=<ip or name>
|
||||||
|
ota: HOST ?= led.local
|
||||||
|
ota: build
|
||||||
|
python3 tools/ota.py $(HOST)
|
||||||
@@ -50,3 +50,78 @@ led-driver/
|
|||||||
## Further reading
|
## Further reading
|
||||||
|
|
||||||
- **`docs/API.md`** — JSON message fields as used in examples (`pattern`, `colors`, …). The Pi app may send **short keys** (`p`, `c`, …); behaviour matches once normalised on device.
|
- **`docs/API.md`** — JSON message fields as used in examples (`pattern`, `colors`, …). The Pi app may send **short keys** (`p`, `c`, …); behaviour matches once normalised on device.
|
||||||
|
|
||||||
|
## C++ app (ESP-IDF)
|
||||||
|
|
||||||
|
The `cpp` branch is an ESP-IDF app for the ESP32-C3 at the repo root (`CMakeLists.txt`, `main/`, `web/`). It drives a 119-LED WS2812 strip on GPIO 10 (set in `main/patterns.cpp`).
|
||||||
|
|
||||||
|
### Web UI, access point and Wi-Fi client
|
||||||
|
|
||||||
|
The firmware runs three things at once:
|
||||||
|
|
||||||
|
- **Access point** `led-XXXXXX` (the last three bytes of the MAC), open, no password. Join it and browse to `http://192.168.4.1/`.
|
||||||
|
- **Wi-Fi client**: set a network from the Settings tab (scan, pick, enter password). Credentials are saved to NVS, and the client reconnects with backoff after a drop.
|
||||||
|
- **mDNS**: once on a network, the device answers as `http://led.local/`.
|
||||||
|
|
||||||
|
Patterns: solid, rainbow, chase, breathe, blink, pulse, transition and circle. The web UI is embedded in the firmware from `web/`.
|
||||||
|
|
||||||
|
JSON API (port 80):
|
||||||
|
|
||||||
|
| Method | Path | Purpose |
|
||||||
|
|--------|------|---------|
|
||||||
|
| GET | `/api/status` | Current pattern and parameters, AP name, client state and IP |
|
||||||
|
| POST | `/api/pattern` | `{"mode","c1":[r,g,b],"c2":[r,g,b],"speed_ms","brightness"}` |
|
||||||
|
| GET | `/api/wifi` | Saved client SSID and connection state |
|
||||||
|
| POST | `/api/wifi` | `{"ssid","password"}`: save and connect |
|
||||||
|
| GET | `/api/wifi/scan` | Visible networks |
|
||||||
|
|
||||||
|
### USB configuration (led-tool)
|
||||||
|
|
||||||
|
The JSON API above is also served on the USB serial port (`/dev/ttyACM0`, `main/usb_cfg.cpp`), so a driver can be set up without Wi-Fi. One line per request and per reply; every other line is log output:
|
||||||
|
|
||||||
|
```
|
||||||
|
@api {"id":1,"method":"GET","path":"/api/status"}
|
||||||
|
@api {"id":1,"status":200,"body":"{...}"}
|
||||||
|
@api {"id":2,"method":"POST","path":"/api/hardware","body":{"num_leds":60}}
|
||||||
|
@reboot
|
||||||
|
```
|
||||||
|
|
||||||
|
Requests run on the web server's task, with the same checks as the web UI. `led-tool` uses this automatically:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python cli.py -s
|
||||||
|
python cli.py -l 60 -o rgb --pin 10 -b 128 -n bar1
|
||||||
|
```
|
||||||
|
|
||||||
|
Open the port with DTR high and RTS low (RTS high with DTR low resets the chip).
|
||||||
|
|
||||||
|
Build and flash for the ESP32-C3:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
. ~/.espressif/v6.1/esp-idf/export.sh
|
||||||
|
idf.py set-target esp32c3
|
||||||
|
idf.py build flash monitor
|
||||||
|
```
|
||||||
|
|
||||||
|
### ESP-NOW (led-controller)
|
||||||
|
|
||||||
|
The driver takes part in an ESP-NOW rig run by `led-controller` (the same 0x4C wire protocol as the
|
||||||
|
MicroPython drivers). It announces itself at boot, so the controller lists it with its name and LED count
|
||||||
|
(`transport: espnow`), and then takes:
|
||||||
|
|
||||||
|
- presets and selects, the brightness, device settings (`device_config`), the zones (group commands) and
|
||||||
|
the startup preset, from v2/v3 envelopes and v1 JSON;
|
||||||
|
- the controller's reliable messages: acknowledged, reassembled, duplicates dropped, state resynced by digest;
|
||||||
|
- pings, and the beat for beat-timed presets (`tb`), which take their quarter-beat length from the
|
||||||
|
controller's tempo.
|
||||||
|
|
||||||
|
Settings (`GET`/`POST /api/espnow`): `enabled`, and `channel` (1-13). ESP-NOW uses the radio's channel:
|
||||||
|
the access point's, or the router's when the client is joined. Put the controller's bridge on the same
|
||||||
|
channel. A client that is searching for a network that is not in range keeps the radio hopping channels,
|
||||||
|
which breaks ESP-NOW; the access point gives it a fixed channel.
|
||||||
|
|
||||||
|
Saving Wi-Fi credentials (`POST /api/wifi`, or the Settings tab) switches to Wi-Fi mode: ESP-NOW is turned
|
||||||
|
off and the driver restarts, then joins the saved network. Turn ESP-NOW back on with `POST /api/espnow` and
|
||||||
|
a restart.
|
||||||
|
|
||||||
|
Not supported yet: OTA over ESP-NOW, the reverse (`reversed`) setting, and the lossy-link test mode.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
PORT="${1:-/dev/ttyACM0}"
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
ls "$PORT" && led-cli -p "$PORT" --erase --src --patterns && led-cli -p "$PORT" --reset -f
|
||||||
|
sleep 0.5
|
||||||
|
done
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
dependencies:
|
||||||
|
espressif/cjson:
|
||||||
|
component_hash: e788323270d90738662d66fffa910bfe1fba019bba087f01557e70c40485b469
|
||||||
|
dependencies:
|
||||||
|
- name: idf
|
||||||
|
require: private
|
||||||
|
version: '>=5.0'
|
||||||
|
source:
|
||||||
|
registry_url: https://components.espressif.com/
|
||||||
|
type: service
|
||||||
|
version: 1.7.19~2
|
||||||
|
espressif/mdns:
|
||||||
|
component_hash: 2fa43caa78cc170842255bc7bf71f306bc815cae12e9496bfb12372423019ac7
|
||||||
|
dependencies:
|
||||||
|
- name: idf
|
||||||
|
require: private
|
||||||
|
version: '>=5.0'
|
||||||
|
source:
|
||||||
|
registry_url: https://components.espressif.com/
|
||||||
|
type: service
|
||||||
|
version: 1.15.1
|
||||||
|
idf:
|
||||||
|
source:
|
||||||
|
type: idf
|
||||||
|
version: 6.1.0
|
||||||
|
direct_dependencies:
|
||||||
|
- espressif/cjson
|
||||||
|
- espressif/mdns
|
||||||
|
manifest_hash: d0a7e36d6cc4abacaa550a978cbc8f50812589b67060a807571ef39c1e829dfd
|
||||||
|
target: esp32c3
|
||||||
|
version: 3.0.0
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
|
|
||||||
import shutil
|
|
||||||
import subprocess
|
|
||||||
import serial
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
|
|
||||||
def mpremote_base():
|
|
||||||
"""mpremote on PATH, or same interpreter as this script (e.g. pipenv venv)."""
|
|
||||||
exe = shutil.which("mpremote")
|
|
||||||
if exe:
|
|
||||||
return [exe]
|
|
||||||
return [sys.executable, "-m", "mpremote"]
|
|
||||||
|
|
||||||
|
|
||||||
print(sys.argv)
|
|
||||||
|
|
||||||
# Extract port (first arg if it's not a command)
|
|
||||||
commands = ["src", "lib", "ls", "reset", "follow", "db", "test"]
|
|
||||||
port = None
|
|
||||||
if len(sys.argv) > 1 and sys.argv[1] not in commands:
|
|
||||||
port = sys.argv[1]
|
|
||||||
|
|
||||||
|
|
||||||
for cmd in sys.argv[1:]:
|
|
||||||
print(cmd)
|
|
||||||
match cmd:
|
|
||||||
case "src":
|
|
||||||
if port:
|
|
||||||
subprocess.call(
|
|
||||||
[*mpremote_base(), "connect", port, "fs", "cp", "-r", ".", ":"],
|
|
||||||
cwd="src",
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
print("Error: Port required for 'src' command")
|
|
||||||
case "lib":
|
|
||||||
if port:
|
|
||||||
subprocess.call([*mpremote_base(), "connect", port, "fs", "cp", "-r", "lib", ":"])
|
|
||||||
else:
|
|
||||||
print("Error: Port required for 'lib' command")
|
|
||||||
case "ls":
|
|
||||||
if port:
|
|
||||||
subprocess.call([*mpremote_base(), "connect", port, "fs", "ls", ":"])
|
|
||||||
else:
|
|
||||||
print("Error: Port required for 'ls' command")
|
|
||||||
case "reset":
|
|
||||||
if port:
|
|
||||||
with serial.Serial(port, baudrate=115200) as ser:
|
|
||||||
ser.write(b'\x03\x03\x04')
|
|
||||||
else:
|
|
||||||
print("Error: Port required for 'reset' command")
|
|
||||||
case "follow":
|
|
||||||
if port:
|
|
||||||
with serial.Serial(port, baudrate=115200) as ser:
|
|
||||||
while True:
|
|
||||||
if ser.in_waiting > 0: # Check if there is data in the buffer
|
|
||||||
data = ser.readline().decode('utf-8').strip() # Read and decode the data
|
|
||||||
print(data)
|
|
||||||
else:
|
|
||||||
print("Error: Port required for 'follow' command")
|
|
||||||
case "db":
|
|
||||||
if port:
|
|
||||||
subprocess.call([*mpremote_base(), "connect", port, "fs", "cp", "-r", "db", ":"])
|
|
||||||
else:
|
|
||||||
print("Error: Port required for 'db' command")
|
|
||||||
case "test":
|
|
||||||
if port:
|
|
||||||
if "all" in sys.argv[1:]:
|
|
||||||
test_files = sorted(
|
|
||||||
str(path)
|
|
||||||
for path in Path("test").rglob("*.py")
|
|
||||||
if path.is_file()
|
|
||||||
)
|
|
||||||
failed = []
|
|
||||||
for test_file in test_files:
|
|
||||||
print(f"Running {test_file}")
|
|
||||||
code = subprocess.call(
|
|
||||||
[*mpremote_base(), "connect", port, "run", test_file]
|
|
||||||
)
|
|
||||||
if code != 0:
|
|
||||||
failed.append((test_file, code))
|
|
||||||
if failed:
|
|
||||||
print("Some tests failed:")
|
|
||||||
for test_file, code in failed:
|
|
||||||
print(f" {test_file} (exit {code})")
|
|
||||||
else:
|
|
||||||
subprocess.call(
|
|
||||||
[*mpremote_base(), "connect", port, "run", "test/all.py"]
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
print("Error: Port required for 'test' command")
|
|
||||||
@@ -97,6 +97,13 @@ Presets define LED patterns with their configuration. Each preset has a name and
|
|||||||
- **`n3`**: Tail movement rate (LEDs per second)
|
- **`n3`**: Tail movement rate (LEDs per second)
|
||||||
- **`n4`**: Minimum length
|
- **`n4`**: Minimum length
|
||||||
|
|
||||||
|
#### Gradient Wipe (`gradient_wipe`)
|
||||||
|
One-shot: lights LEDs from `n1` to `n2` (backwards if `n1 > n2`) with a gradient from the first to the second colour, then stops.
|
||||||
|
- **`n1`**: First LED
|
||||||
|
- **`n2`**: Last LED
|
||||||
|
- **`delay`**: Total time in milliseconds to sweep from `n1` to `n2`
|
||||||
|
- **`background`**: Colour for the rest of the strip
|
||||||
|
|
||||||
## Select Messages
|
## Select Messages
|
||||||
|
|
||||||
Select messages control which preset is active on which device. The format uses a list to support step synchronization.
|
Select messages control which preset is active on which device. The format uses a list to support step synchronization.
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
# Patterns and presets on the LED driver
|
||||||
|
|
||||||
|
This document describes **how patterns are wired**, how **presets** map to patterns, and what each **shipped pattern** expects. For the JSON wire format (`v`: `"1"`, `presets`, `select`, short keys `p` / `c` / `b`, etc.), see [API.md](API.md).
|
||||||
|
|
||||||
|
## End-to-end control
|
||||||
|
|
||||||
|
1. The controller sends a **v1 JSON** object (ESP-NOW, serial bridge, or one line per message over TCP WebSocket in Wi-Fi mode).
|
||||||
|
2. `controller_messages.process_data()` parses it and applies fields in a fixed order (see `src/controller_messages.py`):
|
||||||
|
- `device_config` — name, LED count, colour order, startup mode; may reload `presets.json` and re-select the previous preset.
|
||||||
|
- `b` — **global** output brightness (0–255), stored in settings and in `presets.b`.
|
||||||
|
- `presets` — merge definitions into the in-memory preset table (`Presets.edit()` per id).
|
||||||
|
- `clear_presets` — optional wipe of all presets.
|
||||||
|
- `select` — pick the active preset (and optional step) for **this** device (matched by `settings["name"]`).
|
||||||
|
- `default` — update saved default preset when `targets` includes this device.
|
||||||
|
- `manifest` — pattern OTA: fetch pattern `.py` files and `reload_patterns()`.
|
||||||
|
- `save` — persist presets and/or settings when combined with the relevant fields.
|
||||||
|
3. The main loop calls `presets.tick()` so the active pattern **generator** advances one frame per iteration.
|
||||||
|
|
||||||
|
## Presets
|
||||||
|
|
||||||
|
- **Class:** `src/preset.py` — `Preset` holds the pattern configuration.
|
||||||
|
- **Short keys** (what the driver uses internally after `apply_presets` normalisation):
|
||||||
|
|
||||||
|
| Key | Meaning | Default |
|
||||||
|
|-----|---------|--------|
|
||||||
|
| `p` | Pattern id (string), must match a registered pattern | `"off"` |
|
||||||
|
| `c` | Colours as RGB tuples (after colour-order conversion) | `[(255,255,255)]` |
|
||||||
|
| `d` | Delay (ms); meaning is pattern-specific | `100` |
|
||||||
|
| `b` | Preset brightness 0–255 (combined with global `presets.b`) | `127` |
|
||||||
|
| `a` | Auto: continuous animation; `false` = manual / beat-stepped where supported | `True` |
|
||||||
|
| `bg` | Background colour (hex string or RGB tuple on device) | `(0,0,0)` |
|
||||||
|
| `n1`–`n6` | Pattern-specific integers | `0` |
|
||||||
|
|
||||||
|
Long aliases from the controller (`pattern`, `colors`, `delay`, `brightness`, `auto`, `background`) are converted in `Preset.edit()`.
|
||||||
|
|
||||||
|
- **Persistence:** `presets.json` on flash; **`MAX_PRESETS` = 32** (exceptions for auto-created `"on"` / `"off"`).
|
||||||
|
- **Activation:** `Presets.select(preset_name, step=None)` loads the preset, looks up **`preset.p`** in the pattern registry, and sets `generator = patterns[preset.p](preset)`, then runs one `tick()` so the first frame appears.
|
||||||
|
|
||||||
|
## Brightness
|
||||||
|
|
||||||
|
- **Global:** `presets.b` from message `{"v":"1","b":…}` scales every output channel.
|
||||||
|
- **Per preset:** `preset.b`; combined in `Presets.apply_brightness(colour, preset.b)` as
|
||||||
|
`effective = round(preset_channel * presets.b / 255)` with preset level applied first conceptually (`apply_brightness` takes the preset’s `b` as the override for that colour).
|
||||||
|
|
||||||
|
## Pattern registry
|
||||||
|
|
||||||
|
Built in `Presets.reload_patterns()` (`src/presets.py`):
|
||||||
|
|
||||||
|
1. **Built-ins:** `"off"` and `"on"` — methods on the `Presets` instance (not separate files).
|
||||||
|
2. **Dynamic modules:** Every `patterns/*.py` on flash (except `__init__.py`), imported as `patterns.<basename>`. The loader takes the **first class** in the module that defines **`run`**, instantiates it with `Presets(self)` (the driver / NeoPixel wrapper), and registers:
|
||||||
|
|
||||||
|
```text
|
||||||
|
patterns[basename] = PatternClass(driver).run
|
||||||
|
```
|
||||||
|
|
||||||
|
So the **`p` field must equal the file basename without `.py`** (e.g. file `radiate.py` ⇒ pattern `"radiate"`).
|
||||||
|
|
||||||
|
### Adding or updating patterns on device
|
||||||
|
|
||||||
|
- **OTA:** v1 message with `"manifest"` (URL or inline JSON listing `files` with `name`, `url` or `code`) — see `apply_patterns_ota()` in `controller_messages.py`.
|
||||||
|
- **HTTP:** `POST /patterns/upload` on the device (`src/main.py`) with a safe `.py` filename; optional reload of the registry.
|
||||||
|
|
||||||
|
After new files land in `patterns/`, call `presets.reload_patterns()` (done automatically by OTA and upload when configured).
|
||||||
|
|
||||||
|
## Auto vs manual (`a`)
|
||||||
|
|
||||||
|
- **`a: true` (auto):** The main loop keeps calling `tick()`; the generator runs continuously (subject to internal `yield` timing / `utime`).
|
||||||
|
- **`a: false` (manual):** Intended for patterns that advance **once per explicit `select`** (or per beat routing from the controller). The driver does **not** call `select()` again when editing a manual preset-only push — manual steps are driven by incoming `select` messages.
|
||||||
|
|
||||||
|
Special case in `Presets.select()`: for **manual chase**, if the same preset is re-selected mid-generator, pending frames may be flushed so step indices stay aligned with beats.
|
||||||
|
|
||||||
|
## Built-in patterns
|
||||||
|
|
||||||
|
### `off`
|
||||||
|
|
||||||
|
- **Registration:** built-in method `Presets.off`.
|
||||||
|
- **Behaviour:** fills the strip with black (after generator setup, `tick` completes immediately).
|
||||||
|
- **Parameters:** ignores preset colours for the strip; optional `preset` argument unused for pixels.
|
||||||
|
|
||||||
|
### `on`
|
||||||
|
|
||||||
|
- **Registration:** built-in method `Presets.on`.
|
||||||
|
- **Behaviour:** solid fill with `preset.c[0]` (or white if no colours), via `apply_brightness(..., preset.b)`.
|
||||||
|
- **Parameters:** `c`, `b`; `d` / `n*` not used.
|
||||||
|
|
||||||
|
## Dynamic pattern: `radiate`
|
||||||
|
|
||||||
|
- **File:** `src/patterns/radiate.py`
|
||||||
|
- **Class:** `Radiate` — `run(self, preset)` is a **generator** (must `yield` each frame).
|
||||||
|
- **Pattern key:** `p` = `"radiate"`
|
||||||
|
|
||||||
|
Concept: repeating **nodes** along the strip every **`n1`** LEDs; from each node a lit region expands outward then contracts (timed by **`n2`** / **`n3`**). In **auto**, a new pulse train starts every **`d`** ms and the active colour index advances. In **manual**, a **single** out-and-back cycle runs, then the generator ends (next colour on the next `select`).
|
||||||
|
|
||||||
|
| Field | Role |
|
||||||
|
|-------|------|
|
||||||
|
| `n1` | Node spacing in LEDs (`>= 1`; half-spacing used for symmetry) |
|
||||||
|
| `n2` | Outbound travel time (ms), `>= 1` |
|
||||||
|
| `n3` | Return travel time (ms), `>= 1` |
|
||||||
|
| `d` | Auto only: interval (ms) between re-triggers; `>= 1` |
|
||||||
|
| `c` | Colour list; cycles per retrigger / per manual cycle |
|
||||||
|
| `bg` | Off state / gap colour (via `preset.background_or`) |
|
||||||
|
| `b` | Preset brightness |
|
||||||
|
| `a` | `true` = repeating pulses on a timer; `false` = one shot per select |
|
||||||
|
|
||||||
|
Debug: if `presets.debug` is true (from settings), periodic logs print timing and lit LED counts.
|
||||||
|
|
||||||
|
## Other pattern names (`blink`, `rainbow`, `pulse`, …)
|
||||||
|
|
||||||
|
Those pattern **ids** are valid on the **wire** and in **led-controller** `db/pattern.json`, but they are **not** all present in this repository’s `src/patterns/` tree. On a real device they normally appear as **additional** `patterns/*.py` files delivered by OTA or upload. For the intended **`n1`–`n6`** semantics on the wire, use [API.md](API.md) **Pattern-Specific Parameters**; the implementation must match that contract in each module’s `run(preset)` generator.
|
||||||
|
|
||||||
|
## Quick reference: files
|
||||||
|
|
||||||
|
| File | Role |
|
||||||
|
|------|------|
|
||||||
|
| `src/preset.py` | Preset field model and aliases |
|
||||||
|
| `src/presets.py` | Registry, `select`, `tick`, `off` / `on`, dynamic load |
|
||||||
|
| `src/controller_messages.py` | Parse v1 JSON, apply presets/select/brightness/OTA |
|
||||||
|
| `src/patterns/*.py` | One pattern module per dynamic id (basename = `p`) |
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
|
|
||||||
send_file # noqa: F401
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
try:
|
|
||||||
from functools import wraps
|
|
||||||
except ImportError: # pragma: no cover
|
|
||||||
# MicroPython does not currently implement functools.wraps
|
|
||||||
def wraps(wrapped):
|
|
||||||
def _(wrapper):
|
|
||||||
return wrapper
|
|
||||||
return _
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,225 +0,0 @@
|
|||||||
try:
|
|
||||||
import jwt
|
|
||||||
HAS_JWT = True
|
|
||||||
except ImportError:
|
|
||||||
HAS_JWT = False
|
|
||||||
try:
|
|
||||||
import ubinascii
|
|
||||||
except ImportError:
|
|
||||||
import binascii as ubinascii
|
|
||||||
try:
|
|
||||||
import uhashlib as hashlib
|
|
||||||
except ImportError:
|
|
||||||
import hashlib
|
|
||||||
try:
|
|
||||||
import uhmac as hmac
|
|
||||||
except ImportError:
|
|
||||||
try:
|
|
||||||
import hmac
|
|
||||||
except ImportError:
|
|
||||||
hmac = None
|
|
||||||
import json
|
|
||||||
|
|
||||||
from microdot.microdot import invoke_handler
|
|
||||||
from microdot.helpers import wraps
|
|
||||||
|
|
||||||
|
|
||||||
class SessionDict(dict):
|
|
||||||
"""A session dictionary.
|
|
||||||
|
|
||||||
The session dictionary is a standard Python dictionary that has been
|
|
||||||
extended with convenience ``save()`` and ``delete()`` methods.
|
|
||||||
"""
|
|
||||||
def __init__(self, request, session_dict):
|
|
||||||
super().__init__(session_dict)
|
|
||||||
self.request = request
|
|
||||||
|
|
||||||
def save(self):
|
|
||||||
"""Update the session cookie."""
|
|
||||||
self.request.app._session.update(self.request, self)
|
|
||||||
|
|
||||||
def delete(self):
|
|
||||||
"""Delete the session cookie."""
|
|
||||||
self.request.app._session.delete(self.request)
|
|
||||||
|
|
||||||
|
|
||||||
class Session:
|
|
||||||
"""Session handling
|
|
||||||
|
|
||||||
:param app: The application instance.
|
|
||||||
:param secret_key: The secret key, as a string or bytes object.
|
|
||||||
:param cookie_options: A dictionary with cookie options to pass as
|
|
||||||
arguments to :meth:`Response.set_cookie()
|
|
||||||
<microdot.Response.set_cookie>`.
|
|
||||||
"""
|
|
||||||
secret_key = None
|
|
||||||
|
|
||||||
def __init__(self, app=None, secret_key=None, cookie_options=None):
|
|
||||||
self.secret_key = secret_key
|
|
||||||
self.cookie_options = cookie_options or {}
|
|
||||||
if app is not None:
|
|
||||||
self.initialize(app)
|
|
||||||
|
|
||||||
def initialize(self, app, secret_key=None, cookie_options=None):
|
|
||||||
if secret_key is not None:
|
|
||||||
self.secret_key = secret_key
|
|
||||||
if cookie_options is not None:
|
|
||||||
self.cookie_options = cookie_options
|
|
||||||
if 'path' not in self.cookie_options:
|
|
||||||
self.cookie_options['path'] = '/'
|
|
||||||
if 'http_only' not in self.cookie_options:
|
|
||||||
self.cookie_options['http_only'] = True
|
|
||||||
app._session = self
|
|
||||||
|
|
||||||
def get(self, request):
|
|
||||||
"""Retrieve the user session.
|
|
||||||
|
|
||||||
:param request: The client request.
|
|
||||||
|
|
||||||
The return value is a session dictionary with the data stored in the
|
|
||||||
user's session, or ``{}`` if the session data is not available or
|
|
||||||
invalid.
|
|
||||||
"""
|
|
||||||
if not self.secret_key:
|
|
||||||
raise ValueError('The session secret key is not configured')
|
|
||||||
if hasattr(request.g, '_session'):
|
|
||||||
return request.g._session
|
|
||||||
session = request.cookies.get('session')
|
|
||||||
if session is None:
|
|
||||||
request.g._session = SessionDict(request, {})
|
|
||||||
return request.g._session
|
|
||||||
request.g._session = SessionDict(request, self.decode(session))
|
|
||||||
return request.g._session
|
|
||||||
|
|
||||||
def update(self, request, session):
|
|
||||||
"""Update the user session.
|
|
||||||
|
|
||||||
:param request: The client request.
|
|
||||||
:param session: A dictionary with the update session data for the user.
|
|
||||||
|
|
||||||
Applications would normally not call this method directly, instead they
|
|
||||||
would use the :meth:`SessionDict.save` method on the session
|
|
||||||
dictionary, which calls this method. For example::
|
|
||||||
|
|
||||||
@app.route('/')
|
|
||||||
@with_session
|
|
||||||
def index(request, session):
|
|
||||||
session['foo'] = 'bar'
|
|
||||||
session.save()
|
|
||||||
return 'Hello, World!'
|
|
||||||
|
|
||||||
Calling this method adds a cookie with the updated session to the
|
|
||||||
request currently being processed.
|
|
||||||
"""
|
|
||||||
if not self.secret_key:
|
|
||||||
raise ValueError('The session secret key is not configured')
|
|
||||||
|
|
||||||
encoded_session = self.encode(session)
|
|
||||||
|
|
||||||
@request.after_request
|
|
||||||
def _update_session(request, response):
|
|
||||||
response.set_cookie('session', encoded_session,
|
|
||||||
**self.cookie_options)
|
|
||||||
return response
|
|
||||||
|
|
||||||
def delete(self, request):
|
|
||||||
"""Remove the user session.
|
|
||||||
|
|
||||||
:param request: The client request.
|
|
||||||
|
|
||||||
Applications would normally not call this method directly, instead they
|
|
||||||
would use the :meth:`SessionDict.delete` method on the session
|
|
||||||
dictionary, which calls this method. For example::
|
|
||||||
|
|
||||||
@app.route('/')
|
|
||||||
@with_session
|
|
||||||
def index(request, session):
|
|
||||||
session.delete()
|
|
||||||
return 'Hello, World!'
|
|
||||||
|
|
||||||
Calling this method adds a cookie removal header to the request
|
|
||||||
currently being processed.
|
|
||||||
"""
|
|
||||||
@request.after_request
|
|
||||||
def _delete_session(request, response):
|
|
||||||
response.delete_cookie('session', **self.cookie_options)
|
|
||||||
return response
|
|
||||||
|
|
||||||
def encode(self, payload, secret_key=None):
|
|
||||||
"""Encode session data using JWT if available, otherwise use simple HMAC."""
|
|
||||||
if HAS_JWT:
|
|
||||||
return jwt.encode(payload, secret_key or self.secret_key,
|
|
||||||
algorithm='HS256')
|
|
||||||
else:
|
|
||||||
# Simple encoding for MicroPython: base64(json) + HMAC signature
|
|
||||||
key = (secret_key or self.secret_key).encode() if isinstance(secret_key or self.secret_key, str) else (secret_key or self.secret_key)
|
|
||||||
payload_json = json.dumps(payload)
|
|
||||||
payload_b64 = ubinascii.b2a_base64(payload_json.encode()).decode().strip()
|
|
||||||
|
|
||||||
# Create HMAC signature
|
|
||||||
if hmac:
|
|
||||||
# Use hmac module if available
|
|
||||||
h = hmac.new(key, payload_json.encode(), hashlib.sha256)
|
|
||||||
else:
|
|
||||||
# Fallback: simple SHA256(key + message)
|
|
||||||
h = hashlib.sha256(key + payload_json.encode())
|
|
||||||
signature = ubinascii.b2a_base64(h.digest()).decode().strip()
|
|
||||||
|
|
||||||
return f"{payload_b64}.{signature}"
|
|
||||||
|
|
||||||
def decode(self, session, secret_key=None):
|
|
||||||
"""Decode session data using JWT if available, otherwise use simple HMAC."""
|
|
||||||
if HAS_JWT:
|
|
||||||
try:
|
|
||||||
payload = jwt.decode(session, secret_key or self.secret_key,
|
|
||||||
algorithms=['HS256'])
|
|
||||||
except jwt.exceptions.PyJWTError: # pragma: no cover
|
|
||||||
return {}
|
|
||||||
return payload
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
# Simple decoding for MicroPython
|
|
||||||
if '.' not in session:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
payload_b64, signature = session.rsplit('.', 1)
|
|
||||||
payload_json = ubinascii.a2b_base64(payload_b64).decode()
|
|
||||||
|
|
||||||
# Verify HMAC signature
|
|
||||||
key = (secret_key or self.secret_key).encode() if isinstance(secret_key or self.secret_key, str) else (secret_key or self.secret_key)
|
|
||||||
if hmac:
|
|
||||||
# Use hmac module if available
|
|
||||||
h = hmac.new(key, payload_json.encode(), hashlib.sha256)
|
|
||||||
else:
|
|
||||||
# Fallback: simple SHA256(key + message)
|
|
||||||
h = hashlib.sha256(key + payload_json.encode())
|
|
||||||
expected_signature = ubinascii.b2a_base64(h.digest()).decode().strip()
|
|
||||||
|
|
||||||
if signature != expected_signature:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
return json.loads(payload_json)
|
|
||||||
except Exception:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
|
|
||||||
def with_session(f):
|
|
||||||
"""Decorator that passes the user session to the route handler.
|
|
||||||
|
|
||||||
The session dictionary is passed to the decorated function as an argument
|
|
||||||
after the request object. Example::
|
|
||||||
|
|
||||||
@app.route('/')
|
|
||||||
@with_session
|
|
||||||
def index(request, session):
|
|
||||||
return 'Hello, World!'
|
|
||||||
|
|
||||||
Note that the decorator does not save the session. To update the session,
|
|
||||||
call the :func:`session.save() <microdot.session.SessionDict.save>` method.
|
|
||||||
"""
|
|
||||||
@wraps(f)
|
|
||||||
async def wrapper(request, *args, **kwargs):
|
|
||||||
return await invoke_handler(
|
|
||||||
f, request, request.app._session.get(request), *args, **kwargs)
|
|
||||||
|
|
||||||
return wrapper
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
from utemplate import recompile
|
|
||||||
|
|
||||||
_loader = None
|
|
||||||
|
|
||||||
|
|
||||||
class Template:
|
|
||||||
"""A template object.
|
|
||||||
|
|
||||||
:param template: The filename of the template to render, relative to the
|
|
||||||
configured template directory.
|
|
||||||
"""
|
|
||||||
@classmethod
|
|
||||||
def initialize(cls, template_dir='templates',
|
|
||||||
loader_class=recompile.Loader):
|
|
||||||
"""Initialize the templating subsystem.
|
|
||||||
|
|
||||||
:param template_dir: the directory where templates are stored. This
|
|
||||||
argument is optional. The default is to load
|
|
||||||
templates from a *templates* subdirectory.
|
|
||||||
:param loader_class: the ``utemplate.Loader`` class to use when loading
|
|
||||||
templates. This argument is optional. The default
|
|
||||||
is the ``recompile.Loader`` class, which
|
|
||||||
automatically recompiles templates when they
|
|
||||||
change.
|
|
||||||
"""
|
|
||||||
global _loader
|
|
||||||
_loader = loader_class(None, template_dir)
|
|
||||||
|
|
||||||
def __init__(self, template):
|
|
||||||
if _loader is None: # pragma: no cover
|
|
||||||
self.initialize()
|
|
||||||
#: The name of the template
|
|
||||||
self.name = template
|
|
||||||
self.template = _loader.load(template)
|
|
||||||
|
|
||||||
def generate(self, *args, **kwargs):
|
|
||||||
"""Return a generator that renders the template in chunks, with the
|
|
||||||
given arguments."""
|
|
||||||
return self.template(*args, **kwargs)
|
|
||||||
|
|
||||||
def render(self, *args, **kwargs):
|
|
||||||
"""Render the template with the given arguments and return it as a
|
|
||||||
string."""
|
|
||||||
return ''.join(self.generate(*args, **kwargs))
|
|
||||||
|
|
||||||
def generate_async(self, *args, **kwargs):
|
|
||||||
"""Return an asynchronous generator that renders the template in
|
|
||||||
chunks, using the given arguments."""
|
|
||||||
class sync_to_async_iter():
|
|
||||||
def __init__(self, iter):
|
|
||||||
self.iter = iter
|
|
||||||
|
|
||||||
def __aiter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __anext__(self):
|
|
||||||
try:
|
|
||||||
return next(self.iter)
|
|
||||||
except StopIteration:
|
|
||||||
raise StopAsyncIteration
|
|
||||||
|
|
||||||
return sync_to_async_iter(self.generate(*args, **kwargs))
|
|
||||||
|
|
||||||
async def render_async(self, *args, **kwargs):
|
|
||||||
"""Render the template with the given arguments asynchronously and
|
|
||||||
return it as a string."""
|
|
||||||
response = ''
|
|
||||||
async for chunk in self.generate_async(*args, **kwargs):
|
|
||||||
response += chunk
|
|
||||||
return response
|
|
||||||
@@ -1,231 +0,0 @@
|
|||||||
import binascii
|
|
||||||
import hashlib
|
|
||||||
from microdot import Request, Response
|
|
||||||
from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception
|
|
||||||
from microdot.helpers import wraps
|
|
||||||
|
|
||||||
|
|
||||||
class WebSocketError(Exception):
|
|
||||||
"""Exception raised when an error occurs in a WebSocket connection."""
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class WebSocket:
|
|
||||||
"""A WebSocket connection object.
|
|
||||||
|
|
||||||
An instance of this class is sent to handler functions to manage the
|
|
||||||
WebSocket connection.
|
|
||||||
"""
|
|
||||||
CONT = 0
|
|
||||||
TEXT = 1
|
|
||||||
BINARY = 2
|
|
||||||
CLOSE = 8
|
|
||||||
PING = 9
|
|
||||||
PONG = 10
|
|
||||||
|
|
||||||
#: Specify the maximum message size that can be received when calling the
|
|
||||||
#: ``receive()`` method. Messages with payloads that are larger than this
|
|
||||||
#: size will be rejected and the connection closed. Set to 0 to disable
|
|
||||||
#: the size check (be aware of potential security issues if you do this),
|
|
||||||
#: or to -1 to use the value set in
|
|
||||||
#: ``Request.max_body_length``. The default is -1.
|
|
||||||
#:
|
|
||||||
#: Example::
|
|
||||||
#:
|
|
||||||
#: WebSocket.max_message_length = 4 * 1024 # up to 4KB messages
|
|
||||||
max_message_length = -1
|
|
||||||
|
|
||||||
def __init__(self, request):
|
|
||||||
self.request = request
|
|
||||||
self.closed = False
|
|
||||||
|
|
||||||
async def handshake(self):
|
|
||||||
response = self._handshake_response()
|
|
||||||
await self.request.sock[1].awrite(
|
|
||||||
b'HTTP/1.1 101 Switching Protocols\r\n')
|
|
||||||
await self.request.sock[1].awrite(b'Upgrade: websocket\r\n')
|
|
||||||
await self.request.sock[1].awrite(b'Connection: Upgrade\r\n')
|
|
||||||
await self.request.sock[1].awrite(
|
|
||||||
b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n')
|
|
||||||
|
|
||||||
async def receive(self):
|
|
||||||
"""Receive a message from the client."""
|
|
||||||
while True:
|
|
||||||
opcode, payload = await self._read_frame()
|
|
||||||
send_opcode, data = self._process_websocket_frame(opcode, payload)
|
|
||||||
if send_opcode: # pragma: no cover
|
|
||||||
await self.send(data, send_opcode)
|
|
||||||
elif data: # pragma: no branch
|
|
||||||
return data
|
|
||||||
|
|
||||||
async def send(self, data, opcode=None):
|
|
||||||
"""Send a message to the client.
|
|
||||||
|
|
||||||
:param data: the data to send, given as a string or bytes.
|
|
||||||
:param opcode: a custom frame opcode to use. If not given, the opcode
|
|
||||||
is ``TEXT`` or ``BINARY`` depending on the type of the
|
|
||||||
data.
|
|
||||||
"""
|
|
||||||
frame = self._encode_websocket_frame(
|
|
||||||
opcode or (self.TEXT if isinstance(data, str) else self.BINARY),
|
|
||||||
data)
|
|
||||||
await self.request.sock[1].awrite(frame)
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
"""Close the websocket connection."""
|
|
||||||
if not self.closed: # pragma: no cover
|
|
||||||
self.closed = True
|
|
||||||
await self.send(b'', self.CLOSE)
|
|
||||||
|
|
||||||
def _handshake_response(self):
|
|
||||||
connection = False
|
|
||||||
upgrade = False
|
|
||||||
websocket_key = None
|
|
||||||
for header, value in self.request.headers.items():
|
|
||||||
h = header.lower()
|
|
||||||
if h == 'connection':
|
|
||||||
connection = True
|
|
||||||
if 'upgrade' not in value.lower():
|
|
||||||
return self.request.app.abort(400)
|
|
||||||
elif h == 'upgrade':
|
|
||||||
upgrade = True
|
|
||||||
if not value.lower() == 'websocket':
|
|
||||||
return self.request.app.abort(400)
|
|
||||||
elif h == 'sec-websocket-key':
|
|
||||||
websocket_key = value
|
|
||||||
if not connection or not upgrade or not websocket_key:
|
|
||||||
return self.request.app.abort(400)
|
|
||||||
d = hashlib.sha1(websocket_key.encode())
|
|
||||||
d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
|
|
||||||
return binascii.b2a_base64(d.digest())[:-1]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _parse_frame_header(cls, header):
|
|
||||||
fin = header[0] & 0x80
|
|
||||||
opcode = header[0] & 0x0f
|
|
||||||
if fin == 0 or opcode == cls.CONT: # pragma: no cover
|
|
||||||
raise WebSocketError('Continuation frames not supported')
|
|
||||||
has_mask = header[1] & 0x80
|
|
||||||
length = header[1] & 0x7f
|
|
||||||
if length == 126:
|
|
||||||
length = -2
|
|
||||||
elif length == 127:
|
|
||||||
length = -8
|
|
||||||
return fin, opcode, has_mask, length
|
|
||||||
|
|
||||||
def _process_websocket_frame(self, opcode, payload):
|
|
||||||
if opcode == self.TEXT:
|
|
||||||
payload = payload.decode()
|
|
||||||
elif opcode == self.BINARY:
|
|
||||||
pass
|
|
||||||
elif opcode == self.CLOSE:
|
|
||||||
raise WebSocketError('Websocket connection closed')
|
|
||||||
elif opcode == self.PING:
|
|
||||||
return self.PONG, payload
|
|
||||||
elif opcode == self.PONG: # pragma: no branch
|
|
||||||
return None, None
|
|
||||||
return None, payload
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _encode_websocket_frame(cls, opcode, payload):
|
|
||||||
frame = bytearray()
|
|
||||||
frame.append(0x80 | opcode)
|
|
||||||
if opcode == cls.TEXT:
|
|
||||||
payload = payload.encode()
|
|
||||||
if len(payload) < 126:
|
|
||||||
frame.append(len(payload))
|
|
||||||
elif len(payload) < (1 << 16):
|
|
||||||
frame.append(126)
|
|
||||||
frame.extend(len(payload).to_bytes(2, 'big'))
|
|
||||||
else:
|
|
||||||
frame.append(127)
|
|
||||||
frame.extend(len(payload).to_bytes(8, 'big'))
|
|
||||||
frame.extend(payload)
|
|
||||||
return frame
|
|
||||||
|
|
||||||
async def _read_frame(self):
|
|
||||||
header = await self.request.sock[0].read(2)
|
|
||||||
if len(header) != 2: # pragma: no cover
|
|
||||||
raise WebSocketError('Websocket connection closed')
|
|
||||||
fin, opcode, has_mask, length = self._parse_frame_header(header)
|
|
||||||
if length == -2:
|
|
||||||
length = await self.request.sock[0].read(2)
|
|
||||||
length = int.from_bytes(length, 'big')
|
|
||||||
elif length == -8:
|
|
||||||
length = await self.request.sock[0].read(8)
|
|
||||||
length = int.from_bytes(length, 'big')
|
|
||||||
max_allowed_length = Request.max_body_length \
|
|
||||||
if self.max_message_length == -1 else self.max_message_length
|
|
||||||
if length > max_allowed_length:
|
|
||||||
raise WebSocketError('Message too large')
|
|
||||||
if has_mask: # pragma: no cover
|
|
||||||
mask = await self.request.sock[0].read(4)
|
|
||||||
payload = await self.request.sock[0].read(length)
|
|
||||||
if has_mask: # pragma: no cover
|
|
||||||
payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload))
|
|
||||||
return opcode, payload
|
|
||||||
|
|
||||||
|
|
||||||
async def websocket_upgrade(request):
|
|
||||||
"""Upgrade a request handler to a websocket connection.
|
|
||||||
|
|
||||||
This function can be called directly inside a route function to process a
|
|
||||||
WebSocket upgrade handshake, for example after the user's credentials are
|
|
||||||
verified. The function returns the websocket object::
|
|
||||||
|
|
||||||
@app.route('/echo')
|
|
||||||
async def echo(request):
|
|
||||||
if not authenticate_user(request):
|
|
||||||
abort(401)
|
|
||||||
ws = await websocket_upgrade(request)
|
|
||||||
while True:
|
|
||||||
message = await ws.receive()
|
|
||||||
await ws.send(message)
|
|
||||||
"""
|
|
||||||
ws = WebSocket(request)
|
|
||||||
await ws.handshake()
|
|
||||||
|
|
||||||
@request.after_request
|
|
||||||
async def after_request(request, response):
|
|
||||||
return Response.already_handled
|
|
||||||
|
|
||||||
return ws
|
|
||||||
|
|
||||||
|
|
||||||
def websocket_wrapper(f, upgrade_function):
|
|
||||||
@wraps(f)
|
|
||||||
async def wrapper(request, *args, **kwargs):
|
|
||||||
ws = await upgrade_function(request)
|
|
||||||
try:
|
|
||||||
await f(request, ws, *args, **kwargs)
|
|
||||||
except OSError as exc:
|
|
||||||
if exc.errno not in MUTED_SOCKET_ERRORS: # pragma: no cover
|
|
||||||
raise
|
|
||||||
except WebSocketError:
|
|
||||||
pass
|
|
||||||
except Exception as exc:
|
|
||||||
print_exception(exc)
|
|
||||||
finally: # pragma: no cover
|
|
||||||
try:
|
|
||||||
await ws.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return Response.already_handled
|
|
||||||
return wrapper
|
|
||||||
|
|
||||||
|
|
||||||
def with_websocket(f):
|
|
||||||
"""Decorator to make a route a WebSocket endpoint.
|
|
||||||
|
|
||||||
This decorator is used to define a route that accepts websocket
|
|
||||||
connections. The route then receives a websocket object as a second
|
|
||||||
argument that it can use to send and receive messages::
|
|
||||||
|
|
||||||
@app.route('/echo')
|
|
||||||
@with_websocket
|
|
||||||
async def echo(request, ws):
|
|
||||||
while True:
|
|
||||||
message = await ws.receive()
|
|
||||||
await ws.send(message)
|
|
||||||
"""
|
|
||||||
return websocket_wrapper(f, websocket_upgrade)
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
class Loader:
|
|
||||||
|
|
||||||
def __init__(self, pkg, dir):
|
|
||||||
if dir == ".":
|
|
||||||
dir = ""
|
|
||||||
else:
|
|
||||||
dir = dir.replace("/", ".") + "."
|
|
||||||
if pkg and pkg != "__main__":
|
|
||||||
dir = pkg + "." + dir
|
|
||||||
self.p = dir
|
|
||||||
|
|
||||||
def load(self, name):
|
|
||||||
name = name.replace(".", "_")
|
|
||||||
return __import__(self.p + name, None, None, (name,)).render
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
# (c) 2014-2020 Paul Sokolovsky. MIT license.
|
|
||||||
try:
|
|
||||||
from uos import stat, remove
|
|
||||||
except:
|
|
||||||
from os import stat, remove
|
|
||||||
from . import source
|
|
||||||
|
|
||||||
|
|
||||||
class Loader(source.Loader):
|
|
||||||
|
|
||||||
def load(self, name):
|
|
||||||
o_path = self.pkg_path + self.compiled_path(name)
|
|
||||||
i_path = self.pkg_path + self.dir + "/" + name
|
|
||||||
try:
|
|
||||||
o_stat = stat(o_path)
|
|
||||||
i_stat = stat(i_path)
|
|
||||||
if i_stat[8] > o_stat[8]:
|
|
||||||
# input file is newer, remove output to force recompile
|
|
||||||
remove(o_path)
|
|
||||||
finally:
|
|
||||||
return super().load(name)
|
|
||||||
@@ -1,188 +0,0 @@
|
|||||||
# (c) 2014-2019 Paul Sokolovsky. MIT license.
|
|
||||||
from . import compiled
|
|
||||||
|
|
||||||
|
|
||||||
class Compiler:
|
|
||||||
|
|
||||||
START_CHAR = "{"
|
|
||||||
STMNT = "%"
|
|
||||||
STMNT_END = "%}"
|
|
||||||
EXPR = "{"
|
|
||||||
EXPR_END = "}}"
|
|
||||||
|
|
||||||
def __init__(self, file_in, file_out, indent=0, seq=0, loader=None):
|
|
||||||
self.file_in = file_in
|
|
||||||
self.file_out = file_out
|
|
||||||
self.loader = loader
|
|
||||||
self.seq = seq
|
|
||||||
self._indent = indent
|
|
||||||
self.stack = []
|
|
||||||
self.in_literal = False
|
|
||||||
self.flushed_header = False
|
|
||||||
self.args = "*a, **d"
|
|
||||||
|
|
||||||
def indent(self, adjust=0):
|
|
||||||
if not self.flushed_header:
|
|
||||||
self.flushed_header = True
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write("def render%s(%s):\n" % (str(self.seq) if self.seq else "", self.args))
|
|
||||||
self.stack.append("def")
|
|
||||||
self.file_out.write(" " * (len(self.stack) + self._indent + adjust))
|
|
||||||
|
|
||||||
def literal(self, s):
|
|
||||||
if not s:
|
|
||||||
return
|
|
||||||
if not self.in_literal:
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write('yield """')
|
|
||||||
self.in_literal = True
|
|
||||||
self.file_out.write(s.replace('"', '\\"'))
|
|
||||||
|
|
||||||
def close_literal(self):
|
|
||||||
if self.in_literal:
|
|
||||||
self.file_out.write('"""\n')
|
|
||||||
self.in_literal = False
|
|
||||||
|
|
||||||
def render_expr(self, e):
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write('yield str(' + e + ')\n')
|
|
||||||
|
|
||||||
def parse_statement(self, stmt):
|
|
||||||
tokens = stmt.split(None, 1)
|
|
||||||
if tokens[0] == "args":
|
|
||||||
if len(tokens) > 1:
|
|
||||||
self.args = tokens[1]
|
|
||||||
else:
|
|
||||||
self.args = ""
|
|
||||||
elif tokens[0] == "set":
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write(stmt[3:].strip() + "\n")
|
|
||||||
elif tokens[0] == "include":
|
|
||||||
if not self.flushed_header:
|
|
||||||
# If there was no other output, we still need a header now
|
|
||||||
self.indent()
|
|
||||||
tokens = tokens[1].split(None, 1)
|
|
||||||
args = ""
|
|
||||||
if len(tokens) > 1:
|
|
||||||
args = tokens[1]
|
|
||||||
if tokens[0][0] == "{":
|
|
||||||
self.indent()
|
|
||||||
# "1" as fromlist param is uPy hack
|
|
||||||
self.file_out.write('_ = __import__(%s.replace(".", "_"), None, None, 1)\n' % tokens[0][2:-2])
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write("yield from _.render(%s)\n" % args)
|
|
||||||
return
|
|
||||||
|
|
||||||
with self.loader.input_open(tokens[0][1:-1]) as inc:
|
|
||||||
self.seq += 1
|
|
||||||
c = Compiler(inc, self.file_out, len(self.stack) + self._indent, self.seq)
|
|
||||||
inc_id = self.seq
|
|
||||||
self.seq = c.compile()
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write("yield from render%d(%s)\n" % (inc_id, args))
|
|
||||||
elif len(tokens) > 1:
|
|
||||||
if tokens[0] == "elif":
|
|
||||||
assert self.stack[-1] == "if"
|
|
||||||
self.indent(-1)
|
|
||||||
self.file_out.write(stmt + ":\n")
|
|
||||||
else:
|
|
||||||
self.indent()
|
|
||||||
self.file_out.write(stmt + ":\n")
|
|
||||||
self.stack.append(tokens[0])
|
|
||||||
else:
|
|
||||||
if stmt.startswith("end"):
|
|
||||||
assert self.stack[-1] == stmt[3:]
|
|
||||||
self.stack.pop(-1)
|
|
||||||
elif stmt == "else":
|
|
||||||
assert self.stack[-1] == "if"
|
|
||||||
self.indent(-1)
|
|
||||||
self.file_out.write("else:\n")
|
|
||||||
else:
|
|
||||||
assert False
|
|
||||||
|
|
||||||
def parse_line(self, l):
|
|
||||||
while l:
|
|
||||||
start = l.find(self.START_CHAR)
|
|
||||||
if start == -1:
|
|
||||||
self.literal(l)
|
|
||||||
return
|
|
||||||
self.literal(l[:start])
|
|
||||||
self.close_literal()
|
|
||||||
sel = l[start + 1]
|
|
||||||
#print("*%s=%s=" % (sel, EXPR))
|
|
||||||
if sel == self.STMNT:
|
|
||||||
end = l.find(self.STMNT_END)
|
|
||||||
assert end > 0
|
|
||||||
stmt = l[start + len(self.START_CHAR + self.STMNT):end].strip()
|
|
||||||
self.parse_statement(stmt)
|
|
||||||
end += len(self.STMNT_END)
|
|
||||||
l = l[end:]
|
|
||||||
if not self.in_literal and l == "\n":
|
|
||||||
break
|
|
||||||
elif sel == self.EXPR:
|
|
||||||
# print("EXPR")
|
|
||||||
end = l.find(self.EXPR_END)
|
|
||||||
assert end > 0
|
|
||||||
expr = l[start + len(self.START_CHAR + self.EXPR):end].strip()
|
|
||||||
self.render_expr(expr)
|
|
||||||
end += len(self.EXPR_END)
|
|
||||||
l = l[end:]
|
|
||||||
else:
|
|
||||||
self.literal(l[start])
|
|
||||||
l = l[start + 1:]
|
|
||||||
|
|
||||||
def header(self):
|
|
||||||
self.file_out.write("# Autogenerated file\n")
|
|
||||||
|
|
||||||
def compile(self):
|
|
||||||
self.header()
|
|
||||||
for l in self.file_in:
|
|
||||||
self.parse_line(l)
|
|
||||||
self.close_literal()
|
|
||||||
return self.seq
|
|
||||||
|
|
||||||
|
|
||||||
class Loader(compiled.Loader):
|
|
||||||
|
|
||||||
def __init__(self, pkg, dir):
|
|
||||||
super().__init__(pkg, dir)
|
|
||||||
self.dir = dir
|
|
||||||
if pkg == "__main__":
|
|
||||||
# if pkg isn't really a package, don't bother to use it
|
|
||||||
# it means we're running from "filesystem directory", not
|
|
||||||
# from a package.
|
|
||||||
pkg = None
|
|
||||||
|
|
||||||
self.pkg_path = ""
|
|
||||||
if pkg:
|
|
||||||
p = __import__(pkg)
|
|
||||||
if isinstance(p.__path__, str):
|
|
||||||
# uPy
|
|
||||||
self.pkg_path = p.__path__
|
|
||||||
else:
|
|
||||||
# CPy
|
|
||||||
self.pkg_path = p.__path__[0]
|
|
||||||
self.pkg_path += "/"
|
|
||||||
|
|
||||||
def input_open(self, template):
|
|
||||||
path = self.pkg_path + self.dir + "/" + template
|
|
||||||
return open(path)
|
|
||||||
|
|
||||||
def compiled_path(self, template):
|
|
||||||
return self.dir + "/" + template.replace(".", "_") + ".py"
|
|
||||||
|
|
||||||
def load(self, name):
|
|
||||||
try:
|
|
||||||
return super().load(name)
|
|
||||||
except (OSError, ImportError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
compiled_path = self.pkg_path + self.compiled_path(name)
|
|
||||||
|
|
||||||
f_in = self.input_open(name)
|
|
||||||
f_out = open(compiled_path, "w")
|
|
||||||
c = Compiler(f_in, f_out, loader=self)
|
|
||||||
c.compile()
|
|
||||||
f_in.close()
|
|
||||||
f_out.close()
|
|
||||||
return super().load(name)
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" "presets.cpp"
|
||||||
|
"effects_util.cpp" "ws_client.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp" "usb_cfg.cpp" "beat_sync.cpp" "ctrl_msg.cpp" "espnow_link.cpp"
|
||||||
|
PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event
|
||||||
|
esp_timer nvs_flash esp_http_server esp_http_client cjson mdns esp_hw_support app_update esp_app_format lwip esp_driver_usb_serial_jtag
|
||||||
|
INCLUDE_DIRS "."
|
||||||
|
EMBED_TXTFILES "../web/index.html" "../web/app.js" "../web/style.css")
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include "beat_sync.h"
|
||||||
|
|
||||||
|
#include "esp_timer.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr uint8_t kMagic = 0x4C;
|
||||||
|
constexpr uint8_t kBeat = 0x25;
|
||||||
|
constexpr uint32_t kDefaultPeriodMs = 500;
|
||||||
|
constexpr uint32_t kMinPeriodMs = 30;
|
||||||
|
constexpr uint32_t kMaxPeriodMs = 4000;
|
||||||
|
constexpr int kLostPeriods = 4; // no beat for this many periods: the controller has stopped
|
||||||
|
|
||||||
|
volatile uint16_t s_last_idx;
|
||||||
|
volatile uint32_t s_period_ms;
|
||||||
|
volatile int64_t s_last_us;
|
||||||
|
volatile bool s_have;
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void beat_on_frame(const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
if (len != 8 || data[0] != kMagic || data[1] != kBeat) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint16_t idx = (uint16_t)(data[3] | (data[4] << 8));
|
||||||
|
uint32_t period = (uint32_t)(data[5] | (data[6] << 8));
|
||||||
|
if (s_have && idx == s_last_idx) {
|
||||||
|
return; // the second copy of a beat already taken
|
||||||
|
}
|
||||||
|
if (period < kMinPeriodMs || period > kMaxPeriodMs) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_last_idx = idx;
|
||||||
|
s_period_ms = period;
|
||||||
|
s_last_us = esp_timer_get_time();
|
||||||
|
s_have = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t beat_period_ms(void)
|
||||||
|
{
|
||||||
|
if (!s_have) {
|
||||||
|
return kDefaultPeriodMs;
|
||||||
|
}
|
||||||
|
int64_t age_us = esp_timer_get_time() - s_last_us;
|
||||||
|
if (age_us > (int64_t)s_period_ms * kLostPeriods * 1000) {
|
||||||
|
return kDefaultPeriodMs;
|
||||||
|
}
|
||||||
|
return s_period_ms;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Beat frames from led-controller (ESP-NOW [4C][25][flags][idx u16][period u16][fire_in]). Only the tempo
|
||||||
|
* is used: beat-timed presets (tb) take their quarter-beat durations from it.
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
/** @brief Note a received frame. Called from the ESP-NOW receive callback, so it does no more than store the values. */
|
||||||
|
void beat_on_frame(const uint8_t *data, size_t len);
|
||||||
|
|
||||||
|
/** @brief The controller's beat period in ms while beats are arriving, else 500 (120 BPM). */
|
||||||
|
uint32_t beat_period_ms(void);
|
||||||
@@ -0,0 +1,669 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include "ctrl_msg.h"
|
||||||
|
|
||||||
|
#include <cctype>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_mac.h"
|
||||||
|
#include "nvs.h"
|
||||||
|
#include "nvs_flash.h"
|
||||||
|
|
||||||
|
#include "patterns.h"
|
||||||
|
#include "presets.h"
|
||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
static const char *TAG = "ctrl_msg";
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr uint8_t kMagic = 0x4C;
|
||||||
|
constexpr uint8_t kGroups = 0x02;
|
||||||
|
constexpr uint8_t kCmd = 0x03;
|
||||||
|
constexpr uint8_t kGroupCmd = 0x04;
|
||||||
|
constexpr size_t kGroupsMax = 16;
|
||||||
|
constexpr size_t kGroupIdMax = 24;
|
||||||
|
constexpr size_t kEnvHdr = 5;
|
||||||
|
|
||||||
|
char s_groups[kGroupsMax][kGroupIdMax];
|
||||||
|
size_t s_ngroups;
|
||||||
|
char s_pending[32]; // a select for a preset not saved yet: applied when that preset arrives
|
||||||
|
|
||||||
|
// Copy n bytes as a NUL-terminated string
|
||||||
|
void cstr(char *dst, size_t cap, const uint8_t *src, size_t n)
|
||||||
|
{
|
||||||
|
size_t k = n < cap - 1 ? n : cap - 1;
|
||||||
|
memcpy(dst, src, k);
|
||||||
|
dst[k] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bounds-checked reader over an envelope blob
|
||||||
|
struct Rd {
|
||||||
|
const uint8_t *p;
|
||||||
|
size_t n;
|
||||||
|
size_t off;
|
||||||
|
bool ok;
|
||||||
|
bool bytes(size_t k, const uint8_t **out)
|
||||||
|
{
|
||||||
|
if (!ok || k > n - off) {
|
||||||
|
ok = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
*out = p + off;
|
||||||
|
off += k;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
bool u8(uint8_t *v)
|
||||||
|
{
|
||||||
|
const uint8_t *b;
|
||||||
|
if (!bytes(1, &b)) return false;
|
||||||
|
*v = b[0];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
bool u16(uint16_t *v)
|
||||||
|
{
|
||||||
|
const uint8_t *b;
|
||||||
|
if (!bytes(2, &b)) return false;
|
||||||
|
*v = (uint16_t)(b[0] | (b[1] << 8));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Presets blob: count, then per record name, pattern, colours, delay, brightness, auto, n1..n6 and (v3) an
|
||||||
|
// extension block with fade (key 1) and beat timing (key 2)
|
||||||
|
cJSON *decode_presets(Rd &r, bool v3)
|
||||||
|
{
|
||||||
|
uint8_t count;
|
||||||
|
if (!r.u8(&count)) return nullptr;
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
uint8_t nl, pl, nc;
|
||||||
|
const uint8_t *name, *pat;
|
||||||
|
if (!r.u8(&nl) || !r.bytes(nl, &name) || !r.u8(&pl) || !r.bytes(pl, &pat) || !r.u8(&nc)) {
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
char nm[64], pn[64];
|
||||||
|
cstr(nm, sizeof(nm), name, nl);
|
||||||
|
cstr(pn, sizeof(pn), pat, pl);
|
||||||
|
cJSON *rec = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(rec, "pattern", pn);
|
||||||
|
cJSON *cols = cJSON_AddArrayToObject(rec, "colors");
|
||||||
|
for (int c = 0; c < nc; c++) {
|
||||||
|
const uint8_t *rgb;
|
||||||
|
if (!r.bytes(3, &rgb)) {
|
||||||
|
cJSON_Delete(rec);
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
int v[3] = { rgb[0], rgb[1], rgb[2] };
|
||||||
|
cJSON_AddItemToArray(cols, cJSON_CreateIntArray(v, 3));
|
||||||
|
}
|
||||||
|
uint16_t delay, nn[6];
|
||||||
|
uint8_t br, au;
|
||||||
|
bool ok = r.u16(&delay) && r.u8(&br) && r.u8(&au);
|
||||||
|
for (int k = 0; ok && k < 6; k++) {
|
||||||
|
ok = r.u16(&nn[k]);
|
||||||
|
}
|
||||||
|
if (!ok) {
|
||||||
|
cJSON_Delete(rec);
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
cJSON_AddNumberToObject(rec, "delay", delay);
|
||||||
|
cJSON_AddNumberToObject(rec, "brightness", br);
|
||||||
|
cJSON_AddBoolToObject(rec, "auto", au != 0);
|
||||||
|
for (int k = 0; k < 6; k++) {
|
||||||
|
char key[4] = { 'n', (char)('1' + k), '\0' };
|
||||||
|
cJSON_AddNumberToObject(rec, key, (int16_t)nn[k]);
|
||||||
|
}
|
||||||
|
if (v3) {
|
||||||
|
uint8_t ext_len;
|
||||||
|
const uint8_t *ext;
|
||||||
|
if (!r.u8(&ext_len) || !r.bytes(ext_len, &ext)) {
|
||||||
|
cJSON_Delete(rec);
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
Rd e = { ext, ext_len, 0, true };
|
||||||
|
while (e.off < e.n) {
|
||||||
|
uint8_t key, len;
|
||||||
|
const uint8_t *val;
|
||||||
|
if (!e.u8(&key) || !e.u8(&len) || !e.bytes(len, &val)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (key == 1 && len == 2) {
|
||||||
|
cJSON_AddNumberToObject(rec, "fade", val[0] | (val[1] << 8));
|
||||||
|
} else if (key == 2 && len == 1) {
|
||||||
|
cJSON_AddBoolToObject(rec, "beat_time", val[0] != 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(o, nm, rec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return o;
|
||||||
|
fail:
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Select blob: per device, its preset name and an optional step
|
||||||
|
cJSON *decode_select(Rd &r)
|
||||||
|
{
|
||||||
|
uint8_t count;
|
||||||
|
if (!r.u8(&count)) return nullptr;
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
uint8_t dl, pl, has;
|
||||||
|
const uint8_t *dev, *pname;
|
||||||
|
if (!r.u8(&dl) || !r.bytes(dl, &dev) || !r.u8(&pl) || !r.bytes(pl, &pname) || !r.u8(&has)) {
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
char dn[64], pn[64];
|
||||||
|
cstr(dn, sizeof(dn), dev, dl);
|
||||||
|
cstr(pn, sizeof(pn), pname, pl);
|
||||||
|
cJSON *arr = cJSON_CreateArray();
|
||||||
|
cJSON_AddItemToArray(arr, cJSON_CreateString(pn));
|
||||||
|
if (has) {
|
||||||
|
uint16_t step;
|
||||||
|
if (!r.u16(&step)) {
|
||||||
|
cJSON_Delete(arr);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToArray(arr, cJSON_CreateNumber(step));
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(o, dn, arr);
|
||||||
|
}
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default blob: the startup preset name and the devices it applies to
|
||||||
|
bool decode_default(Rd &r, cJSON *o)
|
||||||
|
{
|
||||||
|
uint8_t nl, nt;
|
||||||
|
const uint8_t *name;
|
||||||
|
if (!r.u8(&nl) || !r.bytes(nl, &name)) return false;
|
||||||
|
char dn[64];
|
||||||
|
cstr(dn, sizeof(dn), name, nl);
|
||||||
|
cJSON_AddStringToObject(o, "default", dn);
|
||||||
|
if (!r.u8(&nt)) return false;
|
||||||
|
cJSON *targets = cJSON_AddArrayToObject(o, "targets");
|
||||||
|
for (int i = 0; i < nt; i++) {
|
||||||
|
uint8_t tl;
|
||||||
|
const uint8_t *t;
|
||||||
|
if (!r.u8(&tl) || !r.bytes(tl, &t)) return false;
|
||||||
|
char tn[64];
|
||||||
|
cstr(tn, sizeof(tn), t, tl);
|
||||||
|
cJSON_AddItemToArray(targets, cJSON_CreateString(tn));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A v2/v3 envelope as the v1 JSON object the MicroPython driver works from
|
||||||
|
cJSON *env_to_json(const uint8_t *b, size_t n)
|
||||||
|
{
|
||||||
|
if (n < kEnvHdr || (b[0] != 2 && b[0] != 3)) return nullptr;
|
||||||
|
size_t lp = b[2], ls = b[3], ld = b[4];
|
||||||
|
// CMD and GROUP_CMD frames may end with the controller's save byte after the envelope: ignored, as settings
|
||||||
|
// are saved on every change
|
||||||
|
size_t want = kEnvHdr + lp + ls + ld;
|
||||||
|
if (n != want && n != want + 1) return nullptr;
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(o, "v", "1");
|
||||||
|
uint8_t w = b[1];
|
||||||
|
if (w < 128) { // device brightness, 0-127 on the wire
|
||||||
|
int v = (w * 255) / 127;
|
||||||
|
cJSON_AddNumberToObject(o, "b", v > 255 ? 255 : v);
|
||||||
|
}
|
||||||
|
Rd p = { b + kEnvHdr, lp, 0, true };
|
||||||
|
Rd s = { b + kEnvHdr + lp, ls, 0, true };
|
||||||
|
Rd d = { b + kEnvHdr + lp + ls, ld, 0, true };
|
||||||
|
if (lp) {
|
||||||
|
cJSON *pr = decode_presets(p, b[0] == 3);
|
||||||
|
if (!pr) goto fail;
|
||||||
|
cJSON_AddItemToObject(o, "presets", pr);
|
||||||
|
}
|
||||||
|
if (ls) {
|
||||||
|
cJSON *sel = decode_select(s);
|
||||||
|
if (!sel) goto fail;
|
||||||
|
cJSON_AddItemToObject(o, "select", sel);
|
||||||
|
}
|
||||||
|
if (ld && !decode_default(d, o)) goto fail;
|
||||||
|
return o;
|
||||||
|
fail:
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This driver's MAC as 12 lowercase hex digits, the way the controller names a device
|
||||||
|
void own_mac_hex(char out[13])
|
||||||
|
{
|
||||||
|
uint8_t mac[6];
|
||||||
|
esp_read_mac(mac, ESP_MAC_WIFI_STA);
|
||||||
|
snprintf(out, 13, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A select or default names this driver if it names its hostname or its MAC (any separators), or "*"
|
||||||
|
bool names_me(const char *name)
|
||||||
|
{
|
||||||
|
if (strcmp(name, "*") == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (strcmp(name, n.hostname) == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
char mine[13], hex[13];
|
||||||
|
own_mac_hex(mine);
|
||||||
|
size_t k = 0;
|
||||||
|
for (const char *c = name; *c; c++) {
|
||||||
|
if (isxdigit((unsigned char)*c)) {
|
||||||
|
if (k < 12) hex[k] = (char)tolower((unsigned char)*c);
|
||||||
|
k++;
|
||||||
|
} else if (*c != ':' && *c != '-') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hex[12] = '\0';
|
||||||
|
return k == 12 && strcmp(hex, mine) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool in_group(const char *gid)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < s_ngroups; i++) {
|
||||||
|
if (strcmp(s_groups[i], gid) == 0) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void save_groups(void)
|
||||||
|
{
|
||||||
|
char buf[kGroupsMax * (kGroupIdMax + 1)] = "";
|
||||||
|
for (size_t i = 0; i < s_ngroups; i++) {
|
||||||
|
if (i) strncat(buf, "\n", sizeof(buf) - strlen(buf) - 1);
|
||||||
|
strncat(buf, s_groups[i], sizeof(buf) - strlen(buf) - 1);
|
||||||
|
}
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open("espnow", NVS_READWRITE, &h) == ESP_OK) {
|
||||||
|
nvs_set_str(h, "groups", buf);
|
||||||
|
nvs_commit(h);
|
||||||
|
nvs_close(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GROUPS: [4C][02][count] then per id [len][id]. The list replaces the stored one.
|
||||||
|
void set_groups(const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
if (len < 3) return;
|
||||||
|
size_t count = data[2], off = 3;
|
||||||
|
s_ngroups = 0;
|
||||||
|
for (size_t i = 0; i < count && off < len; i++) {
|
||||||
|
size_t gl = data[off++];
|
||||||
|
if (gl == 0 || off + gl > len) break;
|
||||||
|
if (gl < kGroupIdMax && s_ngroups < kGroupsMax) {
|
||||||
|
cstr(s_groups[s_ngroups], kGroupIdMax, data + off, gl);
|
||||||
|
s_ngroups++;
|
||||||
|
}
|
||||||
|
off += gl;
|
||||||
|
}
|
||||||
|
save_groups();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The device settings in a device_config object, applied to the strip and the saved network settings
|
||||||
|
void apply_device_config(const cJSON *dc)
|
||||||
|
{
|
||||||
|
if (!cJSON_IsObject(dc)) return;
|
||||||
|
const cJSON *v = cJSON_GetObjectItem(dc, "name");
|
||||||
|
if (cJSON_IsString(v) && v->valuestring[0]) {
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
cstr(n.hostname, sizeof(n.hostname), (const uint8_t *)v->valuestring, strlen(v->valuestring));
|
||||||
|
settings_save_net(&n);
|
||||||
|
}
|
||||||
|
hw_cfg_t hw;
|
||||||
|
settings_load_hw(&hw);
|
||||||
|
bool changed = false;
|
||||||
|
v = cJSON_GetObjectItem(dc, "num_leds");
|
||||||
|
if (cJSON_IsNumber(v) && v->valueint >= 1 && v->valueint <= 512) {
|
||||||
|
hw.num_leds = v->valueint;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(dc, "max_brightness");
|
||||||
|
if (cJSON_IsNumber(v) && v->valueint >= 0 && v->valueint <= 255) {
|
||||||
|
hw.max_brightness = (uint8_t)v->valueint;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(dc, "color_order");
|
||||||
|
if (cJSON_IsString(v)) {
|
||||||
|
static const char *orders[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" };
|
||||||
|
for (const char *o : orders) {
|
||||||
|
if (strcmp(v->valuestring, o) == 0) {
|
||||||
|
strncpy(hw.order, o, sizeof(hw.order) - 1);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
settings_save_hw(&hw);
|
||||||
|
patterns_set_hardware(hw);
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(dc, "startup_mode");
|
||||||
|
if (cJSON_IsString(v) && strcmp(v->valuestring, "off") == 0) {
|
||||||
|
presets_set_startup("");
|
||||||
|
}
|
||||||
|
// "reversed" is accepted and ignored: the C++ driver does not reverse its strip yet
|
||||||
|
}
|
||||||
|
|
||||||
|
void clear_all_presets(void)
|
||||||
|
{
|
||||||
|
while (presets_count() > 0) {
|
||||||
|
char name[32];
|
||||||
|
snprintf(name, sizeof(name), "%s", presets_at(0)->name);
|
||||||
|
presets_delete(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save each preset by name. Missing fields keep the pattern's defaults.
|
||||||
|
void apply_presets(const cJSON *presets)
|
||||||
|
{
|
||||||
|
const cJSON *rec;
|
||||||
|
cJSON_ArrayForEach(rec, presets)
|
||||||
|
{
|
||||||
|
const cJSON *pat = cJSON_GetObjectItem(rec, "pattern");
|
||||||
|
int idx = cJSON_IsString(pat) ? patterns_index(pat->valuestring) : -1;
|
||||||
|
if (idx < 0) {
|
||||||
|
ESP_LOGW(TAG, "preset %s: unknown pattern", rec->string);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
preset_t p;
|
||||||
|
preset_defaults(&p, idx);
|
||||||
|
snprintf(p.name, sizeof(p.name), "%s", rec->string);
|
||||||
|
if (preset_from_json(rec, &p)) {
|
||||||
|
presets_save(&p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s_pending[0] && presets_select(s_pending) == ESP_OK) {
|
||||||
|
s_pending[0] = '\0';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The select entry for this driver: a device key that names it, else the only entry
|
||||||
|
const cJSON *pick_select(const cJSON *sel)
|
||||||
|
{
|
||||||
|
if (cJSON_IsString(sel)) {
|
||||||
|
return sel;
|
||||||
|
}
|
||||||
|
if (cJSON_IsArray(sel)) {
|
||||||
|
return cJSON_GetArrayItem(sel, 0);
|
||||||
|
}
|
||||||
|
if (!cJSON_IsObject(sel)) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
const cJSON *e;
|
||||||
|
cJSON_ArrayForEach(e, sel)
|
||||||
|
{
|
||||||
|
if (names_me(e->string)) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cJSON_GetArraySize(sel) == 1 ? sel->child : nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void apply_select(const cJSON *sel)
|
||||||
|
{
|
||||||
|
const cJSON *e = pick_select(sel);
|
||||||
|
if (!e) return;
|
||||||
|
// an entry is [name, step] or a bare name; step is not used by this driver
|
||||||
|
const cJSON *name = cJSON_IsArray(e) ? cJSON_GetArrayItem(e, 0) : e;
|
||||||
|
if (!cJSON_IsString(name) || !name->valuestring[0]) return;
|
||||||
|
if (presets_select(name->valuestring) == ESP_OK) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// "on" and "off" are the built-in patterns (the controller's identify ends with "off"): select them
|
||||||
|
if (strcmp(name->valuestring, "on") == 0 || strcmp(name->valuestring, "off") == 0) {
|
||||||
|
preset_t p;
|
||||||
|
preset_defaults(&p, patterns_index(name->valuestring));
|
||||||
|
snprintf(p.name, sizeof(p.name), "%s", name->valuestring);
|
||||||
|
patterns_select(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
snprintf(s_pending, sizeof(s_pending), "%s", name->valuestring); // preset not here yet
|
||||||
|
}
|
||||||
|
|
||||||
|
// A default applies when there are no targets or this driver is one of them
|
||||||
|
void apply_default(const cJSON *d)
|
||||||
|
{
|
||||||
|
const cJSON *def = cJSON_GetObjectItem(d, "default");
|
||||||
|
if (!cJSON_IsString(def)) return;
|
||||||
|
const cJSON *targets = cJSON_GetObjectItem(d, "targets");
|
||||||
|
if (cJSON_IsArray(targets) && cJSON_GetArraySize(targets) > 0) {
|
||||||
|
bool hit = false;
|
||||||
|
const cJSON *t;
|
||||||
|
cJSON_ArrayForEach(t, targets)
|
||||||
|
{
|
||||||
|
if (cJSON_IsString(t) && names_me(t->valuestring)) hit = true;
|
||||||
|
}
|
||||||
|
if (!hit) return;
|
||||||
|
}
|
||||||
|
presets_set_startup(def->valuestring);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The controller's JSON path shortens keys (engine.c compact()); these map them back to the long names
|
||||||
|
struct KeyName {
|
||||||
|
const char *shortk;
|
||||||
|
const char *longk;
|
||||||
|
};
|
||||||
|
constexpr KeyName kTopKeys[] = {
|
||||||
|
{"p", "presets"}, {"s", "select"}, {"g", "groups"}, {"sg", "set_groups"},
|
||||||
|
{"sv", "save"}, {"df", "default"}, {"dc", "device_config"}, {"cp", "clear_presets"},
|
||||||
|
{"mf", "manifest"},
|
||||||
|
};
|
||||||
|
constexpr KeyName kPresetKeys[] = {
|
||||||
|
{"p", "pattern"}, {"c", "colors"}, {"d", "delay"}, {"b", "brightness"},
|
||||||
|
{"a", "auto"}, {"bg", "background"}, {"f", "fade"}, {"tb", "beat_time"},
|
||||||
|
};
|
||||||
|
|
||||||
|
const char *long_name(const KeyName *map, size_t n, const char *k)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < n; i++) {
|
||||||
|
if (strcmp(map[i].shortk, k) == 0) return map[i].longk;
|
||||||
|
}
|
||||||
|
return k;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A copy of one preset object with long key names
|
||||||
|
cJSON *expand_preset(const cJSON *src)
|
||||||
|
{
|
||||||
|
cJSON *out = cJSON_CreateObject();
|
||||||
|
const cJSON *it;
|
||||||
|
cJSON_ArrayForEach(it, src)
|
||||||
|
{
|
||||||
|
const char *k = long_name(kPresetKeys, sizeof(kPresetKeys) / sizeof(kPresetKeys[0]), it->string);
|
||||||
|
if (!cJSON_HasObjectItem(out, k)) cJSON_AddItemToObject(out, k, cJSON_Duplicate(it, true));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A copy of a v1 message with long key names (its presets too)
|
||||||
|
cJSON *expand_v1(const cJSON *src)
|
||||||
|
{
|
||||||
|
cJSON *out = cJSON_CreateObject();
|
||||||
|
const cJSON *it;
|
||||||
|
cJSON_ArrayForEach(it, src)
|
||||||
|
{
|
||||||
|
const char *k = long_name(kTopKeys, sizeof(kTopKeys) / sizeof(kTopKeys[0]), it->string);
|
||||||
|
if (cJSON_HasObjectItem(out, k)) continue;
|
||||||
|
if (strcmp(k, "presets") == 0 && cJSON_IsObject(it)) {
|
||||||
|
cJSON *ps = cJSON_AddObjectToObject(out, "presets");
|
||||||
|
const cJSON *p;
|
||||||
|
cJSON_ArrayForEach(p, it) { cJSON_AddItemToObject(ps, p->string, expand_preset(p)); }
|
||||||
|
} else {
|
||||||
|
cJSON_AddItemToObject(out, k, cJSON_Duplicate(it, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A JSON message with groups applies only when this driver is in one of them (no groups: everyone)
|
||||||
|
bool json_for_me(const cJSON *o)
|
||||||
|
{
|
||||||
|
const cJSON *groups = cJSON_GetObjectItem(o, "groups");
|
||||||
|
if (!cJSON_IsArray(groups) || cJSON_GetArraySize(groups) == 0) return true;
|
||||||
|
const cJSON *g;
|
||||||
|
cJSON_ArrayForEach(g, groups)
|
||||||
|
{
|
||||||
|
if (cJSON_IsString(g) && in_group(g->valuestring)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One v1 object, in the order controller_messages.py applies them
|
||||||
|
void apply_v1(const cJSON *d)
|
||||||
|
{
|
||||||
|
const cJSON *v = cJSON_GetObjectItem(d, "v");
|
||||||
|
if (!cJSON_IsString(v) || strcmp(v->valuestring, "1") != 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
apply_device_config(cJSON_GetObjectItem(d, "device_config"));
|
||||||
|
v = cJSON_GetObjectItem(d, "b");
|
||||||
|
if (cJSON_IsNumber(v)) {
|
||||||
|
int b = v->valueint < 0 ? 0 : (v->valueint > 255 ? 255 : v->valueint);
|
||||||
|
patterns_set_global((uint8_t)b);
|
||||||
|
}
|
||||||
|
if (cJSON_HasObjectItem(d, "clear_presets")) {
|
||||||
|
clear_all_presets();
|
||||||
|
}
|
||||||
|
const cJSON *presets = cJSON_GetObjectItem(d, "presets");
|
||||||
|
if (cJSON_IsObject(presets)) {
|
||||||
|
apply_presets(presets);
|
||||||
|
}
|
||||||
|
const cJSON *sel = cJSON_GetObjectItem(d, "select");
|
||||||
|
if (sel) {
|
||||||
|
apply_select(sel);
|
||||||
|
}
|
||||||
|
apply_default(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A v2/v3 envelope: applied as a v1 object
|
||||||
|
void handle_env(const uint8_t *env, size_t n)
|
||||||
|
{
|
||||||
|
cJSON *o = env_to_json(env, n);
|
||||||
|
if (!o) {
|
||||||
|
ESP_LOGW(TAG, "bad envelope, %u bytes", (unsigned)n);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
apply_v1(o);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void ctrl_init(void)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open("espnow", NVS_READONLY, &h) != ESP_OK) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
char buf[kGroupsMax * (kGroupIdMax + 1)];
|
||||||
|
size_t len = sizeof(buf);
|
||||||
|
if (nvs_get_str(h, "groups", buf, &len) == ESP_OK) {
|
||||||
|
s_ngroups = 0;
|
||||||
|
char *save = nullptr;
|
||||||
|
for (char *tok = strtok_r(buf, "\n", &save); tok && s_ngroups < kGroupsMax; tok = strtok_r(nullptr, "\n", &save)) {
|
||||||
|
snprintf(s_groups[s_ngroups], kGroupIdMax, "%s", tok);
|
||||||
|
s_ngroups++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ctrl_handle(const uint8_t mac[6], const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
(void)mac;
|
||||||
|
if (len < 1) return;
|
||||||
|
if (data[0] == '{') {
|
||||||
|
cJSON *raw = cJSON_ParseWithLength((const char *)data, len);
|
||||||
|
if (raw) {
|
||||||
|
cJSON *o = expand_v1(raw);
|
||||||
|
cJSON_Delete(raw);
|
||||||
|
if (json_for_me(o)) apply_v1(o);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(TAG, "bad JSON");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (len < 2 || data[0] != kMagic) return;
|
||||||
|
switch (data[1]) {
|
||||||
|
case kGroups:
|
||||||
|
set_groups(data, len);
|
||||||
|
break;
|
||||||
|
case kCmd:
|
||||||
|
handle_env(data + 2, len - 2); // a trailing save byte is ignored: settings are saved on every change
|
||||||
|
break;
|
||||||
|
case kGroupCmd: {
|
||||||
|
if (len < 3) return;
|
||||||
|
size_t gl = data[2];
|
||||||
|
if (len < 3 + gl) return;
|
||||||
|
char gid[kGroupIdMax];
|
||||||
|
cstr(gid, sizeof(gid), data + 3, gl);
|
||||||
|
if (!in_group(gid)) return;
|
||||||
|
size_t off = 3 + gl;
|
||||||
|
handle_env(data + off, len - off);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t ctrl_build_announce(uint8_t *out, size_t cap)
|
||||||
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
hw_cfg_t hw;
|
||||||
|
settings_load_hw(&hw);
|
||||||
|
size_t nl = strlen(n.hostname);
|
||||||
|
if (nl > 47) nl = 47;
|
||||||
|
static const char *orders[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" };
|
||||||
|
int co = 0;
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
if (strcmp(hw.order, orders[i]) == 0) co = i;
|
||||||
|
}
|
||||||
|
char cfg[160];
|
||||||
|
snprintf(cfg, sizeof(cfg),
|
||||||
|
"{\"max_brightness\":%u,\"num_leds\":%d,\"color_order\":\"%s\",\"startup_mode\":\"default\",\"reversed\":false}",
|
||||||
|
(unsigned)hw.max_brightness, hw.num_leds, hw.order);
|
||||||
|
size_t cl = strlen(cfg);
|
||||||
|
size_t need = 3 + nl + 6 + 1 + cl;
|
||||||
|
if (need > cap || need > 250) return 0;
|
||||||
|
size_t off = 0;
|
||||||
|
out[off++] = kMagic;
|
||||||
|
out[off++] = 0x01; // ANNOUNCE
|
||||||
|
out[off++] = (uint8_t)nl;
|
||||||
|
memcpy(out + off, n.hostname, nl);
|
||||||
|
off += nl;
|
||||||
|
out[off++] = hw.num_leds & 0xFF;
|
||||||
|
out[off++] = (hw.num_leds >> 8) & 0xFF;
|
||||||
|
out[off++] = (uint8_t)co;
|
||||||
|
out[off++] = 0; // startup mode: default
|
||||||
|
out[off++] = patterns_get_global();
|
||||||
|
out[off++] = 0; // device type: LED strip
|
||||||
|
out[off++] = (uint8_t)cl;
|
||||||
|
memcpy(out + off, cfg, cl);
|
||||||
|
off += cl;
|
||||||
|
return off;
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON *ctrl_groups_json(void)
|
||||||
|
{
|
||||||
|
cJSON *arr = cJSON_CreateArray();
|
||||||
|
for (size_t i = 0; i < s_ngroups; i++) {
|
||||||
|
cJSON_AddItemToArray(arr, cJSON_CreateString(s_groups[i]));
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Messages from led-controller over ESP-NOW: envelopes (0x4C CMD / GROUP_CMD, v2 and v3 binary), v1 JSON
|
||||||
|
* objects, and the group list. They are applied as the MicroPython driver applies them (controller_messages.py).
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
|
||||||
|
/** @brief Load the saved group list. Call once, after NVS is up. */
|
||||||
|
void ctrl_init(void);
|
||||||
|
|
||||||
|
/** @brief Handle one controller message from mac. Runs in the ESP-NOW link task. */
|
||||||
|
void ctrl_handle(const uint8_t mac[6], const uint8_t *data, size_t len);
|
||||||
|
|
||||||
|
/** @brief This driver's ANNOUNCE packet (boot hello, with its settings) into out. Returns its length. */
|
||||||
|
size_t ctrl_build_announce(uint8_t *out, size_t cap);
|
||||||
|
|
||||||
|
/** @brief The group ids this driver is in, as a new JSON array. The caller frees it. */
|
||||||
|
cJSON *ctrl_groups_json(void);
|
||||||
+146
@@ -0,0 +1,146 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "ddp.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
#include "lwip/sockets.h"
|
||||||
|
#include "patterns.h"
|
||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
static const char *TAG = "ddp";
|
||||||
|
|
||||||
|
static volatile bool s_enabled = true;
|
||||||
|
|
||||||
|
void ddp_set_enabled(bool on)
|
||||||
|
{
|
||||||
|
s_enabled = on;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Header: flags, sequence, data type, destination, data offset (4), data length (2); with the timecode
|
||||||
|
// flag, 4 more bytes follow. Version 1 is flags bits 6-7 = 01.
|
||||||
|
#define DDP_FLAG_VER1 0x40
|
||||||
|
#define DDP_VER_MASK 0xC0
|
||||||
|
#define DDP_FLAG_TIMECODE 0x10
|
||||||
|
#define DDP_HEADER 10
|
||||||
|
|
||||||
|
static uint32_t be32(const uint8_t *p)
|
||||||
|
{
|
||||||
|
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint16_t be16(const uint8_t *p)
|
||||||
|
{
|
||||||
|
return (uint16_t)((p[0] << 8) | p[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ddp_task(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
|
||||||
|
if (sock < 0) {
|
||||||
|
ESP_LOGE(TAG, "socket failed");
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
struct sockaddr_in addr = {};
|
||||||
|
addr.sin_family = AF_INET;
|
||||||
|
addr.sin_port = htons(DDP_PORT);
|
||||||
|
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||||
|
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
||||||
|
ESP_LOGE(TAG, "bind to port %d failed", DDP_PORT);
|
||||||
|
close(sock);
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "DDP listening on UDP port %d", DDP_PORT);
|
||||||
|
|
||||||
|
uint8_t buf[1500];
|
||||||
|
while (true) {
|
||||||
|
struct sockaddr_in src = {};
|
||||||
|
socklen_t srclen = sizeof(src);
|
||||||
|
int n = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&src, &srclen);
|
||||||
|
if (!s_enabled) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (n < DDP_HEADER) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
uint8_t flags = buf[0];
|
||||||
|
if ((flags & DDP_VER_MASK) != DDP_FLAG_VER1) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
size_t hdr = DDP_HEADER + ((flags & DDP_FLAG_TIMECODE) ? 4 : 0);
|
||||||
|
if ((size_t)n < hdr) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
uint8_t dtype = buf[2];
|
||||||
|
// 8-bit RGB: 0x00 (undefined, taken as RGB), 0x01 (the shorthand ddp_test sends) and 0x0B (RGB, 8 bits
|
||||||
|
// per channel, the DDP specification's code, which is what the controller sends)
|
||||||
|
if (dtype != 0x00 && dtype != 0x01 && dtype != 0x0B) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
uint32_t offset = be32(buf + 4);
|
||||||
|
size_t len = be16(buf + 8);
|
||||||
|
if (len > (size_t)n - hdr) {
|
||||||
|
len = (size_t)n - hdr;
|
||||||
|
}
|
||||||
|
bool push = (flags & 0x01) != 0;
|
||||||
|
patterns_ddp_write(offset, buf + hdr, len, push);
|
||||||
|
if (push) {
|
||||||
|
// Ack the completed frame to its sender ("LAK1" + the DDP seq). The sender broadcasts the
|
||||||
|
// sync only after this, so the frame is already held when the sync arrives.
|
||||||
|
uint8_t ack[5] = { 'L', 'A', 'K', '1', buf[1] };
|
||||||
|
sendto(sock, ack, sizeof(ack), 0, (struct sockaddr *)&src, srclen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sync broadcasts: a frame that arrived by DDP is shown when the next sync arrives (see patterns.cpp).
|
||||||
|
static void ddp_sync_task(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
|
||||||
|
if (sock < 0) {
|
||||||
|
ESP_LOGE(TAG, "sync socket failed");
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
struct sockaddr_in addr = {};
|
||||||
|
addr.sin_family = AF_INET;
|
||||||
|
addr.sin_port = htons(DDP_SYNC_PORT);
|
||||||
|
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||||
|
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
||||||
|
ESP_LOGE(TAG, "bind to sync port %d failed", DDP_SYNC_PORT);
|
||||||
|
close(sock);
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "sync listening on UDP port %d", DDP_SYNC_PORT);
|
||||||
|
|
||||||
|
uint8_t buf[64];
|
||||||
|
while (true) {
|
||||||
|
int n = recv(sock, buf, sizeof(buf), 0);
|
||||||
|
if (!s_enabled || n < 8 || memcmp(buf, "LSY1", 4) != 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
patterns_ddp_sync(be32(buf + 4));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t ddp_start(void)
|
||||||
|
{
|
||||||
|
net_cfg_t net;
|
||||||
|
if (settings_load_net(&net) == ESP_OK) {
|
||||||
|
s_enabled = net.ddp_enabled;
|
||||||
|
}
|
||||||
|
BaseType_t ok = xTaskCreate(ddp_task, "ddp", 4096, NULL, 4, NULL);
|
||||||
|
if (ok != pdPASS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
ok = xTaskCreate(ddp_sync_task, "ddp_sync", 3072, NULL, 4, NULL);
|
||||||
|
return ok == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* DDP (Distributed Display Protocol) receiver: RGB pixels over UDP, port 4048. Packets fill the strip
|
||||||
|
* while they keep arriving (see patterns.cpp).
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
#define DDP_PORT 4048
|
||||||
|
#define DDP_SYNC_PORT 4049 // UDP broadcast sync: "LSY1" + seq (u32, big endian)
|
||||||
|
|
||||||
|
/** @brief Start listening for DDP packets and sync broadcasts. Off if the saved setting is off. */
|
||||||
|
esp_err_t ddp_start(void);
|
||||||
|
|
||||||
|
/** @brief Turn DDP pixels and sync reception on or off. Packets are ignored while off. */
|
||||||
|
void ddp_set_enabled(bool on);
|
||||||
+151
@@ -0,0 +1,151 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Pattern engine shared by the effect files. Ports the MicroPython led-driver patterns: each pattern
|
||||||
|
* gets the same preset fields (colours, delay d, brightness b, auto a, reverse, n1..n6) and renders into
|
||||||
|
* a shadow frame, which patterns.cpp shows (with crossfade) on the strip.
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "patterns.h"
|
||||||
|
|
||||||
|
#define FX_LEDS_MAX 512 // largest strip the engine supports (per-LED buffers are sized at run time)
|
||||||
|
|
||||||
|
struct rgb {
|
||||||
|
int r, g, b;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Per-frame view handed to a pattern
|
||||||
|
struct fx_t {
|
||||||
|
int n; // LEDs in the strip
|
||||||
|
const preset_t *pr; // the running preset (copy)
|
||||||
|
uint32_t now; // ms now
|
||||||
|
uint32_t t; // ms since the pattern started
|
||||||
|
rgb *px; // shadow frame, physical order; persists between frames (n entries)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Per-pattern state. Patterns run one at a time, so one instance is reset on each select.
|
||||||
|
struct flake_t { int pos, ci, wj; };
|
||||||
|
struct star_t { int h, ci; };
|
||||||
|
struct spark_t { int p, lv, ci; };
|
||||||
|
struct bug_t { int pos, ph; };
|
||||||
|
struct drop_t { int pos, age; };
|
||||||
|
|
||||||
|
struct st_t {
|
||||||
|
bool done; // one-shot finished: hold the frame
|
||||||
|
bool started; // one-time setup done
|
||||||
|
uint32_t last, aux; // timers
|
||||||
|
uint32_t t0; // start time
|
||||||
|
int ci; // colour index
|
||||||
|
int phase, dir, pause; // animation state
|
||||||
|
int head, tail; // moving head / tail
|
||||||
|
int p1, p2; // comet heads
|
||||||
|
int cnt; // counters
|
||||||
|
int sc; // chase step count
|
||||||
|
int stage; // state machine stage
|
||||||
|
int flash_idx;
|
||||||
|
int rise; // flame
|
||||||
|
int cj[8]; // flame cluster jitter
|
||||||
|
uint32_t breath_origin, last_cluster, next_spark, spark_start;
|
||||||
|
int spark_dur;
|
||||||
|
bool spark_active;
|
||||||
|
int breath_ms, lo, hi, gap_lo, gap_hi;
|
||||||
|
bool sparks_on;
|
||||||
|
int centers[32];
|
||||||
|
int ncent;
|
||||||
|
int *glow; // per-LED buffers, n entries each (see frame_alloc)
|
||||||
|
flake_t flakes[64];
|
||||||
|
int nflakes;
|
||||||
|
star_t stars[8];
|
||||||
|
int nstars;
|
||||||
|
spark_t sparks[32];
|
||||||
|
int nsparks;
|
||||||
|
bug_t bugs[16];
|
||||||
|
int nbugs;
|
||||||
|
drop_t drops[32];
|
||||||
|
int ndrops;
|
||||||
|
uint8_t *on, *next_on;
|
||||||
|
int *col_i, *next_ci;
|
||||||
|
int *light, *dark;
|
||||||
|
int nlight, ndark;
|
||||||
|
float *m; // rig: position of each LED along the pattern
|
||||||
|
int *shade; // rig: shade of each LED
|
||||||
|
};
|
||||||
|
|
||||||
|
extern st_t g_st;
|
||||||
|
|
||||||
|
// Allocate the per-LED buffers for n LEDs (frame and pattern state). False if out of memory, in which
|
||||||
|
// case the old buffers are kept. Call with the pattern lock held.
|
||||||
|
bool frame_alloc(int n);
|
||||||
|
|
||||||
|
// Reset the pattern state for a new pattern, keeping the buffers and clearing them.
|
||||||
|
void st_reset(void);
|
||||||
|
|
||||||
|
// ---- helpers ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
int clampi(int v, int lo, int hi);
|
||||||
|
int fdiv(int a, int b); // floor division, as Python's //
|
||||||
|
int pmod(int a, int m); // non-negative modulo, as Python's %
|
||||||
|
int nz(int v, int def); // v when v > 0, else def
|
||||||
|
rgb mk(int r, int g, int b); // clamped
|
||||||
|
rgb ab(rgb c, int level); // c scaled by level/255
|
||||||
|
rgb mix(rgb a, rgb b, int k); // a -> b, k 0..255
|
||||||
|
int sgn(const fx_t &f, int v); // v unchanged; reverse is applied in led_at only
|
||||||
|
int led_at(const fx_t &f, int i); // logical index -> physical (mirrors when reverse)
|
||||||
|
void put(fx_t &f, int phys, rgb c);
|
||||||
|
void putl(fx_t &f, int logical, rgb c);
|
||||||
|
void fill(fx_t &f, rgb c);
|
||||||
|
bool due(uint32_t now, uint32_t &last, uint32_t d); // true (and last += d) once d ms have passed
|
||||||
|
uint32_t dur(const fx_t &f, int v); // ms, or quarter beats with beat_time
|
||||||
|
int get_colours(const fx_t &f, const rgb *def, int ndef, rgb *out); // preset colours or the default
|
||||||
|
int rnd(int lo, int hi); // random integer, inclusive
|
||||||
|
rgb grad_at(const rgb *cols, int ncols, float t); // colour at t (0..1) along the list
|
||||||
|
rgb wheel(int pos); // hue wheel, 0..255 -> colour
|
||||||
|
|
||||||
|
// Colour table for the rig patterns: shades of the colour list, at LEVELS brightness steps
|
||||||
|
#define RIG_SHADES 16
|
||||||
|
#define RIG_LEVELS 16
|
||||||
|
rgb rig_entry(const fx_t &f, const rgb *cols, int ncols, int shades, int shade, int level);
|
||||||
|
|
||||||
|
// Pattern entry points (return true once a one-shot has finished)
|
||||||
|
bool fx_off(fx_t &f, st_t &s);
|
||||||
|
bool fx_on(fx_t &f, st_t &s);
|
||||||
|
bool fx_blink(fx_t &f, st_t &s);
|
||||||
|
bool fx_aurora(fx_t &f, st_t &s);
|
||||||
|
bool fx_bar_graph(fx_t &f, st_t &s);
|
||||||
|
bool fx_blizzard(fx_t &f, st_t &s);
|
||||||
|
bool fx_candle_glow(fx_t &f, st_t &s);
|
||||||
|
bool fx_chase(fx_t &f, st_t &s);
|
||||||
|
bool fx_circle(fx_t &f, st_t &s);
|
||||||
|
bool fx_clock_sweep(fx_t &f, st_t &s);
|
||||||
|
bool fx_colour_cycle(fx_t &f, st_t &s);
|
||||||
|
bool fx_rainbow(fx_t &f, st_t &s);
|
||||||
|
bool fx_flicker(fx_t &f, st_t &s);
|
||||||
|
bool fx_gradient_wipe(fx_t &f, st_t &s);
|
||||||
|
bool fx_hit(fx_t &f, st_t &s);
|
||||||
|
bool fx_icicles(fx_t &f, st_t &s);
|
||||||
|
bool fx_keyframes(fx_t &f, st_t &s);
|
||||||
|
bool fx_orbit(fx_t &f, st_t &s);
|
||||||
|
bool fx_pulse(fx_t &f, st_t &s);
|
||||||
|
bool fx_transition(fx_t &f, st_t &s);
|
||||||
|
bool fx_wipe(fx_t &f, st_t &s);
|
||||||
|
bool fx_strobe_burst(fx_t &f, st_t &s);
|
||||||
|
bool fx_plasma(fx_t &f, st_t &s);
|
||||||
|
|
||||||
|
bool fx_meteor(fx_t &f, st_t &s);
|
||||||
|
bool fx_particles(fx_t &f, st_t &s);
|
||||||
|
bool fx_sparkle(fx_t &f, st_t &s);
|
||||||
|
bool fx_rain_drops(fx_t &f, st_t &s);
|
||||||
|
bool fx_rime(fx_t &f, st_t &s);
|
||||||
|
bool fx_twinkle(fx_t &f, st_t &s);
|
||||||
|
bool fx_radiate(fx_t &f, st_t &s);
|
||||||
|
bool fx_palette_morph(fx_t &f, st_t &s);
|
||||||
|
bool fx_flame(fx_t &f, st_t &s);
|
||||||
|
|
||||||
|
bool fx_field_wave(fx_t &f, st_t &s);
|
||||||
|
bool fx_grow(fx_t &f, st_t &s);
|
||||||
|
bool fx_ripple(fx_t &f, st_t &s);
|
||||||
|
bool fx_spin(fx_t &f, st_t &s);
|
||||||
|
bool fx_sweep(fx_t &f, st_t &s);
|
||||||
@@ -0,0 +1,948 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Basic and colour patterns, ported from the MicroPython led-driver (patterns folder).
|
||||||
|
*/
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdlib>
|
||||||
|
|
||||||
|
#include "effects.h"
|
||||||
|
|
||||||
|
static const rgb WHITE = { 255, 255, 255 };
|
||||||
|
static const rgb BLACK = { 0, 0, 0 };
|
||||||
|
|
||||||
|
static bool first_call(st_t &s)
|
||||||
|
{
|
||||||
|
if (s.started) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
s.started = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- off, on, blink ----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_off(fx_t &f, st_t &)
|
||||||
|
{
|
||||||
|
fill(f, BLACK);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_on(fx_t &f, st_t &)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
fill(f, ab(c[0], f.pr->brightness));
|
||||||
|
(void)nc;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_blink(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
s.stage = 1; // on
|
||||||
|
}
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (due(f.now, s.last, d)) {
|
||||||
|
if (s.stage) {
|
||||||
|
fill(f, ab(c[s.ci % nc], b));
|
||||||
|
s.ci++;
|
||||||
|
} else {
|
||||||
|
fill(f, bgc);
|
||||||
|
}
|
||||||
|
s.stage = !s.stage;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- aurora ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_aurora(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb bands_def[3] = { { 40, 200, 140 }, { 80, 120, 255 }, { 160, 80, 220 } };
|
||||||
|
const rgb north_def[3] = { { 20, 55, 120 }, { 60, 140, 220 }, { 180, 220, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS + 1];
|
||||||
|
bool northern = f.pr->n[6] == 1;
|
||||||
|
int nc = get_colours(f, northern ? north_def : bands_def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
|
||||||
|
if (!northern) {
|
||||||
|
int bands = nz(f.pr->n[1], 3);
|
||||||
|
int shimmer = clampi(nz(f.pr->n[2], 40), 0, 255);
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
int idx = (((i * bands) / (nled > 0 ? nled : 1)) + s.phase / 32) % nc;
|
||||||
|
rgb col = ab(c[idx], b);
|
||||||
|
int w = 255 - abs(128 - ((i * 8 + s.phase) & 255)) * 2;
|
||||||
|
w = clampi(w + shimmer, 0, 255);
|
||||||
|
rgb px = { col.r * w / 255, col.g * w / 255, col.b * w / 255 };
|
||||||
|
putl(f, i, px);
|
||||||
|
}
|
||||||
|
s.phase = pmod(s.phase + sgn(f, 1), 256);
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Northern wave: a sine of brightness along the strip, blended through the colours
|
||||||
|
int period = nz(f.pr->n[1], 20);
|
||||||
|
if (period < 4) period = 4;
|
||||||
|
int contrast = clampi(nz(f.pr->n[2], 200), 1, 255);
|
||||||
|
int drift = nz(f.pr->n[3], 2);
|
||||||
|
if (nc < 2) {
|
||||||
|
c[nc] = mk(120, 180, 255);
|
||||||
|
nc++;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
const float twopi = 6.2831853f;
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
float t = (i * twopi / period) + (s.phase * twopi / 256.0f);
|
||||||
|
float w = (sinf(t) + 1.0f) * 0.5f;
|
||||||
|
int u = (int)(w * (nc - 1) * 256.0f);
|
||||||
|
int fi = u >> 8;
|
||||||
|
int frac = u & 255;
|
||||||
|
if (fi >= nc - 1) {
|
||||||
|
fi = nc - 2;
|
||||||
|
frac = 255;
|
||||||
|
}
|
||||||
|
rgb peak = ab(mix(c[fi], c[fi + 1], frac), b);
|
||||||
|
int mixf = (int)(w * contrast * 2);
|
||||||
|
mixf = mixf >> 1;
|
||||||
|
if (mixf > 255) mixf = 255;
|
||||||
|
putl(f, i, mix(bgc, peak, mixf));
|
||||||
|
}
|
||||||
|
s.phase = pmod(s.phase + sgn(f, drift), 256);
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- bar graph ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_bar_graph(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[2] = { { 0, 255, 0 }, { 255, 80, 0 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 2, c);
|
||||||
|
(void)nc;
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int level = clampi(f.pr->n[1], 0, 100);
|
||||||
|
int target = (f.n * level) / 100;
|
||||||
|
rgb lit = ab(c[0], b);
|
||||||
|
rgb unlit = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
put(f, i, i < target ? lit : unlit);
|
||||||
|
}
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- blizzard ----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_blizzard(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[3] = { { 255, 255, 255 }, { 200, 230, 255 }, { 180, 210, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
int density = nz(f.pr->n[1], 90);
|
||||||
|
int speed = nz(f.pr->n[2], 2);
|
||||||
|
int wraw = f.pr->n[3];
|
||||||
|
int wind = wraw <= 0 ? 0 : clampi(fdiv(wraw - 128, 20), -4, 4);
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
if (rnd(0, 255) < density && s.nflakes < 64) {
|
||||||
|
flake_t fl = { nled - 1, rnd(0, nc - 1), wind == 0 ? 0 : rnd(-1, 1) };
|
||||||
|
s.flakes[s.nflakes++] = fl;
|
||||||
|
}
|
||||||
|
int keep = 0;
|
||||||
|
for (int k = 0; k < s.nflakes; k++) {
|
||||||
|
flake_t fl = s.flakes[k];
|
||||||
|
int p = fl.pos;
|
||||||
|
int lateral = wind + fl.wj;
|
||||||
|
p -= sgn(f, speed);
|
||||||
|
p += sgn(f, lateral);
|
||||||
|
if (p < -2 || p >= nled + 2) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int pi = clampi(p, 0, nled - 1);
|
||||||
|
putl(f, pi, ab(c[fl.ci], b));
|
||||||
|
s.flakes[keep] = { p, fl.ci, fl.wj };
|
||||||
|
keep++;
|
||||||
|
}
|
||||||
|
s.nflakes = keep;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- candle glow -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_candle_glow(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[3] = { { 255, 140, 40 }, { 255, 200, 120 }, { 255, 90, 20 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
if (first_call(s)) {
|
||||||
|
int nc_candles = clampi(nz(f.pr->n[1], 4), 1, nled);
|
||||||
|
if (nc_candles > 32) nc_candles = 32;
|
||||||
|
s.ncent = nc_candles;
|
||||||
|
for (int k = 0; k < nc_candles; k++) {
|
||||||
|
s.centers[k] = rnd(0, nled > 0 ? nled - 1 : 0);
|
||||||
|
}
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
int width = nz(f.pr->n[2], 3);
|
||||||
|
int flicker = clampi(nz(f.pr->n[3], 90), 1, 255);
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
int base_lo = 180 - flicker / 2;
|
||||||
|
if (base_lo < 40) base_lo = 40;
|
||||||
|
for (int ci = 0; ci < s.ncent; ci++) {
|
||||||
|
int centre = s.centers[ci];
|
||||||
|
rgb warmth = c[ci % nc];
|
||||||
|
int pulse = clampi(base_lo + rnd(0, flicker), 0, 255);
|
||||||
|
for (int off = -width; off <= width; off++) {
|
||||||
|
int idx = centre + off;
|
||||||
|
if (idx < 0 || idx >= nled) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int dist = abs(off);
|
||||||
|
int fall = ((width - dist + 1) * 256) / (width + 1);
|
||||||
|
int fac = (fall * pulse) / 256;
|
||||||
|
rgb px = { warmth.r * fac / 255, warmth.g * fac / 255, warmth.b * fac / 255 };
|
||||||
|
rgb lit = ab(px, b);
|
||||||
|
rgb o = f.px[idx];
|
||||||
|
f.px[idx] = { o.r > lit.r ? o.r : lit.r, o.g > lit.g ? o.g : lit.g, o.b > lit.b ? o.b : lit.b };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- chase -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
static void chase_draw(fx_t &f, int pos, int n1, int n2, int n3, int n4, rgb c0, rgb c1)
|
||||||
|
{
|
||||||
|
int seg = n1 + n2;
|
||||||
|
(void)n3;
|
||||||
|
(void)n4;
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
int rel = pmod(i - pos, seg);
|
||||||
|
putl(f, i, rel < n1 ? c0 : c1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_chase(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
if (f.pr->n[6] == 1) {
|
||||||
|
// Marquee: dashes that scroll
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
(void)nc;
|
||||||
|
int on_len = nz(f.pr->n[1], 3);
|
||||||
|
int off_len = nz(f.pr->n[2], 2);
|
||||||
|
int step = f.pr->n[3] == 0 ? 1 : f.pr->n[3]; // negative steps walk the other way
|
||||||
|
int period = on_len + off_len;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb col = ab(c[0], b);
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
int m = pmod(i + s.phase, period);
|
||||||
|
putl(f, i, m < on_len ? col : bgc);
|
||||||
|
}
|
||||||
|
s.phase = pmod(s.phase + step, period);
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chase: two colours moving along the strip, n1/n2 segment lengths, n3/n4 steps
|
||||||
|
const rgb def[2] = { WHITE, WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 2, c);
|
||||||
|
rgb color0 = ab(c[0], b);
|
||||||
|
rgb color1 = ab(nc > 1 ? c[1] : c[0], b);
|
||||||
|
int n1 = nz(f.pr->n[1], 1);
|
||||||
|
int n2 = nz(f.pr->n[2], 1);
|
||||||
|
// Steps may be negative: a negative n3/n4 walks the dot the other way. 0 (unset) means 1.
|
||||||
|
int n3 = f.pr->n[3] == 0 ? 1 : f.pr->n[3];
|
||||||
|
int n4 = f.pr->n[4] == 0 ? 1 : f.pr->n[4];
|
||||||
|
int seg = n1 + n2;
|
||||||
|
int max_pos = nled + seg;
|
||||||
|
auto position = [&](int sc) {
|
||||||
|
int pos;
|
||||||
|
if (sc % 2 == 0) {
|
||||||
|
pos = (sc / 2) * (n3 + n4) + n3;
|
||||||
|
} else {
|
||||||
|
pos = ((sc + 1) / 2) * (n3 + n4);
|
||||||
|
}
|
||||||
|
return pmod(pos, max_pos);
|
||||||
|
};
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
|
||||||
|
s.sc = (s.sc + 1) % (2 * max_pos); // the dot walks the whole cycle; even modulus keeps the parity
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uint32_t dur_ms = f.pr->delay < 10 ? 10 : f.pr->delay;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now - dur_ms; // the first step is immediate
|
||||||
|
}
|
||||||
|
if ((int32_t)(f.now - s.last) >= (int32_t)dur_ms) {
|
||||||
|
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
|
||||||
|
s.sc = (s.sc + 1) % (2 * max_pos); // the dot walks the whole cycle; even modulus keeps the parity
|
||||||
|
s.last += dur_ms;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- circle ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_circle(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
rgb color0, color1;
|
||||||
|
if (f.pr->ncol == 0) {
|
||||||
|
color0 = color1 = ab(WHITE, b);
|
||||||
|
} else {
|
||||||
|
color0 = ab(mk(f.pr->col[0][0], f.pr->col[0][1], f.pr->col[0][2]), b);
|
||||||
|
color1 = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
}
|
||||||
|
int nled = f.n;
|
||||||
|
int head_rate = nz(f.pr->n[1], 1);
|
||||||
|
int max_length = nz(f.pr->n[2], 1);
|
||||||
|
int tail_rate = nz(f.pr->n[3], 1);
|
||||||
|
int min_length = f.pr->n[4] > 0 ? f.pr->n[4] : 0;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.aux = f.now; // head timer
|
||||||
|
s.last = f.now; // tail timer
|
||||||
|
s.phase = 0; // 0 growing, 1 shrinking, 2 off
|
||||||
|
}
|
||||||
|
// Draw the ring: background, then the segment from the tail to the head
|
||||||
|
int seg = pmod(s.head - s.tail, nled);
|
||||||
|
if (seg == 0 && s.head != s.tail) {
|
||||||
|
seg = nled;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
put(f, i, color1);
|
||||||
|
}
|
||||||
|
for (int i = 0; i <= seg; i++) {
|
||||||
|
put(f, (s.tail + i) % nled, color0);
|
||||||
|
}
|
||||||
|
// Head moves at n1 LEDs per second
|
||||||
|
uint32_t head_delay = 1000u / (uint32_t)head_rate;
|
||||||
|
if ((int32_t)(f.now - s.aux) >= (int32_t)head_delay) {
|
||||||
|
s.aux += head_delay;
|
||||||
|
s.head = (s.head + 1) % nled;
|
||||||
|
}
|
||||||
|
// Tail behaviour by phase
|
||||||
|
if (s.phase == 0) {
|
||||||
|
if (seg >= max_length) {
|
||||||
|
s.phase = 1;
|
||||||
|
}
|
||||||
|
} else if (s.phase == 1) {
|
||||||
|
uint32_t tail_delay = 1000u / (uint32_t)tail_rate;
|
||||||
|
if ((int32_t)(f.now - s.last) >= (int32_t)tail_delay) {
|
||||||
|
s.last += tail_delay;
|
||||||
|
s.tail = (s.tail + 1) % nled;
|
||||||
|
int cur = pmod(s.head - s.tail, nled);
|
||||||
|
if (cur == 0 && s.head != s.tail) {
|
||||||
|
cur = nled;
|
||||||
|
}
|
||||||
|
if (min_length == 0 && cur <= 1) {
|
||||||
|
s.phase = 2;
|
||||||
|
} else if (min_length > 0 && cur <= min_length) {
|
||||||
|
s.phase = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
s.tail = s.head;
|
||||||
|
s.phase = 0;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- clock sweep -------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_clock_sweep(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[2] = { WHITE, { 60, 60, 60 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
get_colours(f, def, 2, c);
|
||||||
|
int width = nz(f.pr->n[1], 1);
|
||||||
|
int marker = f.pr->n[2] > 0 ? f.pr->n[2] : 0;
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
rgb fg = ab(c[0], b);
|
||||||
|
rgb dim = { bgc.r * 2 / 3, bgc.g * 2 / 3, bgc.b * 2 / 3 };
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
if (marker > 0 && i % marker == 0) {
|
||||||
|
put(f, i, dim);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int w = 0; w < width; w++) {
|
||||||
|
put(f, (s.phase + w) % f.n, fg);
|
||||||
|
}
|
||||||
|
s.phase = (s.phase + 1) % (f.n > 0 ? f.n : 1);
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- colour cycle ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
static void gradient_render(fx_t &f, const rgb *cols, int nc, int phase)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
if (nc == 1) {
|
||||||
|
fill(f, ab(cols[0], b));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int full_span = nc * 256;
|
||||||
|
int phase_shift = (phase * full_span) / 256;
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
int pos = (((i * full_span) / nled) + phase_shift) % full_span;
|
||||||
|
int idx = pos / 256;
|
||||||
|
int frac = pos & 255;
|
||||||
|
rgb c1 = cols[idx];
|
||||||
|
rgb c2 = cols[(idx + 1) % nc];
|
||||||
|
rgb blended = mix(c1, c2, frac);
|
||||||
|
putl(f, i, ab(blended, b));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void rainbow_render(fx_t &f, int phase)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
int rc = (i * 256) / (nled > 0 ? nled : 1) + phase;
|
||||||
|
putl(f, i, ab(wheel(rc & 255), b));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_colour_cycle(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
int step_amount = nz(f.pr->n[1], 1);
|
||||||
|
if (f.pr->n[6] == 1) {
|
||||||
|
// Fixed spectrum wheel, scrolling
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
rainbow_render(f, s.phase);
|
||||||
|
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rainbow_render(f, s.phase);
|
||||||
|
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const rgb def[2] = { { 255, 0, 0 }, { 0, 0, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 2, c);
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
gradient_render(f, c, nc, s.phase);
|
||||||
|
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
gradient_render(f, c, nc, s.phase);
|
||||||
|
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rainbow: the spectrum wheel scrolling at n1 steps per frame (the controller's "rainbow" pattern)
|
||||||
|
bool fx_rainbow(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
int step_amount = nz(f.pr->n[1], 1);
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
rainbow_render(f, s.phase);
|
||||||
|
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rainbow_render(f, s.phase);
|
||||||
|
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- flicker -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_flicker(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
int lo = clampi(f.pr->n[1], 0, 255);
|
||||||
|
int hi = clampi(f.pr->brightness, 0, 255);
|
||||||
|
if (lo > hi) {
|
||||||
|
int t = lo;
|
||||||
|
lo = hi;
|
||||||
|
hi = t;
|
||||||
|
}
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
int level = rnd(lo, hi);
|
||||||
|
fill(f, ab(c[s.ci % nc], level));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int level = rnd(lo, hi);
|
||||||
|
fill(f, ab(c[s.ci % nc], level));
|
||||||
|
s.ci++;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- gradient wipe (always one-shot) -----------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_gradient_wipe(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
rgb c1 = c[0];
|
||||||
|
rgb c2 = nc > 1 ? c[1] : c[0];
|
||||||
|
int last = f.n > 0 ? f.n - 1 : 0;
|
||||||
|
int n1 = clampi(f.pr->n[1], 0, last);
|
||||||
|
int n2 = clampi(f.pr->n[2], 0, last);
|
||||||
|
int count = abs(n2 - n1) + 1;
|
||||||
|
int step = n2 >= n1 ? 1 : -1;
|
||||||
|
uint32_t duration = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (first_call(s)) {
|
||||||
|
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
|
||||||
|
}
|
||||||
|
if (s.cnt >= count) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
int lit = (int)((f.t * (uint32_t)count) / duration) + 1;
|
||||||
|
if (lit > count) {
|
||||||
|
lit = count;
|
||||||
|
}
|
||||||
|
for (int k = s.cnt; k < lit; k++) {
|
||||||
|
rgb col;
|
||||||
|
if (count == 1) {
|
||||||
|
col = c1;
|
||||||
|
} else {
|
||||||
|
float t = (float)k / (count - 1);
|
||||||
|
col = { (int)(c1.r + (c2.r - c1.r) * t), (int)(c1.g + (c2.g - c1.g) * t),
|
||||||
|
(int)(c1.b + (c2.b - c1.b) * t) };
|
||||||
|
}
|
||||||
|
putl(f, n1 + k * step, ab(col, b));
|
||||||
|
}
|
||||||
|
if (lit > s.cnt) {
|
||||||
|
s.cnt = lit;
|
||||||
|
}
|
||||||
|
return s.cnt >= count;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- hit ---------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_hit(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.aux = f.now;
|
||||||
|
}
|
||||||
|
for (int guard = 0; guard < 2; guard++) {
|
||||||
|
int attack = (int)dur(f, f.pr->n[1]);
|
||||||
|
int hold = (int)dur(f, f.pr->n[2]);
|
||||||
|
int decay = (int)dur(f, f.pr->n[3]);
|
||||||
|
int gap = f.pr->autorun ? (int)dur(f, (int)f.pr->delay) : 0;
|
||||||
|
rgb base = c[s.ci % nc];
|
||||||
|
int t = (int)(f.now - s.aux);
|
||||||
|
if (t < attack) {
|
||||||
|
rgb sc = { base.r * t / attack, base.g * t / attack, base.b * t / attack };
|
||||||
|
fill(f, ab(sc, b));
|
||||||
|
} else if (t < attack + hold) {
|
||||||
|
fill(f, ab(base, b));
|
||||||
|
} else if (t < attack + hold + decay) {
|
||||||
|
int left = decay - (t - attack - hold);
|
||||||
|
rgb sc = { base.r * left / decay, base.g * left / decay, base.b * left / decay };
|
||||||
|
rgb v = ab(sc, b);
|
||||||
|
rgb m = { v.r > bgc.r ? v.r : bgc.r, v.g > bgc.g ? v.g : bgc.g, v.b > bgc.b ? v.b : bgc.b };
|
||||||
|
fill(f, m);
|
||||||
|
} else if (!f.pr->autorun) {
|
||||||
|
fill(f, f.pr->n[4] == 1 ? ab(base, b) : bgc);
|
||||||
|
return true;
|
||||||
|
} else if (t < attack + hold + decay + gap) {
|
||||||
|
fill(f, bgc);
|
||||||
|
} else {
|
||||||
|
s.ci = (s.ci + 1) % nc;
|
||||||
|
s.aux = f.now;
|
||||||
|
continue; // the next flash starts on this frame
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- icicles -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_icicles(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[3] = { { 240, 248, 255 }, { 160, 210, 255 }, { 255, 255, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
int spacing = nz(f.pr->n[1], 12);
|
||||||
|
int cap = nled / 4;
|
||||||
|
if (cap > 14) cap = 14;
|
||||||
|
if (cap < 3) cap = 3;
|
||||||
|
int max_len = nz(f.pr->n[2], cap);
|
||||||
|
if (max_len < 2) max_len = 2;
|
||||||
|
if (max_len > (nled > 2 ? nled : 2)) max_len = nled > 2 ? nled : 2;
|
||||||
|
int span = max_len * 2;
|
||||||
|
int phase_step = nz(f.pr->n[3], 1);
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
int aidx = 0;
|
||||||
|
for (int anchor = 0; anchor < nled; anchor += spacing) {
|
||||||
|
int tri_i = pmod(s.phase + aidx * 5, span);
|
||||||
|
int ic_len = tri_i <= max_len ? tri_i : span - tri_i;
|
||||||
|
rgb tip = ab(c[aidx % nc], b);
|
||||||
|
for (int k = 0; k < ic_len; k++) {
|
||||||
|
int idx = anchor + k;
|
||||||
|
if (idx >= nled) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
int br = ((k + 1) * 255) / (ic_len > 1 ? ic_len : 1);
|
||||||
|
rgb px = { (tip.r * br + bgc.r * (255 - br)) / 255, (tip.g * br + bgc.g * (255 - br)) / 255,
|
||||||
|
(tip.b * br + bgc.b * (255 - br)) / 255 };
|
||||||
|
putl(f, idx, px);
|
||||||
|
}
|
||||||
|
aidx++;
|
||||||
|
}
|
||||||
|
s.phase = pmod(s.phase + sgn(f, phase_step), span);
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- keyframes ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
static float ease_t(float t, int mode)
|
||||||
|
{
|
||||||
|
if (t <= 0) return 0;
|
||||||
|
if (t >= 1) return 1;
|
||||||
|
switch (mode) {
|
||||||
|
case 1: return t * t * (3 - 2 * t); // in-out
|
||||||
|
case 2: return 0; // step
|
||||||
|
case 3: return t * t; // in
|
||||||
|
case 4: return 1 - (1 - t) * (1 - t); // out
|
||||||
|
default: return t; // linear
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_keyframes(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
(void)s;
|
||||||
|
int total = (int)dur(f, (int)f.pr->delay);
|
||||||
|
if (total < 1) total = 1;
|
||||||
|
bool loop = f.pr->autorun;
|
||||||
|
int segs = loop ? nc : (nc - 1 > 1 ? nc - 1 : 1);
|
||||||
|
int t = (int)f.t;
|
||||||
|
if (!loop && t >= total) {
|
||||||
|
if (f.pr->n[2] == 1) {
|
||||||
|
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
|
||||||
|
} else if (f.pr->n[2] == 2) {
|
||||||
|
fill(f, BLACK);
|
||||||
|
} else {
|
||||||
|
fill(f, ab(c[nc - 1], b));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
float x = ((float)(t % total) / total) * segs;
|
||||||
|
int i = (int)x;
|
||||||
|
rgb a = c[i % nc];
|
||||||
|
rgb bb = c[(i + 1) % nc];
|
||||||
|
float k = ease_t(x - i, f.pr->n[1]);
|
||||||
|
rgb m = { (int)(a.r + (bb.r - a.r) * k), (int)(a.g + (bb.g - a.g) * k), (int)(a.b + (bb.b - a.b) * k) };
|
||||||
|
fill(f, ab(m, b));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- orbit -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_orbit(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[3] = { WHITE, { 0, 180, 255 }, { 255, 0, 120 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
int orbits = nz(f.pr->n[1], 3);
|
||||||
|
int speed = nz(f.pr->n[2], 1);
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
for (int k = 0; k < orbits; k++) {
|
||||||
|
int idx = ((s.phase * (k + 1)) / 8 + (k * nled) / orbits) % (nled > 0 ? nled : 1);
|
||||||
|
put(f, idx, ab(c[k % nc], b));
|
||||||
|
}
|
||||||
|
s.phase = (s.phase + speed) & 255;
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- pulse -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_pulse(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
bool manual = !f.pr->autorun;
|
||||||
|
if (first_call(s)) {
|
||||||
|
fill(f, bgc);
|
||||||
|
s.aux = f.now; // cycle start
|
||||||
|
}
|
||||||
|
int attack = nz(f.pr->n[1], 0);
|
||||||
|
int hold = nz(f.pr->n[2], 0);
|
||||||
|
int decay = nz(f.pr->n[3], 0);
|
||||||
|
int delay = manual ? 0 : (int)f.pr->delay;
|
||||||
|
int total = attack + hold + decay + delay;
|
||||||
|
if (total <= 0) total = 1;
|
||||||
|
int elapsed = (int)(f.now - s.aux);
|
||||||
|
rgb base = c[s.ci % nc];
|
||||||
|
if (elapsed < attack && attack > 0) {
|
||||||
|
rgb col = { (int)(base.r * ((float)elapsed / attack)), (int)(base.g * ((float)elapsed / attack)),
|
||||||
|
(int)(base.b * ((float)elapsed / attack)) };
|
||||||
|
fill(f, ab(col, b));
|
||||||
|
} else if (elapsed < attack + hold) {
|
||||||
|
fill(f, ab(base, b));
|
||||||
|
} else if (elapsed < attack + hold + decay && decay > 0) {
|
||||||
|
float fac = 1.0f - (float)(elapsed - attack - hold) / decay;
|
||||||
|
if (fac < 0) fac = 0;
|
||||||
|
rgb col = { (int)(base.r * fac), (int)(base.g * fac), (int)(base.b * fac) };
|
||||||
|
fill(f, ab(col, b));
|
||||||
|
} else if (elapsed < total) {
|
||||||
|
fill(f, bgc);
|
||||||
|
} else {
|
||||||
|
int nclr = nc > 1 ? nc : 1;
|
||||||
|
s.ci = (s.ci + 1) % nclr;
|
||||||
|
if (manual) {
|
||||||
|
fill(f, bgc);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
s.aux = f.now;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- transition --------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Wipe: the next colour sweeps in from the first LED to the last over `delay` ms, then becomes the
|
||||||
|
// current colour and the one after it starts wiping in.
|
||||||
|
bool fx_wipe(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
if (nc == 1) {
|
||||||
|
fill(f, ab(c[0], b));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.aux = f.now;
|
||||||
|
}
|
||||||
|
int duration = f.pr->delay < 10 ? 10 : (int)f.pr->delay;
|
||||||
|
int elapsed = (int)(f.now - s.aux);
|
||||||
|
if (elapsed >= duration) {
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
fill(f, ab(c[(s.ci + 1) % nc], b));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
s.ci = (s.ci + 1) % nc;
|
||||||
|
s.aux = f.now;
|
||||||
|
elapsed = 0;
|
||||||
|
}
|
||||||
|
rgb cur = c[s.ci % nc];
|
||||||
|
rgb nxt = c[(s.ci + 1) % nc];
|
||||||
|
int front = (elapsed * f.n) / duration; // LEDs already showing the next colour
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
putl(f, i, ab(i < front ? nxt : cur, b));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transition: the whole bar shows one colour, which fades from each colour to the next over `delay` ms.
|
||||||
|
bool fx_transition(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
if (nc == 1) {
|
||||||
|
fill(f, ab(c[0], b));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.aux = f.now;
|
||||||
|
}
|
||||||
|
int duration = f.pr->delay < 10 ? 10 : (int)f.pr->delay;
|
||||||
|
int elapsed = (int)(f.now - s.aux);
|
||||||
|
if (elapsed >= duration) {
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
fill(f, ab(c[(s.ci + 1) % nc], b));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
s.ci = (s.ci + 1) % nc;
|
||||||
|
s.aux = f.now;
|
||||||
|
elapsed = 0;
|
||||||
|
}
|
||||||
|
rgb cur = c[s.ci % nc];
|
||||||
|
rgb nxt = c[(s.ci + 1) % nc];
|
||||||
|
int k = (elapsed * 255) / duration; // 0 = all current colour, 255 = all next colour
|
||||||
|
fill(f, ab(mix(cur, nxt, k), b));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- strobe burst ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_strobe_burst(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
(void)nc;
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.stage = 0; // 0 flash on, 1 flash off, 2 cooldown
|
||||||
|
s.flash_idx = 0;
|
||||||
|
s.aux = f.now; // state start
|
||||||
|
}
|
||||||
|
int count = nz(f.pr->n[1], 3);
|
||||||
|
int gap = nz(f.pr->n[2], 60);
|
||||||
|
int cooldown = nz(f.pr->n[3], 400);
|
||||||
|
int on_ms = (int)f.pr->delay / 2;
|
||||||
|
if (on_ms < 1) on_ms = 1;
|
||||||
|
rgb col = ab(c[0], b);
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
int since = (int)(f.now - s.aux);
|
||||||
|
if (s.stage == 0) {
|
||||||
|
fill(f, col);
|
||||||
|
if (since >= on_ms) {
|
||||||
|
s.stage = 1;
|
||||||
|
s.aux += on_ms;
|
||||||
|
}
|
||||||
|
} else if (s.stage == 1) {
|
||||||
|
fill(f, bgc);
|
||||||
|
if (since >= gap) {
|
||||||
|
s.flash_idx++;
|
||||||
|
if (s.flash_idx >= count) {
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
s.stage = 2;
|
||||||
|
s.flash_idx = 0;
|
||||||
|
s.aux += gap;
|
||||||
|
} else {
|
||||||
|
s.stage = 0;
|
||||||
|
s.aux += gap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fill(f, bgc);
|
||||||
|
if (since >= cooldown) {
|
||||||
|
s.stage = 0;
|
||||||
|
s.aux += cooldown;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- plasma ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_plasma(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
int scale = nz(f.pr->n[1], 6);
|
||||||
|
int speed = nz(f.pr->n[2], 2);
|
||||||
|
int contrast = nz(f.pr->n[3], 2);
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int t = s.phase;
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
int v = (i * scale + t) & 255;
|
||||||
|
int v2 = ((i * scale) / contrast - t * 2) & 255;
|
||||||
|
put(f, i, ab(wheel((v + v2) & 255), b));
|
||||||
|
}
|
||||||
|
s.phase = pmod(s.phase + speed, 256);
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
@@ -0,0 +1,896 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Moving lights, particles and sparkles, ported from the MicroPython led-driver (patterns folder).
|
||||||
|
*/
|
||||||
|
#include <cstdlib>
|
||||||
|
|
||||||
|
#include "effects.h"
|
||||||
|
|
||||||
|
static const rgb WHITE = { 255, 255, 255 };
|
||||||
|
|
||||||
|
static bool first_call(st_t &s)
|
||||||
|
{
|
||||||
|
if (s.started) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
s.started = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t period_of(const fx_t &f)
|
||||||
|
{
|
||||||
|
return f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fade every LED's stored colour towards black (the shadow frame persists between frames)
|
||||||
|
static void fade_frame(fx_t &f, int amount)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
rgb c = f.px[i];
|
||||||
|
f.px[i] = { c.r * amount / 255, c.g * amount / 255, c.b * amount / 255 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- meteor / comet / scanner ------------------------------------------------------------------
|
||||||
|
|
||||||
|
static bool meteor_run(fx_t &f, st_t &s, const rgb *cols, int nc)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int tail = nz(f.pr->n[1], 8);
|
||||||
|
int speed = nz(f.pr->n[2], 1);
|
||||||
|
int fade_amount = clampi(nz(f.pr->n[3], 192), 1, 255);
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
s.dir = f.pr->reverse ? -1 : 1;
|
||||||
|
s.head = f.pr->reverse ? (f.n > 0 ? f.n - 1 : 0) : 0;
|
||||||
|
s.ci = 0;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
fade_frame(f, fade_amount);
|
||||||
|
rgb lit = ab(cols[s.ci % nc], b);
|
||||||
|
if (s.head >= 0 && s.head < f.n) {
|
||||||
|
putl(f, s.head, lit);
|
||||||
|
}
|
||||||
|
s.head += sgn(f, s.dir * speed);
|
||||||
|
if (s.head >= f.n + tail) {
|
||||||
|
s.head = f.n - 1;
|
||||||
|
s.dir = -1;
|
||||||
|
s.ci++;
|
||||||
|
} else if (s.head < -tail) {
|
||||||
|
s.head = 0;
|
||||||
|
s.dir = 1;
|
||||||
|
s.ci++;
|
||||||
|
}
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool comet_run(fx_t &f, st_t &s, const rgb *cols, int nc)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
int tail = nz(f.pr->n[1], 6);
|
||||||
|
int speed = nz(f.pr->n[2], 1);
|
||||||
|
int gap = f.pr->n[3] > 0 ? f.pr->n[3] : 0;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
if (f.pr->reverse) {
|
||||||
|
s.p1 = nled - 1;
|
||||||
|
s.p2 = gap;
|
||||||
|
} else {
|
||||||
|
s.p1 = 0;
|
||||||
|
s.p2 = nled - 1 - gap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
rgb c1 = ab(cols[0], b);
|
||||||
|
rgb c2 = ab(nc > 1 ? cols[1] : cols[0], b);
|
||||||
|
int denom = tail > 1 ? tail : 1;
|
||||||
|
for (int t = 0; t < tail; t++) {
|
||||||
|
int i1 = s.p1 - t;
|
||||||
|
if (i1 >= 0 && i1 < nled) {
|
||||||
|
int k = (255 * (tail - t)) / denom;
|
||||||
|
putl(f, i1, { c1.r * k / 255, c1.g * k / 255, c1.b * k / 255 });
|
||||||
|
}
|
||||||
|
int i2 = s.p2 + t;
|
||||||
|
if (i2 >= 0 && i2 < nled) {
|
||||||
|
int k = (255 * (tail - t)) / denom;
|
||||||
|
putl(f, i2, { c2.r * k / 255, c2.g * k / 255, c2.b * k / 255 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.p1 += sgn(f, speed);
|
||||||
|
s.p2 -= sgn(f, speed);
|
||||||
|
if (s.p1 - tail > nled && s.p2 + tail < 0) {
|
||||||
|
s.p1 = 0;
|
||||||
|
s.p2 = nled - 1 - gap;
|
||||||
|
}
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool scanner_run(fx_t &f, st_t &s, const rgb *cols, int nc)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int nled = f.n;
|
||||||
|
int width = nz(f.pr->n[1], 4);
|
||||||
|
int end_pause = f.pr->n[2] > 0 ? f.pr->n[2] : 0;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
s.ci = 0;
|
||||||
|
s.pause = 0;
|
||||||
|
s.dir = f.pr->reverse ? -1 : 1;
|
||||||
|
s.head = f.pr->reverse ? (nled > 0 ? nled - 1 : 0) : 0; // centre
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb base = ab(cols[s.ci % nc], b);
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
int denom = width > 1 ? width : 1;
|
||||||
|
for (int i = 0; i < nled; i++) {
|
||||||
|
int dist = abs(i - s.head);
|
||||||
|
if (dist > width) {
|
||||||
|
putl(f, i, bgc);
|
||||||
|
} else {
|
||||||
|
int sc = ((width - dist) * 255) / denom;
|
||||||
|
putl(f, i, { base.r * sc / 255, base.g * sc / 255, base.b * sc / 255 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s.pause > 0) {
|
||||||
|
s.pause--;
|
||||||
|
} else {
|
||||||
|
s.head += sgn(f, s.dir);
|
||||||
|
if (s.head >= nled - 1) {
|
||||||
|
s.head = nled - 1;
|
||||||
|
s.dir = -1;
|
||||||
|
s.pause = end_pause;
|
||||||
|
s.ci++;
|
||||||
|
} else if (s.head <= 0) {
|
||||||
|
s.head = 0;
|
||||||
|
s.dir = 1;
|
||||||
|
s.pause = end_pause;
|
||||||
|
s.ci++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_meteor(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
switch (f.pr->n[6]) {
|
||||||
|
case 1:
|
||||||
|
return comet_run(f, s, c, nc);
|
||||||
|
case 2:
|
||||||
|
return scanner_run(f, s, c, nc);
|
||||||
|
default:
|
||||||
|
return meteor_run(f, s, c, nc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- particles: snowfall and starfall ----------------------------------------------------------
|
||||||
|
|
||||||
|
static bool snow_run(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[2] = { WHITE, { 180, 220, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 2, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int density = nz(f.pr->n[1], 20);
|
||||||
|
int speed = abs(sgn(f, nz(f.pr->n[2], 1)));
|
||||||
|
if (speed < 1) speed = 1;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (rnd(0, 255) < density && s.nflakes < 64) {
|
||||||
|
s.flakes[s.nflakes++] = { f.n - 1, rnd(0, nc - 1), 0 };
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
int keep = 0;
|
||||||
|
for (int k = 0; k < s.nflakes; k++) {
|
||||||
|
flake_t fl = s.flakes[k];
|
||||||
|
if (fl.pos >= 0 && fl.pos < f.n) {
|
||||||
|
putl(f, fl.pos, ab(c[fl.ci], b));
|
||||||
|
}
|
||||||
|
fl.pos -= sgn(f, speed);
|
||||||
|
if (fl.pos >= -1) {
|
||||||
|
s.flakes[keep++] = fl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.nflakes = keep;
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool starfall_run(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[3] = { WHITE, { 200, 230, 255 }, { 255, 248, 220 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int rate = clampi(nz(f.pr->n[1], 14), 1, 255);
|
||||||
|
int speed = abs(sgn(f, nz(f.pr->n[2], 2)));
|
||||||
|
if (speed < 1) speed = 1;
|
||||||
|
int tail = nz(f.pr->n[3], 10);
|
||||||
|
if (tail < 2) tail = 2;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
if (s.nstars < 4 && rnd(0, 255) < rate) {
|
||||||
|
int extra = f.n / 2;
|
||||||
|
if (extra > 8) extra = 8;
|
||||||
|
int top = f.n - 1 + rnd(0, extra);
|
||||||
|
s.stars[s.nstars++] = { top, rnd(0, nc - 1) };
|
||||||
|
}
|
||||||
|
int keep = 0;
|
||||||
|
for (int k = 0; k < s.nstars; k++) {
|
||||||
|
star_t st = s.stars[k];
|
||||||
|
for (int t = 0; t < tail; t++) {
|
||||||
|
int idx = st.h + t;
|
||||||
|
if (idx < 0 || idx >= f.n) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int fade = 255 - (t * 255) / (tail - 1 > 1 ? tail - 1 : 1);
|
||||||
|
rgb base = c[st.ci];
|
||||||
|
rgb lit = ab({ base.r * fade / 255, base.g * fade / 255, base.b * fade / 255 }, b);
|
||||||
|
int pix = led_at(f, idx);
|
||||||
|
rgb o = f.px[pix];
|
||||||
|
f.px[pix] = { o.r > lit.r ? o.r : lit.r, o.g > lit.g ? o.g : lit.g, o.b > lit.b ? o.b : lit.b };
|
||||||
|
}
|
||||||
|
st.h -= sgn(f, speed);
|
||||||
|
if (st.h >= -tail) {
|
||||||
|
s.stars[keep++] = st;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.nstars = keep;
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_particles(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
return f.pr->n[6] == 1 ? starfall_run(f, s) : snow_run(f, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- sparkle: trail, ice burst, fireflies ------------------------------------------------------
|
||||||
|
|
||||||
|
static bool sparkle_trail(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { { 120, 120, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int density = nz(f.pr->n[1], 24);
|
||||||
|
int decay = clampi(nz(f.pr->n[2], 210), 1, 255);
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
fade_frame(f, decay);
|
||||||
|
int sparks = f.n * density / 255;
|
||||||
|
if (sparks < 1) sparks = 1;
|
||||||
|
for (int k = 0; k < sparks; k++) {
|
||||||
|
int idx = rnd(0, f.n > 0 ? f.n - 1 : 0);
|
||||||
|
put(f, idx, ab(c[rnd(0, nc - 1)], b));
|
||||||
|
}
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool sparkle_ice(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[3] = { { 240, 248, 255 }, { 200, 235, 255 }, { 255, 255, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int rate = clampi(nz(f.pr->n[1], 55), 1, 255);
|
||||||
|
int decay = clampi(nz(f.pr->n[2], 140), 1, 255);
|
||||||
|
int halo = clampi(f.pr->n[3], 0, 3);
|
||||||
|
const int cap = 28;
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
int keep = 0;
|
||||||
|
for (int k = 0; k < s.nsparks; k++) {
|
||||||
|
spark_t sp = s.sparks[k];
|
||||||
|
sp.lv -= decay;
|
||||||
|
if (sp.lv > 0) {
|
||||||
|
s.sparks[keep++] = sp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.nsparks = keep;
|
||||||
|
if (s.nsparks < cap && rnd(0, 255) < rate) {
|
||||||
|
s.sparks[s.nsparks++] = { rnd(0, f.n > 0 ? f.n - 1 : 0), 255, rnd(0, nc - 1) };
|
||||||
|
}
|
||||||
|
for (int k = 0; k < s.nsparks; k++) {
|
||||||
|
spark_t sp = s.sparks[k];
|
||||||
|
rgb base = c[sp.ci];
|
||||||
|
for (int off = -halo; off <= halo; off++) {
|
||||||
|
int idx = sp.p + off;
|
||||||
|
if (idx < 0 || idx >= f.n) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int dist = abs(off);
|
||||||
|
int fac = dist == 0 ? sp.lv : (sp.lv * (halo - dist + 1)) / (halo + 1);
|
||||||
|
rgb lit = ab({ base.r * fac / 255, base.g * fac / 255, base.b * fac / 255 }, b);
|
||||||
|
rgb o = f.px[idx];
|
||||||
|
f.px[idx] = { o.r + lit.r > 255 ? 255 : o.r + lit.r, o.g + lit.g > 255 ? 255 : o.g + lit.g,
|
||||||
|
o.b + lit.b > 255 ? 255 : o.b + lit.b };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool sparkle_fireflies(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[2] = { { 255, 210, 80 }, { 120, 255, 120 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 2, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int count = nz(f.pr->n[1], 6);
|
||||||
|
if (count > 16) count = 16;
|
||||||
|
int speed = nz(f.pr->n[2], 8);
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
s.nbugs = count;
|
||||||
|
for (int k = 0; k < count; k++) {
|
||||||
|
s.bugs[k] = { rnd(0, f.n > 0 ? f.n - 1 : 0), rnd(0, 255) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
for (int k = 0; k < s.nbugs; k++) {
|
||||||
|
bug_t &bg = s.bugs[k];
|
||||||
|
int tri = 255 - abs(128 - bg.ph) * 2;
|
||||||
|
rgb col = ab(c[bg.pos % nc], b);
|
||||||
|
put(f, bg.pos, { col.r * tri / 255, col.g * tri / 255, col.b * tri / 255 });
|
||||||
|
bg.ph = (bg.ph + speed) & 255;
|
||||||
|
if (rnd(0, 31) == 0) {
|
||||||
|
bg.pos = rnd(0, f.n > 0 ? f.n - 1 : 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_sparkle(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
switch (f.pr->n[6]) {
|
||||||
|
case 1:
|
||||||
|
return sparkle_ice(f, s);
|
||||||
|
case 2:
|
||||||
|
return sparkle_fireflies(f, s);
|
||||||
|
default:
|
||||||
|
return sparkle_trail(f, s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- rain drops --------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_rain_drops(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { { 120, 180, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int rate = nz(f.pr->n[1], 32);
|
||||||
|
int width = nz(f.pr->n[2], 3);
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
put(f, i, bgc);
|
||||||
|
}
|
||||||
|
if (rnd(0, 255) < rate && s.ndrops < 32) {
|
||||||
|
s.drops[s.ndrops++] = { rnd(0, f.n > 0 ? f.n - 1 : 0), 0 };
|
||||||
|
}
|
||||||
|
int keep = 0;
|
||||||
|
int denom = width + 1;
|
||||||
|
for (int k = 0; k < s.ndrops; k++) {
|
||||||
|
drop_t dr = s.drops[k];
|
||||||
|
for (int off = -width; off <= width; off++) {
|
||||||
|
int idx = dr.pos + off;
|
||||||
|
if (idx < 0 || idx >= f.n) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int lvl = 255 - (abs(off) * 255 / (denom > 1 ? denom : 1) + dr.age * 40);
|
||||||
|
if (lvl < 0) lvl = 0;
|
||||||
|
rgb base = ab(c[dr.age % nc], b);
|
||||||
|
put(f, idx, { base.r * lvl / 255, base.g * lvl / 255, base.b * lvl / 255 });
|
||||||
|
}
|
||||||
|
dr.age++;
|
||||||
|
if (dr.age < 8) {
|
||||||
|
s.drops[keep++] = dr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.ndrops = keep;
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- rime: slow frost build-up -----------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_rime(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[3] = { { 220, 235, 255 }, WHITE, { 185, 220, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int num = f.n;
|
||||||
|
if (num <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int chill = clampi(nz(f.pr->n[1], 36), 1, 255);
|
||||||
|
int melt = clampi(nz(f.pr->n[2], 12), 1, 255);
|
||||||
|
int spark_cap = clampi(nz(f.pr->n[3], 3), 1, num);
|
||||||
|
if (first_call(s)) {
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
s.glow[i] = 0;
|
||||||
|
}
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!due(f.now, s.last, period_of(f))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
s.glow[i] = s.glow[i] > melt ? s.glow[i] - melt : 0;
|
||||||
|
}
|
||||||
|
int spawned = 0;
|
||||||
|
int tries = spark_cap + num / 8;
|
||||||
|
for (int t = 0; t < tries; t++) {
|
||||||
|
if (spawned >= spark_cap) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (rnd(0, 255) >= chill) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int j = rnd(0, num - 1);
|
||||||
|
int g = s.glow[j] + rnd(80, 200);
|
||||||
|
s.glow[j] = g > 255 ? 255 : g;
|
||||||
|
spawned++;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
int g = clampi(s.glow[i], 0, 255);
|
||||||
|
rgb hi = ab(c[i % nc], b);
|
||||||
|
rgb px = { (hi.r * g + bgc.r * (255 - g)) / 255, (hi.g * g + bgc.g * (255 - g)) / 255,
|
||||||
|
(hi.b * g + bgc.b * (255 - g)) / 255 };
|
||||||
|
put(f, i, px);
|
||||||
|
}
|
||||||
|
return !f.pr->autorun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- twinkle -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
static const rgb kCool[6] = {
|
||||||
|
{ 120, 200, 255 }, { 80, 140, 255 }, { 180, 120, 255 },
|
||||||
|
{ 100, 220, 240 }, { 160, 200, 255 }, { 90, 180, 220 },
|
||||||
|
};
|
||||||
|
|
||||||
|
static int cluster_lo(const fx_t &f, int *hi_out)
|
||||||
|
{
|
||||||
|
int lo = f.pr->n[3];
|
||||||
|
int hi = f.pr->n[4];
|
||||||
|
int num = f.n;
|
||||||
|
if (lo <= 0 && hi <= 0) {
|
||||||
|
lo = 1;
|
||||||
|
hi = num < 4 ? num : 4;
|
||||||
|
} else {
|
||||||
|
if (lo <= 0) lo = 1;
|
||||||
|
if (hi <= 0) hi = lo;
|
||||||
|
if (hi < lo) {
|
||||||
|
int t = lo;
|
||||||
|
lo = hi;
|
||||||
|
hi = t;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lo = clampi(lo, 1, num > 0 ? num : 1);
|
||||||
|
hi = clampi(hi, lo, num > 0 ? num : 1);
|
||||||
|
*hi_out = hi;
|
||||||
|
return lo;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int cluster_len(const fx_t &f)
|
||||||
|
{
|
||||||
|
int hi;
|
||||||
|
int lo = cluster_lo(f, &hi);
|
||||||
|
return lo == hi ? lo : rnd(lo, hi);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int cluster_base(const fx_t &f, int start, int k)
|
||||||
|
{
|
||||||
|
k = clampi(k, 0, f.n);
|
||||||
|
if (k <= 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int b = start < f.n - k ? start : f.n - k;
|
||||||
|
return b < 0 ? 0 : b;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_twinkle(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb palette[PATTERN_MAX_COLOURS];
|
||||||
|
int np = get_colours(f, kCool, 6, palette);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int num = f.n;
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
if (num <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (first_call(s)) {
|
||||||
|
int dens0 = clampi(f.pr->n[2] > 0 ? f.pr->n[2] : 128, 0, 255);
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
s.on[i] = rnd(0, 255) < dens0;
|
||||||
|
s.col_i[i] = rnd(0, np - 1);
|
||||||
|
}
|
||||||
|
s.last = f.now;
|
||||||
|
}
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
put(f, i, s.on[i] ? ab(palette[s.col_i[i] % np], b) : bgc);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uint32_t d = period_of(f);
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int rate = clampi(f.pr->n[1] > 0 ? f.pr->n[1] : 48, 1, 255);
|
||||||
|
int dens = clampi(f.pr->n[2] > 0 ? f.pr->n[2] : 128, 0, 255);
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
s.next_on[i] = s.on[i];
|
||||||
|
s.next_ci[i] = s.col_i[i];
|
||||||
|
}
|
||||||
|
s.nlight = 0;
|
||||||
|
s.ndark = 0;
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
if (rnd(0, 255) < rate) {
|
||||||
|
int r = rnd(0, 255);
|
||||||
|
if (!s.on[i]) {
|
||||||
|
if (r < dens) s.light[s.nlight++] = i;
|
||||||
|
} else {
|
||||||
|
if (r < 255 - dens) s.dark[s.ndark++] = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int k = 0; k < s.ndark; k++) {
|
||||||
|
int start = s.dark[k];
|
||||||
|
int len = cluster_len(f);
|
||||||
|
int base = cluster_base(f, start, len);
|
||||||
|
for (int dj = 0; dj < len; dj++) {
|
||||||
|
s.next_on[base + dj] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int k = 0; k < s.nlight; k++) {
|
||||||
|
int start = s.light[k];
|
||||||
|
int len = cluster_len(f);
|
||||||
|
int base = cluster_base(f, start, len);
|
||||||
|
for (int dj = 0; dj < len; dj++) {
|
||||||
|
s.next_on[base + dj] = 1;
|
||||||
|
s.next_ci[base + dj] = rnd(0, np - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
put(f, i, s.next_on[i] ? ab(palette[s.next_ci[i] % np], b) : bgc);
|
||||||
|
s.on[i] = s.next_on[i];
|
||||||
|
s.col_i[i] = s.next_ci[i];
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- radiate: pulses from nodes ----------------------------------------------------------------
|
||||||
|
|
||||||
|
static int radiate_front(int age, int outward, int ret, int maxd)
|
||||||
|
{
|
||||||
|
if (age <= outward) {
|
||||||
|
return (age * maxd + outward - 1) / outward;
|
||||||
|
}
|
||||||
|
if (age <= outward + ret) {
|
||||||
|
int rem = ret - (age - outward);
|
||||||
|
return (rem * maxd + ret - 1) / ret;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_radiate(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
rgb off_c = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
// n1 spacing (LEDs); n2/n3 rise and fall in ms, default half a period each so a ring is seen
|
||||||
|
int half = (int)(period_of(f) / 2) < 1 ? 1 : (int)(period_of(f) / 2);
|
||||||
|
int spacing = nz(f.pr->n[1], 24);
|
||||||
|
int outward = nz(f.pr->n[2], half);
|
||||||
|
int ret = nz(f.pr->n[3], half);
|
||||||
|
int maxd = spacing / 2;
|
||||||
|
int life = outward + ret;
|
||||||
|
int num = f.n;
|
||||||
|
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
// One pulse, then hold
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.aux = f.now;
|
||||||
|
}
|
||||||
|
int age = (int)(f.now - s.aux);
|
||||||
|
if (age < 1) age = 1;
|
||||||
|
int front = radiate_front(age, outward, ret, maxd);
|
||||||
|
if (front < 0) front = 0;
|
||||||
|
rgb lit = ab(c[s.ci % nc], b);
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
int offset = (i + spacing / 2) % spacing;
|
||||||
|
int dist = offset < spacing - offset ? offset : spacing - offset;
|
||||||
|
put(f, i, dist <= front ? lit : off_c);
|
||||||
|
}
|
||||||
|
if (age >= life) {
|
||||||
|
s.ci++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t delay = period_of(f);
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.last = f.now;
|
||||||
|
s.ncent = 1;
|
||||||
|
s.centers[0] = (int)f.now;
|
||||||
|
}
|
||||||
|
if ((int32_t)(f.now - s.last) >= (int32_t)delay) {
|
||||||
|
s.ncent = 1;
|
||||||
|
s.centers[0] = (int)f.now;
|
||||||
|
s.last += delay;
|
||||||
|
s.ci++;
|
||||||
|
}
|
||||||
|
int kept = 0;
|
||||||
|
for (int k = 0; k < s.ncent; k++) {
|
||||||
|
if ((int)(f.now - s.centers[k]) < life) {
|
||||||
|
s.centers[kept++] = s.centers[k];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.ncent = kept;
|
||||||
|
rgb lit = ab(c[s.ci % nc], b);
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
int offset = (i + spacing / 2) % spacing;
|
||||||
|
int dist = offset < spacing - offset ? offset : spacing - offset;
|
||||||
|
bool on = false;
|
||||||
|
for (int k = 0; k < s.ncent && !on; k++) {
|
||||||
|
int age = (int)(f.now - s.centers[k]);
|
||||||
|
if (age <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
int front = radiate_front(age, outward, ret, maxd);
|
||||||
|
if (front < 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (dist <= front) {
|
||||||
|
on = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
put(f, i, on ? lit : off_c);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- palette morph -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_palette_morph(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[3] = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 3, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
int num = f.n;
|
||||||
|
if (nc < 2) {
|
||||||
|
fill(f, ab(c[0], b));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int morph = nz(f.pr->n[1], 1200);
|
||||||
|
if (morph < 50) morph = 50;
|
||||||
|
int warp = nz(f.pr->n[2], 3);
|
||||||
|
int turb = nz(f.pr->n[3], 24);
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.aux = f.now; // morph start
|
||||||
|
s.last = f.now; // frame timer
|
||||||
|
s.ci = 0; // base colour index
|
||||||
|
s.phase = 0;
|
||||||
|
}
|
||||||
|
uint32_t delay = period_of(f);
|
||||||
|
if (!due(f.now, s.last, delay)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int age = (int)(f.now - s.aux);
|
||||||
|
int t = age < morph ? (age * 255) / morph : 255;
|
||||||
|
rgb a = c[s.ci % nc];
|
||||||
|
rgb bb = c[(s.ci + 1) % nc];
|
||||||
|
rgb anchor = mix(a, bb, t);
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
int pos = (i * 256) / (num > 0 ? num : 1);
|
||||||
|
int wobble = (((pos * turb) / 32) + s.phase + (t / 2)) & 255;
|
||||||
|
int breath = 255 - abs(128 - wobble) * 2;
|
||||||
|
int local = (pos + breath / 3 + t / 4) % 256;
|
||||||
|
int idx = (s.ci + ((local * nc) / 256)) % nc;
|
||||||
|
int frac = (local * nc) & 255;
|
||||||
|
rgb grad = mix(c[idx], c[(idx + 1) % nc], frac);
|
||||||
|
rgb out = mix(grad, anchor, 80);
|
||||||
|
put(f, i, ab(out, b));
|
||||||
|
}
|
||||||
|
if (age >= morph) {
|
||||||
|
s.ci = (s.ci + 1) % nc;
|
||||||
|
s.aux = f.now;
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.phase = (s.phase + warp) & 255;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- flame -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
static int tri255(uint32_t elapsed, uint32_t period)
|
||||||
|
{
|
||||||
|
if (period < 400) period = 400;
|
||||||
|
uint32_t p = elapsed % period;
|
||||||
|
uint32_t half = period >> 1;
|
||||||
|
if (half == 0) return 128;
|
||||||
|
if (p < half) return (int)((p * 255) / half);
|
||||||
|
return (int)(((period - p) * 255) / (period - half));
|
||||||
|
}
|
||||||
|
|
||||||
|
static rgb palette_sample(const rgb *pal, int n, int pos)
|
||||||
|
{
|
||||||
|
if (n == 1) return pal[0];
|
||||||
|
int span = (n - 1) * pos;
|
||||||
|
int seg = span >> 8;
|
||||||
|
if (seg >= n - 1) return pal[n - 1];
|
||||||
|
int frac = span & 0xFF;
|
||||||
|
rgb a = pal[seg];
|
||||||
|
rgb b = pal[seg + 1];
|
||||||
|
rgb o = { a.r + (((b.r - a.r) * frac) >> 8), a.g + (((b.g - a.g) * frac) >> 8),
|
||||||
|
a.b + (((b.b - a.b) * frac) >> 8) };
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void flame_frame(fx_t &f, st_t &s, const rgb *pal, int np, uint32_t breath_el, bool spark_on)
|
||||||
|
{
|
||||||
|
int num = f.n;
|
||||||
|
int denom = num > 1 ? num - 1 : 1;
|
||||||
|
int breathe = tri255(breath_el, (uint32_t)s.breath_ms);
|
||||||
|
int base_level = s.lo + (((s.hi - s.lo) * breathe) >> 8);
|
||||||
|
int micro = 232 + rnd(0, 35);
|
||||||
|
int level = clampi((base_level * micro) >> 8, s.lo, s.hi);
|
||||||
|
int boost = 0;
|
||||||
|
rgb white = { 0, 0, 0 };
|
||||||
|
if (spark_on && s.spark_dur > 0) {
|
||||||
|
int el = (int)(f.now - s.spark_start);
|
||||||
|
if (el < 0) el = 0;
|
||||||
|
if (el < s.spark_dur) {
|
||||||
|
int env = 255 - (el * 255) / s.spark_dur;
|
||||||
|
boost = (env * 90) >> 8;
|
||||||
|
white = { (env * 55) >> 8, (env * 50) >> 8, (env * 40) >> 8 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int cell = num >> 3;
|
||||||
|
if (cell < 1) cell = 1;
|
||||||
|
for (int i = 0; i < num; i++) {
|
||||||
|
int h = (i * 256) / denom;
|
||||||
|
int flow = (h + s.rise + (i / cell) * 17) & 255;
|
||||||
|
int pos = (flow + s.cj[(i >> 2) & 7]) & 255;
|
||||||
|
rgb c = palette_sample(pal, np, pos);
|
||||||
|
if (boost) {
|
||||||
|
c = { clampi(c.r + white.r + ((boost * 3) >> 2), 0, 255), clampi(c.g + white.g + (boost >> 1), 0, 255),
|
||||||
|
clampi(c.b + white.b + (boost >> 2), 0, 255) };
|
||||||
|
}
|
||||||
|
put(f, i, ab(c, level));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fx_flame(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[4] = { { 90, 8, 8 }, { 200, 40, 12 }, { 255, 120, 30 }, { 255, 220, 140 } };
|
||||||
|
rgb pal[PATTERN_MAX_COLOURS];
|
||||||
|
int np = get_colours(f, def, 4, pal);
|
||||||
|
int lo = clampi(f.pr->n[1], 0, 255);
|
||||||
|
int hi = clampi(f.pr->brightness, 0, 255);
|
||||||
|
if (lo > hi) {
|
||||||
|
int t = lo;
|
||||||
|
lo = hi;
|
||||||
|
hi = t;
|
||||||
|
}
|
||||||
|
int bp = f.pr->n[2];
|
||||||
|
int breath_ms = bp > 0 ? bp : 2500;
|
||||||
|
if (breath_ms < 800) breath_ms = 800;
|
||||||
|
int gap_lo = f.pr->n[3];
|
||||||
|
int gap_hi = f.pr->n[4];
|
||||||
|
if (gap_lo == 0 && gap_hi == 0) {
|
||||||
|
gap_lo = 10000;
|
||||||
|
gap_hi = 30000;
|
||||||
|
} else {
|
||||||
|
if (gap_lo < 500) gap_lo = 500;
|
||||||
|
}
|
||||||
|
if (gap_hi < gap_lo) gap_hi = gap_lo;
|
||||||
|
uint32_t delay = f.pr->delay < 16 ? 16 : f.pr->delay;
|
||||||
|
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.breath_ms = breath_ms;
|
||||||
|
s.lo = lo;
|
||||||
|
s.hi = hi;
|
||||||
|
s.rise = rnd(0, 255);
|
||||||
|
for (int k = 0; k < 8; k++) {
|
||||||
|
s.cj[k] = rnd(-18, 18);
|
||||||
|
}
|
||||||
|
s.last = f.now; // last frame
|
||||||
|
s.breath_origin = f.now;
|
||||||
|
s.last_cluster = f.now;
|
||||||
|
s.spark_active = false;
|
||||||
|
s.spark_dur = 0;
|
||||||
|
s.next_spark = f.now + (uint32_t)rnd(gap_lo, gap_hi);
|
||||||
|
}
|
||||||
|
s.lo = lo;
|
||||||
|
s.hi = hi;
|
||||||
|
s.breath_ms = breath_ms;
|
||||||
|
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
flame_frame(f, s, pal, np, 0, false);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if ((int32_t)(f.now - s.last) < (int32_t)delay) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
s.last += delay;
|
||||||
|
s.rise = (s.rise + rnd(-10, 12)) & 255;
|
||||||
|
if ((int32_t)(f.now - s.last_cluster) >= (int32_t)(delay * 4)) {
|
||||||
|
s.last_cluster = f.now;
|
||||||
|
for (int k = 0; k < 8; k++) {
|
||||||
|
s.cj[k] = rnd(-18, 18);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s.spark_active) {
|
||||||
|
if ((int)(f.now - s.spark_start) >= s.spark_dur) {
|
||||||
|
s.spark_active = false;
|
||||||
|
s.next_spark = f.now + (uint32_t)rnd(gap_lo, gap_hi);
|
||||||
|
}
|
||||||
|
} else if ((int32_t)(f.now - s.next_spark) >= 0) {
|
||||||
|
s.spark_active = true;
|
||||||
|
s.spark_start = f.now;
|
||||||
|
s.spark_dur = rnd(180, 360);
|
||||||
|
}
|
||||||
|
flame_frame(f, s, pal, np, f.now - s.breath_origin, s.spark_active);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Patterns that span the rig, ported from the MicroPython led-driver (rig.py and patterns folder).
|
||||||
|
* The rig geometry is the MicroPython default for a lone strip: the bar runs from (-1, 0) to (1, 0), so
|
||||||
|
* LED i sits at x = -1 + 2 (i + 0.5) / n. The rig placement (place) is not configurable on this board.
|
||||||
|
*/
|
||||||
|
#include <cmath>
|
||||||
|
|
||||||
|
#include "effects.h"
|
||||||
|
|
||||||
|
static const rgb WHITE = { 255, 255, 255 };
|
||||||
|
|
||||||
|
static bool first_call(st_t &s)
|
||||||
|
{
|
||||||
|
if (s.started) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
s.started = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Position of LED i on the bar
|
||||||
|
static float led_x(int i, int n)
|
||||||
|
{
|
||||||
|
return -1.0f + 2.0f * (i + 0.5f) / n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Distance from the centre, 0..1
|
||||||
|
static float led_r(int i, int n)
|
||||||
|
{
|
||||||
|
float x = led_x(i, n);
|
||||||
|
return x < 0 ? -x : x;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Angle round the centre, 0..1 of a turn: the left half is at 1/2, the right at 0
|
||||||
|
static float led_a(int i, int n)
|
||||||
|
{
|
||||||
|
return led_x(i, n) < 0 ? 0.5f : 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Position of LED i along a direction across the rig, 0..1
|
||||||
|
static float along(int i, int n, float angle_deg)
|
||||||
|
{
|
||||||
|
float rad = angle_deg * 3.14159265f / 180.0f;
|
||||||
|
return (led_x(i, n) * cosf(rad) + 1.0f) / 2.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int shade_of(float p)
|
||||||
|
{
|
||||||
|
int s = (int)(p * (RIG_SHADES - 1) + 0.5f);
|
||||||
|
return s < 0 ? 0 : (s > RIG_SHADES - 1 ? RIG_SHADES - 1 : s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shade of a brightness-free sine: 0..15
|
||||||
|
static int sin_shade(int i)
|
||||||
|
{
|
||||||
|
float v = (sinf(i * 6.2831853f / 256.0f) + 1.0f) / 2.0f * (RIG_SHADES - 1) + 0.5f;
|
||||||
|
return (int)v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- field wave --------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_field_wave(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int n = f.n;
|
||||||
|
int kind = f.pr->n[3];
|
||||||
|
int lam = nz(f.pr->n[2], 1000);
|
||||||
|
uint32_t period = dur(f, (int)f.pr->delay);
|
||||||
|
if (period < 1) period = 1;
|
||||||
|
(void)first_call(s);
|
||||||
|
uint32_t t = f.t;
|
||||||
|
bool done = !f.pr->autorun && t >= period;
|
||||||
|
int ph = done ? 256 : (int)((t % period) * 256 / period);
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
int shade;
|
||||||
|
if (kind == 3) {
|
||||||
|
// Plasma: two sines of the position, summed
|
||||||
|
// Lone bar: y is always 0, so the second sine is taken at -p13
|
||||||
|
int px = (int)(led_x(i, n) * 3 * 256000 / (lam * 6.283f));
|
||||||
|
int p13 = ph * 13 / 10;
|
||||||
|
float v = sinf(((px + ph) & 255) * 6.2831853f / 256.0f)
|
||||||
|
+ sinf(((-p13) & 255) * 6.2831853f / 256.0f); // -2..2
|
||||||
|
shade = sin_shade(((int)(v * 41) + ph) & 255);
|
||||||
|
} else {
|
||||||
|
float m = kind == 1 ? led_r(i, n) : (kind == 2 ? led_a(i, n) : along(i, n, (float)f.pr->n[1]));
|
||||||
|
int mi = (int)(m * 256000 / lam);
|
||||||
|
shade = sin_shade((mi - ph) & 255);
|
||||||
|
}
|
||||||
|
put(f, i, rig_entry(f, c, nc, RIG_SHADES, shade, RIG_LEVELS - 1));
|
||||||
|
}
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- grow --------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_grow(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int n = f.n;
|
||||||
|
int mode = f.pr->n[1];
|
||||||
|
const int top = RIG_LEVELS - 1;
|
||||||
|
const float edge = 0.06f;
|
||||||
|
(void)first_call(s);
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
float m;
|
||||||
|
if (mode == 1) {
|
||||||
|
m = 1 - led_r(i, n);
|
||||||
|
} else if (mode == 2) {
|
||||||
|
m = led_a(i, n);
|
||||||
|
} else if (mode == 3) {
|
||||||
|
m = along(i, n, (float)f.pr->n[3]);
|
||||||
|
} else {
|
||||||
|
m = led_r(i, n);
|
||||||
|
}
|
||||||
|
s.m[i] = m;
|
||||||
|
s.shade[i] = shade_of(m);
|
||||||
|
}
|
||||||
|
uint32_t total = dur(f, (int)f.pr->delay);
|
||||||
|
if (total < 1) total = 1;
|
||||||
|
bool empties = f.pr->n[2] == 1 || f.pr->n[2] == 2 || f.pr->autorun;
|
||||||
|
int phases = empties ? 2 : 1;
|
||||||
|
uint32_t t = f.t;
|
||||||
|
if (!f.pr->autorun && t >= total * phases) {
|
||||||
|
if (f.pr->n[2] == 3 || empties) {
|
||||||
|
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), f.pr->brightness));
|
||||||
|
} else {
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], top));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
float ph;
|
||||||
|
if (f.pr->autorun) {
|
||||||
|
ph = (float)(t % (total * phases)) / total;
|
||||||
|
} else {
|
||||||
|
ph = (float)t / total;
|
||||||
|
if (ph > phases) ph = (float)phases;
|
||||||
|
}
|
||||||
|
float front;
|
||||||
|
bool rising;
|
||||||
|
if (ph <= 1) {
|
||||||
|
front = ph * (1 + edge);
|
||||||
|
rising = true;
|
||||||
|
} else if (f.pr->n[2] == 2) {
|
||||||
|
front = (ph - 1) * (1 + edge);
|
||||||
|
rising = false;
|
||||||
|
} else {
|
||||||
|
front = (2 - ph) * (1 + edge);
|
||||||
|
rising = true;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
float v = (rising ? (front - s.m[i]) : (s.m[i] - front)) / edge;
|
||||||
|
int lv = v <= 0 ? 0 : (v >= 1 ? top : (int)(v * top));
|
||||||
|
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], lv));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- ripple ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_ripple(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int n = f.n;
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
const int top = RIG_LEVELS - 1;
|
||||||
|
(void)first_call(s);
|
||||||
|
uint32_t period = dur(f, (int)f.pr->delay);
|
||||||
|
if (period < 1) period = 1;
|
||||||
|
float hw = (f.pr->n[1] > 0 ? f.pr->n[1] : 150) / 2000.0f;
|
||||||
|
int rings = f.pr->autorun ? nz(f.pr->n[2], 1) : 1;
|
||||||
|
if (rings > 8) rings = 8;
|
||||||
|
float fade = (f.pr->n[4] > 0 ? f.pr->n[4] : 0) / 1000.0f;
|
||||||
|
uint32_t t = f.t;
|
||||||
|
if (!f.pr->autorun && t >= period) {
|
||||||
|
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
float base = f.pr->autorun ? (float)(t % period) / period : (float)t / period;
|
||||||
|
float span = 1 + 4 * hw;
|
||||||
|
float rads[8];
|
||||||
|
for (int k = 0; k < rings; k++) {
|
||||||
|
float x = base + (float)k / rings;
|
||||||
|
x = x - floorf(x);
|
||||||
|
rads[k] = -2 * hw + x * span;
|
||||||
|
}
|
||||||
|
int shade = (int)((t / period) % (uint32_t)nc);
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
float r = (f.pr->n[3] == 1) ? (1 - led_r(i, n)) : led_r(i, n);
|
||||||
|
float best = 0;
|
||||||
|
for (int k = 0; k < rings; k++) {
|
||||||
|
float v = 1 - fabsf(r - rads[k]) / hw;
|
||||||
|
if (v > best) best = v;
|
||||||
|
}
|
||||||
|
if (fade > 0 && best > 0) {
|
||||||
|
best *= 1 - fade * r;
|
||||||
|
if (best < 0) best = 0;
|
||||||
|
}
|
||||||
|
put(f, i, rig_entry(f, c, nc, nc, shade, (int)(best * top)));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- spin --------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_spin(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int n = f.n;
|
||||||
|
const int top = RIG_LEVELS - 1;
|
||||||
|
(void)first_call(s);
|
||||||
|
uint32_t period = dur(f, (int)f.pr->delay);
|
||||||
|
if (period < 1) period = 1;
|
||||||
|
float span = 1.0f / (f.pr->n[1] > 0 ? f.pr->n[1] : 1);
|
||||||
|
float width = (f.pr->n[2] > 0 ? f.pr->n[2] : 20) / 360.0f;
|
||||||
|
float tail = (f.pr->n[3] > 0 ? f.pr->n[3] : 90) / 360.0f;
|
||||||
|
uint32_t t = f.t;
|
||||||
|
if (!f.pr->autorun && t >= period) {
|
||||||
|
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), f.pr->brightness));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
float rot = fmodf((float)t / period, 1.0f);
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
float ang = f.pr->n[4] == 1 ? 1 - led_a(i, n) : led_a(i, n);
|
||||||
|
float x = rot - ang;
|
||||||
|
float behind = x - floorf(x / span) * span;
|
||||||
|
if (behind < width) {
|
||||||
|
put(f, i, rig_entry(f, c, nc, RIG_SHADES, 0, top));
|
||||||
|
} else {
|
||||||
|
float fr = (behind - width) / tail;
|
||||||
|
if (fr >= 1) {
|
||||||
|
put(f, i, rig_entry(f, c, nc, RIG_SHADES, 0, 0));
|
||||||
|
} else {
|
||||||
|
int shade = (int)(fr * (RIG_SHADES - 1));
|
||||||
|
int lv = (int)((1 - fr) * top);
|
||||||
|
put(f, i, rig_entry(f, c, nc, RIG_SHADES, shade, lv));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- sweep -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool fx_sweep(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
const rgb def[1] = { WHITE };
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, def, 1, c);
|
||||||
|
int n = f.n;
|
||||||
|
const int top = RIG_LEVELS - 1;
|
||||||
|
(void)first_call(s);
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
s.m[i] = along(i, n, (float)f.pr->n[1]);
|
||||||
|
s.shade[i] = shade_of(s.m[i]);
|
||||||
|
}
|
||||||
|
uint32_t total = dur(f, (int)f.pr->delay);
|
||||||
|
if (total < 1) total = 1;
|
||||||
|
float hw = (f.pr->n[2] > 0 ? f.pr->n[2] : 200) / 2000.0f;
|
||||||
|
float trail = (f.pr->n[3] > 0 ? f.pr->n[3] : 0) / 1000.0f;
|
||||||
|
bool keep = f.pr->n[4] == 1;
|
||||||
|
uint32_t t = f.t;
|
||||||
|
bool done = !f.pr->autorun && t >= total;
|
||||||
|
float p = done ? 1.0f : (float)(t % total) / total;
|
||||||
|
float head = -hw + p * (1 + 2 * hw + trail);
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
float d = s.m[i] - head;
|
||||||
|
float k;
|
||||||
|
if (d > hw) {
|
||||||
|
k = 0;
|
||||||
|
} else if (d >= -hw) {
|
||||||
|
k = (keep && d < 0) ? 1.0f : 1 - fabsf(d) / hw;
|
||||||
|
} else if (keep) {
|
||||||
|
k = 1;
|
||||||
|
} else if (trail > 0) {
|
||||||
|
k = 1 + (d + hw) / trail;
|
||||||
|
if (k < 0) k = 0;
|
||||||
|
} else {
|
||||||
|
k = 0;
|
||||||
|
}
|
||||||
|
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], (int)(k * top)));
|
||||||
|
}
|
||||||
|
return done;
|
||||||
|
}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Helpers shared by the pattern files: integer maths that matches Python's // and %, colour mixing,
|
||||||
|
* random numbers and the rig colour table.
|
||||||
|
*/
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "esp_random.h"
|
||||||
|
#include "beat_sync.h"
|
||||||
|
#include "effects.h"
|
||||||
|
|
||||||
|
int clampi(int v, int lo, int hi)
|
||||||
|
{
|
||||||
|
return v < lo ? lo : (v > hi ? hi : v);
|
||||||
|
}
|
||||||
|
|
||||||
|
int fdiv(int a, int b)
|
||||||
|
{
|
||||||
|
int q = a / b;
|
||||||
|
if ((a % b != 0) && ((a < 0) != (b < 0))) {
|
||||||
|
q--;
|
||||||
|
}
|
||||||
|
return q;
|
||||||
|
}
|
||||||
|
|
||||||
|
int pmod(int a, int m)
|
||||||
|
{
|
||||||
|
int r = a % m;
|
||||||
|
return r < 0 ? r + m : r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int nz(int v, int def)
|
||||||
|
{
|
||||||
|
return v > 0 ? v : def;
|
||||||
|
}
|
||||||
|
|
||||||
|
rgb mk(int r, int g, int b)
|
||||||
|
{
|
||||||
|
rgb c = { clampi(r, 0, 255), clampi(g, 0, 255), clampi(b, 0, 255) };
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
rgb ab(rgb c, int level)
|
||||||
|
{
|
||||||
|
rgb o = { fdiv(c.r * level, 255), fdiv(c.g * level, 255), fdiv(c.b * level, 255) };
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
rgb mix(rgb a, rgb b, int k)
|
||||||
|
{
|
||||||
|
rgb o = {
|
||||||
|
a.r + fdiv((b.r - a.r) * k, 255),
|
||||||
|
a.g + fdiv((b.g - a.g) * k, 255),
|
||||||
|
a.b + fdiv((b.b - a.b) * k, 255),
|
||||||
|
};
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
int sgn(const fx_t &, int v)
|
||||||
|
{
|
||||||
|
return v; // reverse mirrors the strip only (led_at), it does not change direction
|
||||||
|
}
|
||||||
|
|
||||||
|
int led_at(const fx_t &f, int i)
|
||||||
|
{
|
||||||
|
return (f.pr->reverse && i >= 0 && i < f.n) ? f.n - 1 - i : i;
|
||||||
|
}
|
||||||
|
|
||||||
|
void put(fx_t &f, int phys, rgb c)
|
||||||
|
{
|
||||||
|
if (phys >= 0 && phys < f.n) {
|
||||||
|
f.px[phys] = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void putl(fx_t &f, int logical, rgb c)
|
||||||
|
{
|
||||||
|
put(f, led_at(f, logical), c);
|
||||||
|
}
|
||||||
|
|
||||||
|
void fill(fx_t &f, rgb c)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
f.px[i] = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool due(uint32_t now, uint32_t &last, uint32_t d)
|
||||||
|
{
|
||||||
|
if ((int32_t)(now - last) >= (int32_t)d) {
|
||||||
|
last += d;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A preset's timing is always milliseconds. Beats belong to sequences and animations, which the
|
||||||
|
// controller plays, so a preset never follows the tempo.
|
||||||
|
uint32_t dur(const fx_t &, int v)
|
||||||
|
{
|
||||||
|
return v < 0 ? 0 : (uint32_t)v;
|
||||||
|
}
|
||||||
|
|
||||||
|
int get_colours(const fx_t &f, const rgb *def, int ndef, rgb *out)
|
||||||
|
{
|
||||||
|
if (f.pr->ncol > 0) {
|
||||||
|
int n = f.pr->ncol > PATTERN_MAX_COLOURS ? PATTERN_MAX_COLOURS : f.pr->ncol;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
out[i] = mk(f.pr->col[i][0], f.pr->col[i][1], f.pr->col[i][2]);
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < ndef; i++) {
|
||||||
|
out[i] = def[i];
|
||||||
|
}
|
||||||
|
return ndef;
|
||||||
|
}
|
||||||
|
|
||||||
|
int rnd(int lo, int hi)
|
||||||
|
{
|
||||||
|
if (hi <= lo) {
|
||||||
|
return lo;
|
||||||
|
}
|
||||||
|
return lo + (int)(esp_random() % (uint32_t)(hi - lo + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
rgb grad_at(const rgb *cols, int m, float t)
|
||||||
|
{
|
||||||
|
if (m == 1 || t <= 0) {
|
||||||
|
return cols[0];
|
||||||
|
}
|
||||||
|
if (t >= 1) {
|
||||||
|
return cols[m - 1];
|
||||||
|
}
|
||||||
|
float x = t * (m - 1);
|
||||||
|
int j = (int)x;
|
||||||
|
float f = x - j;
|
||||||
|
rgb a = cols[j];
|
||||||
|
rgb b = cols[j + 1];
|
||||||
|
rgb o = { (int)(a.r + (b.r - a.r) * f), (int)(a.g + (b.g - a.g) * f), (int)(a.b + (b.b - a.b) * f) };
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Colour of one entry of the rig table: a shade of the colour list at a brightness level (0..15),
|
||||||
|
// over the background. Mirrors rig.Lut in the MicroPython driver.
|
||||||
|
rgb rig_entry(const fx_t &f, const rgb *cols, int ncols, int shades, int shade, int level)
|
||||||
|
{
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
|
rgb c = (shades > 1) ? grad_at(cols, ncols, (float)shade / (shades - 1)) : cols[0];
|
||||||
|
rgb sc = { fdiv((int)c.r * b, 255), fdiv((int)c.g * b, 255), fdiv((int)c.b * b, 255) };
|
||||||
|
int top = RIG_LEVELS - 1;
|
||||||
|
rgb o = {
|
||||||
|
bgc.r + fdiv((sc.r - bgc.r) * level, top),
|
||||||
|
bgc.g + fdiv((sc.g - bgc.g) * level, top),
|
||||||
|
bgc.b + fdiv((sc.b - bgc.b) * level, top),
|
||||||
|
};
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hue wheel, 0..255 -> colour
|
||||||
|
rgb wheel(int pos)
|
||||||
|
{
|
||||||
|
pos &= 255;
|
||||||
|
rgb c;
|
||||||
|
if (pos < 85) {
|
||||||
|
c.r = pos * 3;
|
||||||
|
c.g = 255 - pos * 3;
|
||||||
|
c.b = 0;
|
||||||
|
} else if (pos < 170) {
|
||||||
|
pos -= 85;
|
||||||
|
c.r = 255 - pos * 3;
|
||||||
|
c.g = 0;
|
||||||
|
c.b = pos * 3;
|
||||||
|
} else {
|
||||||
|
pos -= 170;
|
||||||
|
c.r = 0;
|
||||||
|
c.g = pos * 3;
|
||||||
|
c.b = 255 - pos * 3;
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
}
|
||||||
@@ -0,0 +1,443 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Port of led-driver/src/espnow_rx.py (the MicroPython driver) and the announce and ping parts of
|
||||||
|
* espnow_transport.py. Frames arrive in the ESP-NOW callback; beats are taken there, the rest is queued for
|
||||||
|
* the link task, which does the reliable-link work and calls ctrl_handle.
|
||||||
|
*/
|
||||||
|
#include "espnow_link.h"
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "esp_check.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_now.h"
|
||||||
|
#include "esp_random.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "esp_wifi.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/queue.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
#include "beat_sync.h"
|
||||||
|
#include "ctrl_msg.h"
|
||||||
|
#include "net.h"
|
||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
static const char *TAG = "espnow";
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr uint8_t kMagic = 0x4C;
|
||||||
|
constexpr uint8_t kAnnounce = 0x01;
|
||||||
|
constexpr uint8_t kData = 0x20;
|
||||||
|
constexpr uint8_t kAck = 0x21;
|
||||||
|
constexpr uint8_t kDigest = 0x22;
|
||||||
|
constexpr uint8_t kResync = 0x23;
|
||||||
|
constexpr uint8_t kBeat = 0x25;
|
||||||
|
constexpr uint8_t kPingReq = 0x05;
|
||||||
|
constexpr uint8_t kPingRsp = 0x06;
|
||||||
|
constexpr uint8_t kFlagAck = 1;
|
||||||
|
constexpr uint8_t kFlagCommit = 2;
|
||||||
|
|
||||||
|
constexpr size_t kHdr = 9; // DATA header: [4C][20][flags][seq u16][ver u16][idx][cnt]
|
||||||
|
constexpr size_t kFragMax = 238; // bytes of the inner packet per DATA frame
|
||||||
|
constexpr int kMaxFrags = 32;
|
||||||
|
constexpr int kAsmSlots = 2; // messages being reassembled at once
|
||||||
|
constexpr int kDoneMax = 16; // recent messages kept for duplicate detection
|
||||||
|
constexpr int kInboxLen = 24;
|
||||||
|
constexpr int64_t kAsmTimeoutUs = 3000000;
|
||||||
|
constexpr int64_t kResyncGapUs = 3000000;
|
||||||
|
constexpr int64_t kAnnounceUs[3] = { 300000, 1300000, 2600000 };
|
||||||
|
// After the boot announces, repeat every 10 s: the radio's channel can hop while the client scans for its
|
||||||
|
// network, so one burst can be missed. The controller updates the device it already has, so repeats are harmless.
|
||||||
|
constexpr int64_t kAnnounceEveryUs = 10000000;
|
||||||
|
|
||||||
|
struct Frame {
|
||||||
|
uint8_t mac[6];
|
||||||
|
uint16_t len;
|
||||||
|
uint8_t data[250];
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Asm {
|
||||||
|
bool used;
|
||||||
|
uint8_t mac[6];
|
||||||
|
uint16_t seq;
|
||||||
|
uint8_t cnt;
|
||||||
|
uint8_t flags;
|
||||||
|
uint16_t ver;
|
||||||
|
uint32_t mask;
|
||||||
|
uint16_t lens[kMaxFrags];
|
||||||
|
uint8_t *buf; // cnt * kFragMax
|
||||||
|
int64_t last_us;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Done {
|
||||||
|
uint8_t mac[6];
|
||||||
|
uint16_t seq;
|
||||||
|
};
|
||||||
|
|
||||||
|
QueueHandle_t s_inbox;
|
||||||
|
bool s_started;
|
||||||
|
espnow_stats_t s_st;
|
||||||
|
Asm s_asm[kAsmSlots];
|
||||||
|
Done s_done[kDoneMax];
|
||||||
|
int s_ndone;
|
||||||
|
uint16_t s_ver; // state version this driver has
|
||||||
|
bool s_resync_pending;
|
||||||
|
int64_t s_resync_at;
|
||||||
|
int64_t s_last_resync;
|
||||||
|
bool s_ping_pending;
|
||||||
|
int64_t s_ping_at;
|
||||||
|
uint8_t s_ping_mac[6];
|
||||||
|
uint32_t s_ping_id;
|
||||||
|
int s_announce_left;
|
||||||
|
int64_t s_announce_base;
|
||||||
|
int64_t s_next_announce;
|
||||||
|
|
||||||
|
// ---- sending ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
esp_err_t send_to(const uint8_t mac[6], const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
if (!esp_now_is_peer_exist(mac)) {
|
||||||
|
esp_now_peer_info_t p = {};
|
||||||
|
memcpy(p.peer_addr, mac, 6);
|
||||||
|
p.ifidx = WIFI_IF_STA;
|
||||||
|
p.encrypt = false;
|
||||||
|
esp_err_t e = esp_now_add_peer(&p);
|
||||||
|
if (e != ESP_OK && e != ESP_ERR_ESPNOW_EXIST) {
|
||||||
|
s_st.send_fail++;
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
esp_err_t e = esp_now_send(mac, data, len);
|
||||||
|
if (e == ESP_OK) {
|
||||||
|
s_st.sent++;
|
||||||
|
} else {
|
||||||
|
s_st.send_fail++;
|
||||||
|
}
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t kBroadcast[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
|
||||||
|
|
||||||
|
void send_announce(void)
|
||||||
|
{
|
||||||
|
uint8_t pkt[250];
|
||||||
|
size_t n = ctrl_build_announce(pkt, sizeof(pkt));
|
||||||
|
if (n) {
|
||||||
|
send_to(kBroadcast, pkt, n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void send_ack(const uint8_t mac[6], uint16_t seq, uint8_t cnt, uint32_t mask)
|
||||||
|
{
|
||||||
|
uint8_t p[10] = { kMagic, kAck, 0, (uint8_t)(seq & 0xFF), (uint8_t)(seq >> 8), cnt,
|
||||||
|
(uint8_t)(mask & 0xFF), (uint8_t)(mask >> 8), (uint8_t)(mask >> 16), (uint8_t)(mask >> 24) };
|
||||||
|
send_to(mac, p, sizeof(p));
|
||||||
|
s_st.acks++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void send_resync(void)
|
||||||
|
{
|
||||||
|
if (!s_st.master_seen) return;
|
||||||
|
uint8_t p[4] = { kMagic, kResync, (uint8_t)(s_ver & 0xFF), (uint8_t)(s_ver >> 8) };
|
||||||
|
send_to(s_st.master, p, sizeof(p));
|
||||||
|
s_st.resyncs++;
|
||||||
|
s_last_resync = esp_timer_get_time();
|
||||||
|
}
|
||||||
|
|
||||||
|
void send_ping_rsp(void)
|
||||||
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
size_t nl = strlen(n.hostname);
|
||||||
|
uint8_t p[250];
|
||||||
|
p[0] = kMagic;
|
||||||
|
p[1] = kPingRsp;
|
||||||
|
p[2] = s_ping_id & 0xFF;
|
||||||
|
p[3] = (s_ping_id >> 8) & 0xFF;
|
||||||
|
p[4] = (s_ping_id >> 16) & 0xFF;
|
||||||
|
p[5] = (s_ping_id >> 24) & 0xFF;
|
||||||
|
p[6] = (uint8_t)nl;
|
||||||
|
memcpy(p + 7, n.hostname, nl);
|
||||||
|
send_to(s_ping_mac, p, 7 + nl);
|
||||||
|
s_st.pings++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- receiving (link task) --------------------------------------------------------------------
|
||||||
|
|
||||||
|
void asm_free(Asm &a)
|
||||||
|
{
|
||||||
|
free(a.buf);
|
||||||
|
a.buf = nullptr;
|
||||||
|
a.used = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Asm *asm_find(const uint8_t mac[6], uint16_t seq)
|
||||||
|
{
|
||||||
|
for (auto &a : s_asm) {
|
||||||
|
if (a.used && a.seq == seq && memcmp(a.mac, mac, 6) == 0) return &a;
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool done_has(const uint8_t mac[6], uint16_t seq)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < s_ndone; i++) {
|
||||||
|
if (s_done[i].seq == seq && memcmp(s_done[i].mac, mac, 6) == 0) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void done_add(const uint8_t mac[6], uint16_t seq)
|
||||||
|
{
|
||||||
|
if (s_ndone == kDoneMax) {
|
||||||
|
memmove(&s_done[0], &s_done[1], sizeof(Done) * (kDoneMax - 1));
|
||||||
|
s_ndone--;
|
||||||
|
}
|
||||||
|
memcpy(s_done[s_ndone].mac, mac, 6);
|
||||||
|
s_done[s_ndone].seq = seq;
|
||||||
|
s_ndone++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void on_data(const uint8_t mac[6], const uint8_t *data, size_t len, int64_t now)
|
||||||
|
{
|
||||||
|
if (len <= kHdr) return;
|
||||||
|
uint8_t flags = data[2];
|
||||||
|
uint16_t seq = (uint16_t)(data[3] | (data[4] << 8));
|
||||||
|
uint16_t ver = (uint16_t)(data[5] | (data[6] << 8));
|
||||||
|
uint8_t idx = data[7], cnt = data[8];
|
||||||
|
if (cnt == 0 || cnt > kMaxFrags || idx >= cnt) return;
|
||||||
|
memcpy(s_st.master, mac, 6);
|
||||||
|
s_st.master_seen = true;
|
||||||
|
uint32_t full = cnt < 32 ? ((1u << cnt) - 1) : 0xFFFFFFFFu;
|
||||||
|
if (done_has(mac, seq)) {
|
||||||
|
s_st.dups++;
|
||||||
|
if (flags & kFlagAck) send_ack(mac, seq, cnt, full); // our earlier ack was lost
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Asm *a = asm_find(mac, seq);
|
||||||
|
if (!a) {
|
||||||
|
// a free slot, else the one idle longest
|
||||||
|
Asm *pick = nullptr;
|
||||||
|
for (auto &s : s_asm) {
|
||||||
|
if (!s.used) { pick = &s; break; }
|
||||||
|
}
|
||||||
|
if (!pick) {
|
||||||
|
pick = &s_asm[0];
|
||||||
|
for (auto &s : s_asm) {
|
||||||
|
if (s.last_us < pick->last_us) pick = &s;
|
||||||
|
}
|
||||||
|
asm_free(*pick);
|
||||||
|
}
|
||||||
|
pick->buf = (uint8_t *)malloc((size_t)cnt * kFragMax);
|
||||||
|
if (!pick->buf) return;
|
||||||
|
pick->used = true;
|
||||||
|
memcpy(pick->mac, mac, 6);
|
||||||
|
pick->seq = seq;
|
||||||
|
pick->cnt = cnt;
|
||||||
|
pick->flags = flags;
|
||||||
|
pick->ver = ver;
|
||||||
|
pick->mask = 0;
|
||||||
|
memset(pick->lens, 0, sizeof(pick->lens));
|
||||||
|
a = pick;
|
||||||
|
}
|
||||||
|
size_t frag = len - kHdr;
|
||||||
|
if (frag > kFragMax) frag = kFragMax;
|
||||||
|
memcpy(a->buf + (size_t)idx * kFragMax, data + kHdr, frag);
|
||||||
|
a->lens[idx] = (uint16_t)frag;
|
||||||
|
a->mask |= 1u << idx;
|
||||||
|
a->last_us = now;
|
||||||
|
if (flags & kFlagAck) send_ack(mac, seq, cnt, a->mask);
|
||||||
|
if (a->mask != full) return;
|
||||||
|
|
||||||
|
// complete: the message is the fragments in order
|
||||||
|
size_t total = 0;
|
||||||
|
for (int i = 0; i < cnt; i++) total += a->lens[i];
|
||||||
|
uint8_t *msg = (uint8_t *)malloc(total ? total : 1);
|
||||||
|
if (msg) {
|
||||||
|
size_t off = 0;
|
||||||
|
for (int i = 0; i < cnt; i++) {
|
||||||
|
memcpy(msg + off, a->buf + (size_t)i * kFragMax, a->lens[i]);
|
||||||
|
off += a->lens[i];
|
||||||
|
}
|
||||||
|
done_add(mac, seq);
|
||||||
|
s_st.msgs++;
|
||||||
|
ctrl_handle(mac, msg, total);
|
||||||
|
free(msg);
|
||||||
|
}
|
||||||
|
if ((a->flags & kFlagCommit) && a->ver) {
|
||||||
|
s_ver = a->ver;
|
||||||
|
s_st.ver = a->ver;
|
||||||
|
s_resync_pending = false;
|
||||||
|
}
|
||||||
|
asm_free(*a);
|
||||||
|
}
|
||||||
|
|
||||||
|
void on_digest(const uint8_t mac[6], const uint8_t *data, size_t len, int64_t now)
|
||||||
|
{
|
||||||
|
if (len < 4) return;
|
||||||
|
memcpy(s_st.master, mac, 6);
|
||||||
|
s_st.master_seen = true;
|
||||||
|
uint16_t ver = (uint16_t)(data[2] | (data[3] << 8));
|
||||||
|
if (ver == 0 || ver == s_ver || s_resync_pending) return;
|
||||||
|
if (s_last_resync && now - s_last_resync < kResyncGapUs) return;
|
||||||
|
// spread the drivers' resync requests over a few hundred ms
|
||||||
|
s_resync_at = now + (int64_t)(esp_random() % 400) * 1000;
|
||||||
|
s_resync_pending = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void handle_frame(const Frame &f, int64_t now)
|
||||||
|
{
|
||||||
|
if (f.len < 2) return;
|
||||||
|
if (f.data[0] == kMagic) {
|
||||||
|
switch (f.data[1]) {
|
||||||
|
case kData:
|
||||||
|
on_data(f.mac, f.data, f.len, now);
|
||||||
|
return;
|
||||||
|
case kDigest:
|
||||||
|
on_digest(f.mac, f.data, f.len, now);
|
||||||
|
return;
|
||||||
|
case kPingReq:
|
||||||
|
if (f.len >= 6) {
|
||||||
|
s_ping_id = f.data[2] | (f.data[3] << 8) | (f.data[4] << 16) | ((uint32_t)f.data[5] << 24);
|
||||||
|
memcpy(s_ping_mac, f.mac, 6);
|
||||||
|
s_ping_at = now + (int64_t)(50 + esp_random() % 451) * 1000; // 50-500 ms, as the other drivers
|
||||||
|
s_ping_pending = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
case kAck:
|
||||||
|
case kResync:
|
||||||
|
case 0x24: // echo: bench only
|
||||||
|
case kPingRsp:
|
||||||
|
case kAnnounce:
|
||||||
|
return; // controller-bound messages, not for a driver
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctrl_handle(f.mac, f.data, f.len);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The ESP-NOW receive callback: beats are taken here, anything else is queued
|
||||||
|
void on_recv(const esp_now_recv_info_t *info, const uint8_t *data, int len)
|
||||||
|
{
|
||||||
|
s_st.frames++;
|
||||||
|
if (len < 2 || len > 250) return;
|
||||||
|
if (data[0] == kMagic && data[1] == kBeat) {
|
||||||
|
beat_on_frame(data, (size_t)len);
|
||||||
|
s_st.beats++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Frame f;
|
||||||
|
memcpy(f.mac, info->src_addr, 6);
|
||||||
|
f.len = (uint16_t)len;
|
||||||
|
memcpy(f.data, data, len);
|
||||||
|
if (xQueueSend(s_inbox, &f, 0) != pdTRUE) {
|
||||||
|
s_st.dropped++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One pass of the link: up to a burst of received frames (waiting up to wait for the first), then the timed sends
|
||||||
|
// (announces, resync, ping reply) and expired reassemblies
|
||||||
|
void link_pass(TickType_t wait)
|
||||||
|
{
|
||||||
|
Frame f;
|
||||||
|
// at most a burst of frames per pass, then the other tasks run
|
||||||
|
if (xQueueReceive(s_inbox, &f, wait) == pdTRUE) {
|
||||||
|
for (int burst = 0; burst < 8; burst++) {
|
||||||
|
handle_frame(f, esp_timer_get_time());
|
||||||
|
if (xQueueReceive(s_inbox, &f, 0) != pdTRUE) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (wait) {
|
||||||
|
vTaskDelay(1);
|
||||||
|
}
|
||||||
|
int64_t now = esp_timer_get_time();
|
||||||
|
if (s_announce_left > 0 && now >= s_announce_base + kAnnounceUs[3 - s_announce_left]) {
|
||||||
|
s_announce_left--;
|
||||||
|
send_announce();
|
||||||
|
if (s_announce_left == 0) {
|
||||||
|
s_next_announce = now + kAnnounceEveryUs;
|
||||||
|
}
|
||||||
|
} else if (s_announce_left == 0 && now >= s_next_announce) {
|
||||||
|
s_next_announce = now + kAnnounceEveryUs;
|
||||||
|
send_announce();
|
||||||
|
}
|
||||||
|
if (s_resync_pending && now >= s_resync_at) {
|
||||||
|
s_resync_pending = false;
|
||||||
|
send_resync();
|
||||||
|
}
|
||||||
|
if (s_ping_pending && now >= s_ping_at) {
|
||||||
|
s_ping_pending = false;
|
||||||
|
send_ping_rsp();
|
||||||
|
}
|
||||||
|
for (auto &a : s_asm) {
|
||||||
|
if (a.used && now - a.last_us > kAsmTimeoutUs) asm_free(a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void link_task(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
for (;;) {
|
||||||
|
link_pass(pdMS_TO_TICKS(5));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
esp_err_t espnow_link_start(void)
|
||||||
|
{
|
||||||
|
if (s_started) {
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (!n.espnow_enabled) {
|
||||||
|
ESP_LOGI(TAG, "ESP-NOW is off in settings");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
ctrl_init();
|
||||||
|
// ESP-NOW uses the radio's channel: the access point's, or the router's when the client is joined.
|
||||||
|
// It is not set here, since changing the channel while the client connects breaks the association.
|
||||||
|
uint8_t primary = n.espnow_channel;
|
||||||
|
wifi_second_chan_t second;
|
||||||
|
if (esp_wifi_get_channel(&primary, &second) == ESP_OK) {
|
||||||
|
s_st.channel = primary;
|
||||||
|
}
|
||||||
|
ESP_RETURN_ON_ERROR(esp_now_init(), TAG, "esp_now_init");
|
||||||
|
ESP_RETURN_ON_ERROR(esp_now_register_recv_cb(on_recv), TAG, "recv cb");
|
||||||
|
esp_now_peer_info_t bcast = {};
|
||||||
|
memcpy(bcast.peer_addr, kBroadcast, 6);
|
||||||
|
bcast.ifidx = WIFI_IF_STA;
|
||||||
|
esp_now_add_peer(&bcast); // it may already exist
|
||||||
|
|
||||||
|
s_inbox = xQueueCreate(kInboxLen, sizeof(Frame));
|
||||||
|
if (!s_inbox) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_announce_left = 3;
|
||||||
|
s_announce_base = esp_timer_get_time();
|
||||||
|
s_st.running = true;
|
||||||
|
s_started = true;
|
||||||
|
xTaskCreate(link_task, "espnow_link", 6144, nullptr, 5, nullptr);
|
||||||
|
ESP_LOGI(TAG, "ESP-NOW on channel %u", n.espnow_channel);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
void espnow_link_poll(void)
|
||||||
|
{
|
||||||
|
if (s_started) {
|
||||||
|
link_pass(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void espnow_link_stats(espnow_stats_t *out)
|
||||||
|
{
|
||||||
|
*out = s_st;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* ESP-NOW link to led-controller: the 0x4C wire protocol the MicroPython drivers speak. The driver announces
|
||||||
|
* itself at boot, takes the controller's reliable messages (acked, reassembled, deduplicated, resynced by
|
||||||
|
* digest), answers pings, and passes everything else to ctrl_msg. Beats set the tempo (beat_sync).
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
bool running;
|
||||||
|
uint8_t channel;
|
||||||
|
bool master_seen;
|
||||||
|
uint8_t master[6];
|
||||||
|
uint32_t msgs; // reliable messages delivered
|
||||||
|
uint32_t dups; // duplicate fragments of a message already delivered
|
||||||
|
uint32_t acks;
|
||||||
|
uint32_t resyncs;
|
||||||
|
uint32_t pings;
|
||||||
|
uint32_t beats;
|
||||||
|
uint32_t dropped; // frames lost to a full inbox
|
||||||
|
uint32_t frames; // every ESP-NOW frame the radio delivered
|
||||||
|
uint32_t sent;
|
||||||
|
uint32_t send_fail;
|
||||||
|
uint16_t ver; // state version of the last committed message
|
||||||
|
} espnow_stats_t;
|
||||||
|
|
||||||
|
/** @brief Start ESP-NOW and the link task, if enabled in settings. Call after net_start(). */
|
||||||
|
esp_err_t espnow_link_start(void);
|
||||||
|
|
||||||
|
/** @brief One pass of the link without waiting: the received frames, then the timed sends. The link task runs it
|
||||||
|
* in a loop; a build without that task (the browser simulator) calls it from a timer. */
|
||||||
|
void espnow_link_poll(void);
|
||||||
|
|
||||||
|
/** @brief Copy the link's counters and state. */
|
||||||
|
void espnow_link_stats(espnow_stats_t *out);
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
dependencies:
|
||||||
|
espressif/mdns:
|
||||||
|
version: "^1.4.0"
|
||||||
|
espressif/cjson:
|
||||||
|
version: "^1.7.19"
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "nvs_flash.h"
|
||||||
|
|
||||||
|
#include "ddp.h"
|
||||||
|
#include "espnow_link.h"
|
||||||
|
#include "net.h"
|
||||||
|
#include "ota.h"
|
||||||
|
#include "patterns.h"
|
||||||
|
#include "presets.h"
|
||||||
|
#include "usb_cfg.h"
|
||||||
|
#include "web.h"
|
||||||
|
|
||||||
|
static const char *TAG = "example";
|
||||||
|
|
||||||
|
extern "C" void app_main(void)
|
||||||
|
{
|
||||||
|
// NVS holds the saved Wi-Fi client credentials
|
||||||
|
esp_err_t err = nvs_flash_init();
|
||||||
|
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||||
|
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||||
|
err = nvs_flash_init();
|
||||||
|
}
|
||||||
|
ESP_ERROR_CHECK(err);
|
||||||
|
|
||||||
|
hw_cfg_t hw;
|
||||||
|
settings_load_hw(&hw);
|
||||||
|
patterns_start(hw);
|
||||||
|
ESP_ERROR_CHECK(presets_init());
|
||||||
|
presets_apply_startup();
|
||||||
|
ESP_ERROR_CHECK(net_start());
|
||||||
|
espnow_link_start(); // ESP-NOW from led-controller, if enabled in settings
|
||||||
|
ESP_ERROR_CHECK(web_start());
|
||||||
|
usb_cfg_start(); // led-tool over USB; the LEDs and Wi-Fi work without it
|
||||||
|
ESP_ERROR_CHECK(ddp_start());
|
||||||
|
ota_confirm_later();
|
||||||
|
|
||||||
|
char ssid[16];
|
||||||
|
net_ap_ssid(ssid, sizeof(ssid));
|
||||||
|
ESP_LOGI(TAG, "Ready: join Wi-Fi %s and open http://192.168.4.1/, or http://led.local/ on your network", ssid);
|
||||||
|
}
|
||||||
+407
@@ -0,0 +1,407 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "esp_event.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_mac.h"
|
||||||
|
#include "esp_netif.h"
|
||||||
|
#include "esp_system.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "esp_wifi.h"
|
||||||
|
#include "mdns.h"
|
||||||
|
#include "net.h"
|
||||||
|
|
||||||
|
static const char *TAG = "net";
|
||||||
|
|
||||||
|
#define AP_CHANNEL 1 // the access point's channel when ESP-NOW is off; otherwise the ESP-NOW channel
|
||||||
|
#define AP_MAX_CLIENTS 4
|
||||||
|
#define RETRY_MAX_MS 30000
|
||||||
|
|
||||||
|
static esp_netif_t *s_ap_netif;
|
||||||
|
static esp_netif_t *s_sta_netif;
|
||||||
|
static esp_timer_handle_t s_retry_timer;
|
||||||
|
static volatile bool s_sta_up;
|
||||||
|
static esp_ip4_addr_t s_sta_ip;
|
||||||
|
static int s_retries;
|
||||||
|
|
||||||
|
// The access point. It can be turned off in settings, as long as the client is connected. If the client
|
||||||
|
// then stays down for about a minute (AP_FALLBACK_RETRIES reconnect attempts), the access point comes back.
|
||||||
|
#define AP_FALLBACK_RETRIES 6
|
||||||
|
static volatile bool s_ap_on;
|
||||||
|
static bool s_ap_want; // the state ap_timer switches to
|
||||||
|
static esp_timer_handle_t s_ap_timer;
|
||||||
|
|
||||||
|
// A saved network change reconnects the client a moment later, so the reply to the request still gets out
|
||||||
|
static esp_timer_handle_t s_reconnect_timer;
|
||||||
|
static net_cfg_t s_pending_net;
|
||||||
|
|
||||||
|
// Set the STA config from credentials. Empty password means an open network.
|
||||||
|
static void apply_sta_config(const wifi_creds_t *c)
|
||||||
|
{
|
||||||
|
wifi_config_t cfg = {};
|
||||||
|
strncpy((char *)cfg.sta.ssid, c->ssid, sizeof(cfg.sta.ssid) - 1);
|
||||||
|
strncpy((char *)cfg.sta.password, c->pass, sizeof(cfg.sta.password) - 1);
|
||||||
|
cfg.sta.threshold.authmode = c->pass[0] ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN;
|
||||||
|
esp_wifi_set_config(WIFI_IF_STA, &cfg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Turn the access point on (its saved name and password, or led-XXXXXX and open) or off.
|
||||||
|
// The client keeps running either way.
|
||||||
|
static void apply_ap(bool on)
|
||||||
|
{
|
||||||
|
if (on) {
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
char ssid[33];
|
||||||
|
net_ap_ssid(ssid, sizeof(ssid));
|
||||||
|
wifi_config_t ap = {};
|
||||||
|
strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1);
|
||||||
|
ap.ap.ssid_len = strlen(ssid);
|
||||||
|
ap.ap.channel = n.espnow_enabled ? n.espnow_channel : AP_CHANNEL;
|
||||||
|
ap.ap.max_connection = AP_MAX_CLIENTS;
|
||||||
|
// A password of 8-63 characters is WPA2; anything else is an open network
|
||||||
|
const size_t plen = strlen(n.ap_pass);
|
||||||
|
if (plen >= 8) {
|
||||||
|
strncpy((char *)ap.ap.password, n.ap_pass, sizeof(ap.ap.password) - 1);
|
||||||
|
ap.ap.authmode = WIFI_AUTH_WPA2_PSK;
|
||||||
|
} else {
|
||||||
|
ap.ap.authmode = WIFI_AUTH_OPEN;
|
||||||
|
}
|
||||||
|
esp_wifi_set_config(WIFI_IF_AP, &ap);
|
||||||
|
esp_wifi_set_mode(WIFI_MODE_APSTA);
|
||||||
|
ESP_LOGI(TAG, "Access point %s on (%s)", ssid, plen >= 8 ? "WPA2" : "open");
|
||||||
|
} else {
|
||||||
|
esp_wifi_set_mode(WIFI_MODE_STA);
|
||||||
|
ESP_LOGI(TAG, "Access point off");
|
||||||
|
}
|
||||||
|
s_ap_on = on;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Switch the access point later, from a timer task (not inside a Wi-Fi event).
|
||||||
|
// s_ap_reapply: the access point stays on but its name or password changed, so restart it with them.
|
||||||
|
static bool s_ap_reapply;
|
||||||
|
|
||||||
|
static void ap_timer_cb(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
if (s_ap_want != s_ap_on) {
|
||||||
|
apply_ap(s_ap_want);
|
||||||
|
} else if (s_ap_want && s_ap_reapply) {
|
||||||
|
apply_ap(true);
|
||||||
|
}
|
||||||
|
s_ap_reapply = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t apply_client_ip(const net_cfg_t *c);
|
||||||
|
|
||||||
|
// The Wi-Fi client and ESP-NOW share the radio, and a client that searches for its network hops channels and
|
||||||
|
// breaks ESP-NOW, so only one is on: with ESP-NOW enabled the client stays off (no connect, no retries).
|
||||||
|
static bool client_allowed(void)
|
||||||
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
return !n.espnow_enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void reconnect_cb(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
esp_timer_stop(s_retry_timer);
|
||||||
|
esp_wifi_disconnect();
|
||||||
|
s_retries = 0;
|
||||||
|
if (apply_client_ip(&s_pending_net) != ESP_OK) {
|
||||||
|
ESP_LOGW(TAG, "Client address could not be applied");
|
||||||
|
}
|
||||||
|
if (client_allowed()) {
|
||||||
|
esp_wifi_connect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ap_switch_later(bool on, uint64_t delay_us)
|
||||||
|
{
|
||||||
|
s_ap_want = on;
|
||||||
|
esp_timer_stop(s_ap_timer); // not running is fine
|
||||||
|
esp_timer_start_once(s_ap_timer, delay_us);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client address: DHCP, or the static address from settings. Called before the client connects.
|
||||||
|
static esp_err_t apply_client_ip(const net_cfg_t *c)
|
||||||
|
{
|
||||||
|
if (!c->use_static) {
|
||||||
|
esp_err_t err = esp_netif_dhcpc_start(s_sta_netif);
|
||||||
|
// Already running is fine
|
||||||
|
return (err == ESP_OK || err == ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) ? ESP_OK : err;
|
||||||
|
}
|
||||||
|
esp_netif_ip_info_t info = {};
|
||||||
|
if (esp_netif_str_to_ip4(c->ip, &info.ip) != ESP_OK ||
|
||||||
|
esp_netif_str_to_ip4(c->netmask, &info.netmask) != ESP_OK ||
|
||||||
|
esp_netif_str_to_ip4(c->gateway, &info.gw) != ESP_OK) {
|
||||||
|
return ESP_ERR_INVALID_ARG;
|
||||||
|
}
|
||||||
|
esp_netif_dhcpc_stop(s_sta_netif); // ignore "not started"
|
||||||
|
esp_err_t err = esp_netif_set_ip_info(s_sta_netif, &info);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
esp_netif_dns_info_t dns = {};
|
||||||
|
const char *dns_str = c->dns[0] ? c->dns : c->gateway;
|
||||||
|
if (esp_netif_str_to_ip4(dns_str, &dns.ip.u_addr.ip4) == ESP_OK) {
|
||||||
|
dns.ip.type = ESP_IPADDR_TYPE_V4;
|
||||||
|
esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "Client static IP %s/%s gw %s", c->ip, c->netmask, c->gateway);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void retry_cb(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
if (!client_allowed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
esp_wifi_connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *data)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
(void)base;
|
||||||
|
(void)data;
|
||||||
|
switch (id) {
|
||||||
|
case WIFI_EVENT_STA_START: {
|
||||||
|
wifi_creds_t c;
|
||||||
|
if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) {
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (apply_client_ip(&n) != ESP_OK) {
|
||||||
|
ESP_LOGW(TAG, "Static IP settings are invalid; using DHCP");
|
||||||
|
n.use_static = false;
|
||||||
|
apply_client_ip(&n);
|
||||||
|
}
|
||||||
|
if (!n.espnow_enabled) {
|
||||||
|
esp_wifi_connect();
|
||||||
|
} else {
|
||||||
|
ESP_LOGI(TAG, "ESP-NOW is on: the Wi-Fi client stays off");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case WIFI_EVENT_STA_DISCONNECTED: {
|
||||||
|
// Back off 1 s, 2 s, 4 s ... up to RETRY_MAX_MS
|
||||||
|
s_sta_up = false;
|
||||||
|
uint32_t delay_ms = 1000u << (s_retries < 5 ? s_retries : 5);
|
||||||
|
if (delay_ms > RETRY_MAX_MS) delay_ms = RETRY_MAX_MS;
|
||||||
|
s_retries++;
|
||||||
|
esp_timer_stop(s_retry_timer);
|
||||||
|
esp_timer_start_once(s_retry_timer, (uint64_t)delay_ms * 1000);
|
||||||
|
if (!s_ap_on && s_retries >= AP_FALLBACK_RETRIES) {
|
||||||
|
ap_switch_later(true, 1000000); // the client keeps failing: bring the access point back
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_ip_event(void *arg, esp_event_base_t base, int32_t id, void *data)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
(void)base;
|
||||||
|
(void)id;
|
||||||
|
ip_event_got_ip_t *e = (ip_event_got_ip_t *)data;
|
||||||
|
s_sta_ip = e->ip_info.ip;
|
||||||
|
s_sta_up = true;
|
||||||
|
s_retries = 0;
|
||||||
|
ESP_LOGI(TAG, "Client IP " IPSTR, IP2STR(&e->ip_info.ip));
|
||||||
|
}
|
||||||
|
|
||||||
|
void net_ap_ssid(char *buf, size_t len)
|
||||||
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (n.ap_ssid[0]) {
|
||||||
|
snprintf(buf, len, "%s", n.ap_ssid);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint8_t mac[6];
|
||||||
|
esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP);
|
||||||
|
snprintf(buf, len, "led-%02X%02X%02X", mac[3], mac[4], mac[5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t net_start(void)
|
||||||
|
{
|
||||||
|
ESP_ERROR_CHECK(esp_netif_init());
|
||||||
|
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||||
|
s_ap_netif = esp_netif_create_default_wifi_ap();
|
||||||
|
s_sta_netif = esp_netif_create_default_wifi_sta();
|
||||||
|
|
||||||
|
wifi_init_config_t init_cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||||
|
ESP_ERROR_CHECK(esp_wifi_init(&init_cfg));
|
||||||
|
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, on_wifi_event, NULL, NULL));
|
||||||
|
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_ip_event, NULL, NULL));
|
||||||
|
|
||||||
|
const esp_timer_create_args_t timer_args = {
|
||||||
|
.callback = retry_cb,
|
||||||
|
.arg = NULL,
|
||||||
|
.dispatch_method = ESP_TIMER_TASK,
|
||||||
|
.name = "wifi_retry",
|
||||||
|
.skip_unhandled_events = false,
|
||||||
|
};
|
||||||
|
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &s_retry_timer));
|
||||||
|
|
||||||
|
const esp_timer_create_args_t ap_args = {
|
||||||
|
.callback = ap_timer_cb,
|
||||||
|
.arg = NULL,
|
||||||
|
.dispatch_method = ESP_TIMER_TASK,
|
||||||
|
.name = "ap_switch",
|
||||||
|
.skip_unhandled_events = false,
|
||||||
|
};
|
||||||
|
ESP_ERROR_CHECK(esp_timer_create(&ap_args, &s_ap_timer));
|
||||||
|
|
||||||
|
const esp_timer_create_args_t reconnect_args = {
|
||||||
|
.callback = reconnect_cb,
|
||||||
|
.arg = NULL,
|
||||||
|
.dispatch_method = ESP_TIMER_TASK,
|
||||||
|
.name = "wifi_reconnect",
|
||||||
|
.skip_unhandled_events = false,
|
||||||
|
};
|
||||||
|
ESP_ERROR_CHECK(esp_timer_create(&reconnect_args, &s_reconnect_timer));
|
||||||
|
|
||||||
|
// The access point is on unless turned off. With no client Wi-Fi saved it stays on, so the device
|
||||||
|
// can always be reached and set up.
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
wifi_creds_t c;
|
||||||
|
const bool has_creds = settings_load_wifi(&c) == ESP_OK && c.ssid[0];
|
||||||
|
apply_ap(n.ap_enabled || !has_creds);
|
||||||
|
|
||||||
|
if (has_creds) {
|
||||||
|
apply_sta_config(&c);
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_ERROR_CHECK(esp_wifi_start());
|
||||||
|
// No modem sleep: the radio stays awake so the AP never holds DDP unicast until a beacon
|
||||||
|
ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
|
||||||
|
|
||||||
|
// mDNS: <hostname>.local, with an HTTP service on port 80
|
||||||
|
ESP_ERROR_CHECK(mdns_init());
|
||||||
|
ESP_ERROR_CHECK(mdns_hostname_set(n.hostname));
|
||||||
|
ESP_ERROR_CHECK(mdns_instance_name_set("LED controller"));
|
||||||
|
// app=led-strip lets other drivers' discovery (GET /api/devices) pick out LED drivers from other HTTP devices
|
||||||
|
static mdns_txt_item_t txt[] = { { "app", "led-strip" } };
|
||||||
|
ESP_ERROR_CHECK(mdns_service_add(NULL, "_http", "_tcp", 80, txt, 1));
|
||||||
|
ESP_LOGI(TAG, "mDNS: %s.local", n.hostname);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool net_ap_on(void)
|
||||||
|
{
|
||||||
|
return s_ap_on;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool net_sta_status(char *ip, size_t ip_len)
|
||||||
|
{
|
||||||
|
if (ip_len) {
|
||||||
|
ip[0] = '\0';
|
||||||
|
}
|
||||||
|
if (!s_sta_up) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
snprintf(ip, ip_len, IPSTR, IP2STR(&s_sta_ip));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restart after a Wi-Fi change, so the reply goes out first
|
||||||
|
static void restart_cb(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t net_sta_connect(const wifi_creds_t *c)
|
||||||
|
{
|
||||||
|
esp_err_t err = settings_save_wifi(c);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (n.espnow_enabled) {
|
||||||
|
// Wi-Fi and ESP-NOW share the radio, so Wi-Fi mode means ESP-NOW off. Restart into it: the
|
||||||
|
// saved credentials are joined at boot.
|
||||||
|
n.espnow_enabled = false;
|
||||||
|
err = settings_save_net(&n);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
static esp_timer_handle_t restart_timer;
|
||||||
|
if (!restart_timer) {
|
||||||
|
esp_timer_create_args_t a = {};
|
||||||
|
a.callback = restart_cb;
|
||||||
|
a.name = "wifi_restart";
|
||||||
|
err = esp_timer_create(&a, &restart_timer);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "Wi-Fi set: ESP-NOW off, restarting into Wi-Fi mode");
|
||||||
|
return esp_timer_start_once(restart_timer, 1500000);
|
||||||
|
}
|
||||||
|
esp_timer_stop(s_retry_timer);
|
||||||
|
esp_wifi_disconnect();
|
||||||
|
s_retries = 0;
|
||||||
|
apply_sta_config(c);
|
||||||
|
return esp_wifi_connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t net_save_network(const net_cfg_t *c)
|
||||||
|
{
|
||||||
|
// Turning the access point off needs a connected client, or the device could not be reached again
|
||||||
|
net_cfg_t old;
|
||||||
|
settings_load_net(&old);
|
||||||
|
if (!c->ap_enabled && old.ap_enabled && !s_sta_up) {
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
esp_err_t err = settings_save_net(c);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
err = mdns_hostname_set(c->hostname);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
const bool ap_cfg_changed = strcmp(old.ap_ssid, c->ap_ssid) != 0 || strcmp(old.ap_pass, c->ap_pass) != 0;
|
||||||
|
if (c->ap_enabled != s_ap_on) {
|
||||||
|
// After the reply has gone out, so the page that asked still gets it
|
||||||
|
ap_switch_later(c->ap_enabled, c->ap_enabled ? 1000000 : 1500000);
|
||||||
|
} else if (c->ap_enabled && ap_cfg_changed) {
|
||||||
|
// Still on, with a new name or password: restart it after the reply has gone out
|
||||||
|
s_ap_reapply = true;
|
||||||
|
ap_switch_later(true, 1500000);
|
||||||
|
}
|
||||||
|
// Reconnect with the new address settings if a client is configured (after the reply, see reconnect_cb)
|
||||||
|
wifi_creds_t w;
|
||||||
|
if (settings_load_wifi(&w) != ESP_OK || !w.ssid[0]) {
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
s_pending_net = *c;
|
||||||
|
esp_timer_stop(s_reconnect_timer);
|
||||||
|
esp_timer_start_once(s_reconnect_timer, 1000000);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count)
|
||||||
|
{
|
||||||
|
esp_err_t err = esp_wifi_scan_start(NULL, true);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
uint16_t max = *count;
|
||||||
|
err = esp_wifi_scan_get_ap_records(&max, recs);
|
||||||
|
*count = max;
|
||||||
|
return err;
|
||||||
|
}
|
||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_wifi_types.h"
|
||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
/** @brief Start Wi-Fi (AP `led-XXXXXX` plus an optional client), and mDNS. Needs NVS. */
|
||||||
|
esp_err_t net_start(void);
|
||||||
|
|
||||||
|
/** @brief Fill buf with the AP SSID, e.g. "led-A1B2C3". */
|
||||||
|
void net_ap_ssid(char *buf, size_t len);
|
||||||
|
|
||||||
|
/** @brief True while the access point is running. */
|
||||||
|
bool net_ap_on(void);
|
||||||
|
|
||||||
|
/** @brief Client link state and its IPv4 address ("" if not connected). */
|
||||||
|
bool net_sta_status(char *ip, size_t ip_len);
|
||||||
|
|
||||||
|
/** @brief Save credentials, then connect the client with them. */
|
||||||
|
esp_err_t net_sta_connect(const wifi_creds_t *c);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Save network settings and apply them: mDNS name, static or DHCP client address.
|
||||||
|
* A connected or configured client reconnects so the new address takes effect.
|
||||||
|
*/
|
||||||
|
esp_err_t net_save_network(const net_cfg_t *c);
|
||||||
|
|
||||||
|
/** @brief Scan for networks. On entry *count is the array size; on exit, the number found. */
|
||||||
|
esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count);
|
||||||
+206
@@ -0,0 +1,206 @@
|
|||||||
|
#include "ota.h"
|
||||||
|
#include "web.h"
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_ota_ops.h"
|
||||||
|
#include "esp_app_format.h"
|
||||||
|
#include "esp_system.h"
|
||||||
|
#include <string.h>
|
||||||
|
#include "esp_timer.h"
|
||||||
|
|
||||||
|
static const char *TAG = "ota";
|
||||||
|
|
||||||
|
#define CHUNK 4096
|
||||||
|
#define CONFIRM_AFTER_US (10 * 1000000LL)
|
||||||
|
|
||||||
|
static bool s_busy;
|
||||||
|
|
||||||
|
static void reboot_cb(void *arg)
|
||||||
|
{
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void confirm_cb(void *arg)
|
||||||
|
{
|
||||||
|
esp_err_t err = esp_ota_mark_app_valid_cancel_rollback();
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
ESP_LOGI(TAG, "running image confirmed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ota_confirm_later(void)
|
||||||
|
{
|
||||||
|
esp_ota_img_states_t state;
|
||||||
|
const esp_partition_t *run = esp_ota_get_running_partition();
|
||||||
|
if (esp_ota_get_state_partition(run, &state) != ESP_OK || state != ESP_OTA_IMG_PENDING_VERIFY) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
static esp_timer_handle_t t;
|
||||||
|
const esp_timer_create_args_t args = { .callback = confirm_cb, .name = "ota_confirm" };
|
||||||
|
if (esp_timer_create(&args, &t) == ESP_OK) {
|
||||||
|
esp_timer_start_once(t, CONFIRM_AFTER_US);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t fail(httpd_req_t *req, const char *status, const char *msg)
|
||||||
|
{
|
||||||
|
ESP_LOGE(TAG, "%s", msg);
|
||||||
|
httpd_resp_set_status(req, status);
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
web_allow_lan_origin(req);
|
||||||
|
char buf[160];
|
||||||
|
snprintf(buf, sizeof(buf), "{\"error\":\"%s\"}", msg);
|
||||||
|
return httpd_resp_sendstr(req, buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t ota_post_handler(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
if (req->content_len == 0) {
|
||||||
|
return fail(req, "400 Bad Request", "empty body");
|
||||||
|
}
|
||||||
|
const esp_partition_t *part = esp_ota_get_next_update_partition(NULL);
|
||||||
|
if (!part) {
|
||||||
|
return fail(req, "500 Internal Server Error", "no update partition");
|
||||||
|
}
|
||||||
|
if (req->content_len > part->size) {
|
||||||
|
return fail(req, "413 Payload Too Large", "image larger than the app slot");
|
||||||
|
}
|
||||||
|
if (s_busy) {
|
||||||
|
return fail(req, "409 Conflict", "update already running");
|
||||||
|
}
|
||||||
|
s_busy = true;
|
||||||
|
|
||||||
|
char *buf = malloc(CHUNK);
|
||||||
|
if (!buf) {
|
||||||
|
s_busy = false;
|
||||||
|
return fail(req, "500 Internal Server Error", "out of memory");
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_ota_handle_t handle = 0;
|
||||||
|
esp_err_t err = esp_ota_begin(part, req->content_len, &handle);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
free(buf);
|
||||||
|
s_busy = false;
|
||||||
|
return fail(req, "500 Internal Server Error", "ota begin failed");
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "receiving %u bytes into %s", (unsigned)req->content_len, part->label);
|
||||||
|
|
||||||
|
size_t got = 0;
|
||||||
|
const char *bad = NULL;
|
||||||
|
while (got < req->content_len) {
|
||||||
|
int want = req->content_len - got;
|
||||||
|
int r = httpd_req_recv(req, buf, want > CHUNK ? CHUNK : want);
|
||||||
|
if (r == HTTPD_SOCK_ERR_TIMEOUT) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (r <= 0) {
|
||||||
|
bad = "receive failed";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (got == 0 && (r < (int)(sizeof(esp_image_header_t)) || (uint8_t)buf[0] != ESP_IMAGE_HEADER_MAGIC)) {
|
||||||
|
bad = "not an ESP32 app image";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (esp_ota_write(handle, buf, r) != ESP_OK) {
|
||||||
|
bad = "flash write failed";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
got += r;
|
||||||
|
}
|
||||||
|
free(buf);
|
||||||
|
if (bad) {
|
||||||
|
esp_ota_abort(handle);
|
||||||
|
s_busy = false;
|
||||||
|
return fail(req, "400 Bad Request", bad);
|
||||||
|
}
|
||||||
|
// esp_ota_end checks the image checksum and hash
|
||||||
|
if (esp_ota_end(handle) != ESP_OK) {
|
||||||
|
s_busy = false;
|
||||||
|
return fail(req, "400 Bad Request", "image failed validation");
|
||||||
|
}
|
||||||
|
if (esp_ota_set_boot_partition(part) != ESP_OK) {
|
||||||
|
s_busy = false;
|
||||||
|
return fail(req, "500 Internal Server Error", "set boot partition failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "update ok, rebooting");
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
web_allow_lan_origin(req);
|
||||||
|
httpd_resp_sendstr(req, "{\"message\":\"update written, rebooting\"}");
|
||||||
|
|
||||||
|
static esp_timer_handle_t t;
|
||||||
|
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "ota_reboot" };
|
||||||
|
if (esp_timer_create(&args, &t) == ESP_OK) {
|
||||||
|
esp_timer_start_once(t, 500 * 1000);
|
||||||
|
} else {
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t ota_get_handler(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
const esp_partition_t *run = esp_ota_get_running_partition();
|
||||||
|
const esp_app_desc_t *app = esp_app_get_description();
|
||||||
|
// The build date is only recompiled with its own file, so the ELF hash is what tells two builds apart
|
||||||
|
char sha[17];
|
||||||
|
for (int i = 0; i < 8; i++) {
|
||||||
|
snprintf(sha + 2 * i, 3, "%02x", app->app_elf_sha256[i]);
|
||||||
|
}
|
||||||
|
char buf[288];
|
||||||
|
snprintf(buf, sizeof(buf),
|
||||||
|
"{\"partition\":\"%s\",\"version\":\"%s\",\"built\":\"%s %s\",\"idf\":\"%s\",\"sha\":\"%s\"}",
|
||||||
|
run ? run->label : "?", app->version, app->date, app->time, app->idf_ver, sha);
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
web_allow_lan_origin(req);
|
||||||
|
return httpd_resp_sendstr(req, buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t reboot_post_handler(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
ESP_LOGI(TAG, "reboot requested");
|
||||||
|
httpd_resp_set_type(req, "application/json");
|
||||||
|
web_allow_lan_origin(req);
|
||||||
|
httpd_resp_sendstr(req, "{\"message\":\"rebooting\"}");
|
||||||
|
|
||||||
|
static esp_timer_handle_t t;
|
||||||
|
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "reboot" };
|
||||||
|
if (esp_timer_create(&args, &t) == ESP_OK) {
|
||||||
|
esp_timer_start_once(t, 500 * 1000);
|
||||||
|
} else {
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Browser preflight for a firmware upload from another device's page (octet-stream is not a simple request)
|
||||||
|
static esp_err_t ota_preflight_handler(httpd_req_t *req)
|
||||||
|
{
|
||||||
|
web_allow_lan_origin(req);
|
||||||
|
httpd_resp_set_hdr(req, "Access-Control-Allow-Methods", "POST");
|
||||||
|
httpd_resp_set_hdr(req, "Access-Control-Allow-Headers", "Content-Type");
|
||||||
|
httpd_resp_set_hdr(req, "Access-Control-Max-Age", "600");
|
||||||
|
httpd_resp_set_status(req, "204 No Content");
|
||||||
|
return httpd_resp_send(req, NULL, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t ota_register(httpd_handle_t server)
|
||||||
|
{
|
||||||
|
const httpd_uri_t post = { .uri = "/ota", .method = HTTP_POST, .handler = ota_post_handler };
|
||||||
|
const httpd_uri_t get = { .uri = "/ota", .method = HTTP_GET, .handler = ota_get_handler };
|
||||||
|
const httpd_uri_t preflight = { .uri = "/ota", .method = HTTP_OPTIONS, .handler = ota_preflight_handler };
|
||||||
|
esp_err_t err = httpd_register_uri_handler(server, &post);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = httpd_register_uri_handler(server, &get);
|
||||||
|
}
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = httpd_register_uri_handler(server, &preflight);
|
||||||
|
}
|
||||||
|
const httpd_uri_t reboot = { .uri = "/reboot", .method = HTTP_POST, .handler = reboot_post_handler };
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
err = httpd_register_uri_handler(server, &reboot);
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_http_server.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Register POST /ota (raw firmware .bin as the body) and GET /ota (running image info).
|
||||||
|
// The web UI is part of the image, so one upload updates both.
|
||||||
|
// POST /reboot restarts the board (replies first, reboots after 0.5 s).
|
||||||
|
// A good upload is written to the idle app slot, becomes the boot image and the board reboots.
|
||||||
|
esp_err_t ota_register(httpd_handle_t server);
|
||||||
|
|
||||||
|
// Call once at boot: confirms the running image after it has stayed up for a few seconds, so
|
||||||
|
// a new image that crashes on start rolls back to the previous one.
|
||||||
|
void ota_confirm_later(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,555 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Pattern engine: runs the selected pattern once per frame into a shadow frame, crossfades from the
|
||||||
|
* previous frame when a preset asks for it, and shows the result on the WS2812 strip.
|
||||||
|
*/
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "driver/gpio.h"
|
||||||
|
#include "esp_heap_caps.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
#include "effects.h"
|
||||||
|
#include "patterns.h"
|
||||||
|
#include "settings.h"
|
||||||
|
#include "ws2812.h"
|
||||||
|
|
||||||
|
#define FRAME_MS 10
|
||||||
|
|
||||||
|
static const char *TAG = "patterns";
|
||||||
|
|
||||||
|
typedef bool (*fx_fn)(fx_t &, st_t &);
|
||||||
|
struct pattern_def_t {
|
||||||
|
const char *name;
|
||||||
|
fx_fn fn;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Same names as the MicroPython led-driver patterns
|
||||||
|
static const pattern_def_t kPatterns[] = {
|
||||||
|
{ "off", fx_off },
|
||||||
|
{ "on", fx_on },
|
||||||
|
{ "blink", fx_blink },
|
||||||
|
{ "aurora", fx_aurora },
|
||||||
|
{ "bar_graph", fx_bar_graph },
|
||||||
|
{ "blizzard", fx_blizzard },
|
||||||
|
{ "candle_glow", fx_candle_glow },
|
||||||
|
{ "chase", fx_chase },
|
||||||
|
{ "circle", fx_circle },
|
||||||
|
{ "clock_sweep", fx_clock_sweep },
|
||||||
|
{ "colour_cycle", fx_colour_cycle },
|
||||||
|
{ "field_wave", fx_field_wave },
|
||||||
|
{ "flame", fx_flame },
|
||||||
|
{ "flicker", fx_flicker },
|
||||||
|
{ "gradient_wipe", fx_gradient_wipe },
|
||||||
|
{ "grow", fx_grow },
|
||||||
|
{ "hit", fx_hit },
|
||||||
|
{ "icicles", fx_icicles },
|
||||||
|
{ "keyframes", fx_keyframes },
|
||||||
|
{ "meteor", fx_meteor },
|
||||||
|
{ "orbit", fx_orbit },
|
||||||
|
{ "palette_morph", fx_palette_morph },
|
||||||
|
{ "particles", fx_particles },
|
||||||
|
{ "plasma", fx_plasma },
|
||||||
|
{ "pulse", fx_pulse },
|
||||||
|
{ "radiate", fx_radiate },
|
||||||
|
{ "rain_drops", fx_rain_drops },
|
||||||
|
{ "rainbow", fx_rainbow },
|
||||||
|
{ "rime", fx_rime },
|
||||||
|
{ "ripple", fx_ripple },
|
||||||
|
{ "sparkle", fx_sparkle },
|
||||||
|
{ "spin", fx_spin },
|
||||||
|
{ "strobe_burst", fx_strobe_burst },
|
||||||
|
{ "sweep", fx_sweep },
|
||||||
|
{ "transition", fx_transition },
|
||||||
|
{ "twinkle", fx_twinkle },
|
||||||
|
{ "wipe", fx_wipe },
|
||||||
|
};
|
||||||
|
#define PATTERN_COUNT ((int)(sizeof(kPatterns) / sizeof(kPatterns[0])))
|
||||||
|
|
||||||
|
static WS2812 *s_strip;
|
||||||
|
static SemaphoreHandle_t s_lock;
|
||||||
|
static preset_t s_cur; // the preset requested (under s_lock)
|
||||||
|
static bool s_reset_pending; // a new pattern was selected (under s_lock)
|
||||||
|
|
||||||
|
static preset_t s_run; // the preset the task is running
|
||||||
|
static fx_t s_fx; // shadow frame and timing for the running pattern
|
||||||
|
st_t g_st; // state of the running pattern
|
||||||
|
|
||||||
|
// Crossfade: the last frame shown, and the frame it fades from
|
||||||
|
static rgb *s_shown; // last frame shown (s_cap entries)
|
||||||
|
static rgb *s_from; // frame the crossfade starts from
|
||||||
|
static int s_cap; // LEDs the buffers are sized for
|
||||||
|
static bool s_fading;
|
||||||
|
|
||||||
|
// DDP: pixels sent by a controller replace the pattern, and the last frame stays up when they stop.
|
||||||
|
#define DDP_TIMEOUT_MS 2000
|
||||||
|
static uint8_t s_ddp[FX_LEDS_MAX * 3];
|
||||||
|
static uint32_t s_ddp_last_ms; // 0: never
|
||||||
|
static uint32_t s_ddp_packets;
|
||||||
|
static uint32_t s_ddp_frames; // frames completed (PUSH seen)
|
||||||
|
static uint32_t s_ddp_sum; // checksum of the last completed frame
|
||||||
|
static uint32_t s_ddp_log_ms; // last serial summary
|
||||||
|
// Frame sync: while syncs keep arriving, a completed DDP frame waits for the next sync before it is shown
|
||||||
|
#define DDP_SYNC_TIMEOUT_MS 2000
|
||||||
|
static uint8_t s_ddp_show[FX_LEDS_MAX * 3]; // the frame the strip shows
|
||||||
|
static uint8_t s_ddp_held[FX_LEDS_MAX * 3]; // a completed frame waiting for a sync
|
||||||
|
static bool s_ddp_held_ok;
|
||||||
|
static uint32_t s_sync_last_ms; // 0: never
|
||||||
|
static uint32_t s_sync_seq; // seq of the last sync
|
||||||
|
static uint32_t s_sync_count;
|
||||||
|
static uint32_t s_ddp_shown; // frames shown
|
||||||
|
static uint8_t s_max_brightness = 255;
|
||||||
|
static uint8_t s_global = 255;
|
||||||
|
static uint8_t s_master = 255;
|
||||||
|
static uint32_t s_fade_t0;
|
||||||
|
static uint32_t s_fade_ms;
|
||||||
|
|
||||||
|
int patterns_count(void)
|
||||||
|
{
|
||||||
|
return PATTERN_COUNT;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *patterns_name(int i)
|
||||||
|
{
|
||||||
|
return (i >= 0 && i < PATTERN_COUNT) ? kPatterns[i].name : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
int patterns_index(const char *name)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < PATTERN_COUNT; i++) {
|
||||||
|
if (strcmp(name, kPatterns[i].name) == 0) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void preset_defaults(preset_t *p, int pattern)
|
||||||
|
{
|
||||||
|
memset(p, 0, sizeof(*p));
|
||||||
|
p->pattern = pattern;
|
||||||
|
p->ncol = 0;
|
||||||
|
p->delay = 100;
|
||||||
|
p->brightness = 127;
|
||||||
|
p->autorun = true;
|
||||||
|
p->reverse = false;
|
||||||
|
p->fade = 0;
|
||||||
|
p->beat_time = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep a preset within the ranges the patterns expect
|
||||||
|
static void sanitize(preset_t *p)
|
||||||
|
{
|
||||||
|
if (p->pattern < 0 || p->pattern >= PATTERN_COUNT) {
|
||||||
|
p->pattern = 0;
|
||||||
|
}
|
||||||
|
if (p->delay < 10) p->delay = 10;
|
||||||
|
if (p->delay > 10000) p->delay = 10000;
|
||||||
|
if (p->ncol < 0) p->ncol = 0;
|
||||||
|
if (p->ncol > PATTERN_MAX_COLOURS) p->ncol = PATTERN_MAX_COLOURS;
|
||||||
|
if (p->fade > 10000) p->fade = 10000;
|
||||||
|
// Chase steps (n3/n4) may be negative to run the dot backwards; other values stay >= 0.
|
||||||
|
const bool chase = p->pattern == patterns_index("chase");
|
||||||
|
for (int i = 1; i <= 6; i++) {
|
||||||
|
bool step = chase && (i == 3 || i == 4);
|
||||||
|
if (p->n[i] < 0 && !step) p->n[i] = 0;
|
||||||
|
if (p->n[i] > 100000) p->n[i] = 100000;
|
||||||
|
if (p->n[i] < -100000) p->n[i] = -100000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Live update: a change of pattern restarts it (with a crossfade if the preset asks); other changes
|
||||||
|
// take effect straight away, keeping the pattern's place
|
||||||
|
void patterns_set(const preset_t &p)
|
||||||
|
{
|
||||||
|
preset_t q = p;
|
||||||
|
sanitize(&q);
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
bool changed = q.pattern != s_cur.pattern;
|
||||||
|
s_cur = q;
|
||||||
|
if (changed) {
|
||||||
|
s_reset_pending = true;
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Select a preset: always restarts the pattern, crossfading in from the frame on the strip
|
||||||
|
void patterns_select(const preset_t &p)
|
||||||
|
{
|
||||||
|
preset_t q = p;
|
||||||
|
sanitize(&q);
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
s_cur = q;
|
||||||
|
s_reset_pending = true;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_set_global(uint8_t level)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
s_global = level;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t patterns_get_global(void)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
uint8_t v = s_global;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_set_master(uint8_t level)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
s_master = level;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t patterns_get_master(void)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
uint8_t v = s_master;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_get(preset_t *out)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
*out = s_cur;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t now_ms(void)
|
||||||
|
{
|
||||||
|
return (uint32_t)(esp_timer_get_time() / 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// True if a timestamp stored as `now | 1` is recent. That value can be 1 ms ahead of a `now` read in the
|
||||||
|
// same millisecond, so the difference is signed: an unsigned one would wrap and look like a timeout.
|
||||||
|
static bool within(uint32_t now, uint32_t stamp, uint32_t window_ms)
|
||||||
|
{
|
||||||
|
return stamp != 0 && (int32_t)(now - stamp) < (int32_t)window_ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show the shadow frame, crossfading from the previous frame while a fade runs
|
||||||
|
static void output(uint32_t now, bool full_brightness)
|
||||||
|
{
|
||||||
|
// Pattern output: device brightness x master scale, under the max brightness ceiling. DDP frames
|
||||||
|
// skip the device and master brightness (the sender sets the colours) but still respect the ceiling.
|
||||||
|
int s_scale = full_brightness ? s_max_brightness : s_global * s_master / 255 * s_max_brightness / 255;
|
||||||
|
int k = -1;
|
||||||
|
if (s_fading) {
|
||||||
|
uint32_t el = now - s_fade_t0;
|
||||||
|
if (el >= s_fade_ms) {
|
||||||
|
s_fading = false;
|
||||||
|
} else {
|
||||||
|
k = (int)((el * 256) / s_fade_ms);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < s_fx.n; i++) {
|
||||||
|
rgb c = s_fx.px[i];
|
||||||
|
c.r = c.r * s_scale / 255;
|
||||||
|
c.g = c.g * s_scale / 255;
|
||||||
|
c.b = c.b * s_scale / 255;
|
||||||
|
if (k >= 0) {
|
||||||
|
rgb a = s_from[i];
|
||||||
|
c.r = (a.r * (256 - k) + c.r * k) >> 8;
|
||||||
|
c.g = (a.g * (256 - k) + c.g * k) >> 8;
|
||||||
|
c.b = (a.b * (256 - k) + c.b * k) >> 8;
|
||||||
|
}
|
||||||
|
s_strip->set(i, c.r, c.g, c.b);
|
||||||
|
s_shown[i] = c;
|
||||||
|
}
|
||||||
|
esp_err_t err = s_strip->write();
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGW(TAG, "LED write failed: %s", esp_err_to_name(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- per-LED buffers --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
bool frame_alloc(int n)
|
||||||
|
{
|
||||||
|
if (n < 1) n = 1;
|
||||||
|
if (n > FX_LEDS_MAX) n = FX_LEDS_MAX;
|
||||||
|
void *fresh[12] = {
|
||||||
|
calloc(n, sizeof(rgb)), calloc(n, sizeof(rgb)), calloc(n, sizeof(rgb)),
|
||||||
|
calloc(n, sizeof(int)), calloc(n, sizeof(float)), calloc(n, sizeof(int)),
|
||||||
|
calloc(n, 1), calloc(n, 1),
|
||||||
|
calloc(n, sizeof(int)), calloc(n, sizeof(int)),
|
||||||
|
calloc(n, sizeof(int)), calloc(n, sizeof(int)),
|
||||||
|
};
|
||||||
|
for (int k = 0; k < 12; k++) {
|
||||||
|
if (!fresh[k]) {
|
||||||
|
for (int j = 0; j < 12; j++) free(fresh[j]);
|
||||||
|
ESP_LOGE(TAG, "Out of memory for %d LEDs", n);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
free(s_fx.px);
|
||||||
|
free(s_shown);
|
||||||
|
free(s_from);
|
||||||
|
free(g_st.glow);
|
||||||
|
free(g_st.m);
|
||||||
|
free(g_st.shade);
|
||||||
|
free(g_st.on);
|
||||||
|
free(g_st.next_on);
|
||||||
|
free(g_st.col_i);
|
||||||
|
free(g_st.next_ci);
|
||||||
|
free(g_st.light);
|
||||||
|
free(g_st.dark);
|
||||||
|
s_fx.px = (rgb *)fresh[0];
|
||||||
|
s_shown = (rgb *)fresh[1];
|
||||||
|
s_from = (rgb *)fresh[2];
|
||||||
|
g_st.glow = (int *)fresh[3];
|
||||||
|
g_st.m = (float *)fresh[4];
|
||||||
|
g_st.shade = (int *)fresh[5];
|
||||||
|
g_st.on = (uint8_t *)fresh[6];
|
||||||
|
g_st.next_on = (uint8_t *)fresh[7];
|
||||||
|
g_st.col_i = (int *)fresh[8];
|
||||||
|
g_st.next_ci = (int *)fresh[9];
|
||||||
|
g_st.light = (int *)fresh[10];
|
||||||
|
g_st.dark = (int *)fresh[11];
|
||||||
|
s_cap = n;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void st_reset(void)
|
||||||
|
{
|
||||||
|
int *glow = g_st.glow, *shade = g_st.shade, *col_i = g_st.col_i, *next_ci = g_st.next_ci;
|
||||||
|
int *light = g_st.light, *dark = g_st.dark;
|
||||||
|
float *m = g_st.m;
|
||||||
|
uint8_t *on = g_st.on, *next_on = g_st.next_on;
|
||||||
|
memset(&g_st, 0, sizeof(g_st));
|
||||||
|
g_st.glow = glow;
|
||||||
|
g_st.shade = shade;
|
||||||
|
g_st.col_i = col_i;
|
||||||
|
g_st.next_ci = next_ci;
|
||||||
|
g_st.light = light;
|
||||||
|
g_st.dark = dark;
|
||||||
|
g_st.m = m;
|
||||||
|
g_st.on = on;
|
||||||
|
g_st.next_on = next_on;
|
||||||
|
memset(glow, 0, s_cap * sizeof(int));
|
||||||
|
memset(shade, 0, s_cap * sizeof(int));
|
||||||
|
memset(col_i, 0, s_cap * sizeof(int));
|
||||||
|
memset(next_ci, 0, s_cap * sizeof(int));
|
||||||
|
memset(light, 0, s_cap * sizeof(int));
|
||||||
|
memset(dark, 0, s_cap * sizeof(int));
|
||||||
|
memset(m, 0, s_cap * sizeof(float));
|
||||||
|
memset(on, 0, s_cap);
|
||||||
|
memset(next_on, 0, s_cap);
|
||||||
|
}
|
||||||
|
|
||||||
|
// One frame: the whole frame (pattern and output) runs under s_lock, so the buffers can't be replaced mid-frame
|
||||||
|
void patterns_frame(void)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
s_fx.pr = &s_run;
|
||||||
|
bool reset = s_reset_pending;
|
||||||
|
s_reset_pending = false;
|
||||||
|
s_run = s_cur;
|
||||||
|
uint32_t now = now_ms();
|
||||||
|
if (reset) {
|
||||||
|
s_ddp_last_ms = 0; // selecting a pattern takes the strip back from DDP
|
||||||
|
}
|
||||||
|
// Once pixels have arrived the strip keeps the last frame when they stop: the pattern does not
|
||||||
|
// come back until one is selected
|
||||||
|
bool ddp_on = s_ddp_last_ms != 0;
|
||||||
|
if (reset) {
|
||||||
|
if (s_run.fade > 0) {
|
||||||
|
memcpy(s_from, s_shown, s_fx.n * sizeof(rgb));
|
||||||
|
s_fading = true;
|
||||||
|
s_fade_t0 = now;
|
||||||
|
s_fade_ms = s_run.fade;
|
||||||
|
} else {
|
||||||
|
s_fading = false;
|
||||||
|
}
|
||||||
|
st_reset();
|
||||||
|
g_st.t0 = now;
|
||||||
|
}
|
||||||
|
s_fx.now = now;
|
||||||
|
s_fx.t = now - g_st.t0;
|
||||||
|
if (ddp_on) {
|
||||||
|
for (int i = 0; i < s_fx.n; i++) {
|
||||||
|
s_fx.px[i] = { s_ddp_show[3 * i], s_ddp_show[3 * i + 1], s_ddp_show[3 * i + 2] };
|
||||||
|
}
|
||||||
|
} else if (!g_st.done) {
|
||||||
|
if (kPatterns[s_run.pattern].fn(s_fx, g_st)) {
|
||||||
|
g_st.done = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
output(now, ddp_on);
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void patterns_task(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
while (true) {
|
||||||
|
patterns_frame();
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(FRAME_MS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int clamp_leds(int n)
|
||||||
|
{
|
||||||
|
return n < 1 ? 1 : (n > FX_LEDS_MAX ? FX_LEDS_MAX : n);
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_start(const hw_cfg_t &hw)
|
||||||
|
{
|
||||||
|
s_lock = xSemaphoreCreateMutex();
|
||||||
|
preset_defaults(&s_cur, 0);
|
||||||
|
preset_defaults(&s_run, 0);
|
||||||
|
s_cur.pattern = patterns_index("chase");
|
||||||
|
s_cur.delay = 1000;
|
||||||
|
s_cur.brightness = 16;
|
||||||
|
s_cur.col[0][0] = 255;
|
||||||
|
s_reset_pending = true;
|
||||||
|
|
||||||
|
int n = clamp_leds(hw.num_leds);
|
||||||
|
if (!frame_alloc(n)) {
|
||||||
|
ESP_ERROR_CHECK(ESP_ERR_NO_MEM);
|
||||||
|
}
|
||||||
|
s_fx.n = n;
|
||||||
|
s_max_brightness = hw.max_brightness;
|
||||||
|
s_global = hw.global_brightness;
|
||||||
|
s_master = hw.master_brightness;
|
||||||
|
s_strip = new WS2812((gpio_num_t)hw.pin, n);
|
||||||
|
s_strip->setOrder(hw.order);
|
||||||
|
s_strip->setBrightness(255); // brightness is applied per colour by the patterns
|
||||||
|
xTaskCreate(patterns_task, "patterns", 6144, NULL, 5, NULL);
|
||||||
|
ESP_LOGI(TAG, "Started %d LEDs on GPIO %d (%s), %d patterns", n, hw.pin, hw.order, PATTERN_COUNT);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change the strip: count, byte order and brightness ceiling. The buffers and the driver are replaced
|
||||||
|
// under the lock the frame runs under; on out-of-memory the old strip is kept.
|
||||||
|
esp_err_t patterns_set_hardware(const hw_cfg_t &hw)
|
||||||
|
{
|
||||||
|
int n = clamp_leds(hw.num_leds);
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
if (!frame_alloc(n)) {
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_fx.n = n;
|
||||||
|
delete s_strip;
|
||||||
|
s_strip = new WS2812((gpio_num_t)hw.pin, n);
|
||||||
|
s_strip->setOrder(hw.order);
|
||||||
|
s_strip->setBrightness(255);
|
||||||
|
s_max_brightness = hw.max_brightness;
|
||||||
|
s_fading = false;
|
||||||
|
s_reset_pending = true;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
ESP_LOGI(TAG, "LED strip: %d LEDs on GPIO %d, %s, max brightness %u, free heap %u", n, hw.pin, hw.order,
|
||||||
|
(unsigned)hw.max_brightness, (unsigned)esp_get_free_heap_size());
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- DDP ---------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Make a completed frame the one the strip shows, and log it. Caller holds s_lock.
|
||||||
|
static void ddp_show(const uint8_t *frame, uint32_t now)
|
||||||
|
{
|
||||||
|
size_t cap = (size_t)s_fx.n * 3;
|
||||||
|
memcpy(s_ddp_show, frame, cap);
|
||||||
|
s_ddp_shown++;
|
||||||
|
uint32_t sum = 0;
|
||||||
|
for (size_t i = 0; i < cap; i++) {
|
||||||
|
sum += frame[i];
|
||||||
|
}
|
||||||
|
s_ddp_sum = sum;
|
||||||
|
// Summary on the serial log, at most twice a second, so the test can check what was shown
|
||||||
|
if (now - s_ddp_log_ms >= 500) {
|
||||||
|
s_ddp_log_ms = now;
|
||||||
|
ESP_LOGI(TAG, "DDP frames=%u packets=%u sum=%u led0=%u,%u,%u led_last=%u,%u,%u",
|
||||||
|
(unsigned)s_ddp_frames, (unsigned)s_ddp_packets, (unsigned)s_ddp_sum,
|
||||||
|
frame[0], frame[1], frame[2],
|
||||||
|
frame[cap - 3], frame[cap - 2], frame[cap - 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
size_t cap = (size_t)s_fx.n * 3;
|
||||||
|
if (offset < cap) {
|
||||||
|
if (offset + len > cap) {
|
||||||
|
len = cap - offset;
|
||||||
|
}
|
||||||
|
memcpy(s_ddp + offset, data, len);
|
||||||
|
}
|
||||||
|
uint32_t now = now_ms();
|
||||||
|
s_ddp_last_ms = now | 1; // never 0
|
||||||
|
s_ddp_packets++;
|
||||||
|
if (push) {
|
||||||
|
s_ddp_frames++;
|
||||||
|
bool syncing = within(now, s_sync_last_ms, DDP_SYNC_TIMEOUT_MS);
|
||||||
|
if (syncing) {
|
||||||
|
// Syncs are arriving: hold the frame until the next one. The sender acks each frame before it
|
||||||
|
// sends the sync, so the frame is always here when its sync arrives.
|
||||||
|
memcpy(s_ddp_held, s_ddp, cap);
|
||||||
|
s_ddp_held_ok = true;
|
||||||
|
} else {
|
||||||
|
s_ddp_held_ok = false;
|
||||||
|
ddp_show(s_ddp, now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_ddp_sync(uint32_t seq)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
uint32_t now = now_ms();
|
||||||
|
s_sync_last_ms = now | 1; // never 0
|
||||||
|
s_sync_seq = seq;
|
||||||
|
s_sync_count++;
|
||||||
|
if (s_ddp_held_ok) {
|
||||||
|
s_ddp_held_ok = false;
|
||||||
|
ddp_show(s_ddp_held, now);
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_ddp_status(bool *active, uint32_t *packets)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
*active = within(now_ms(), s_ddp_last_ms, DDP_TIMEOUT_MS);
|
||||||
|
*packets = s_ddp_packets;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_ddp_debug(patterns_ddp_debug_t *out)
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
uint32_t now = now_ms();
|
||||||
|
out->syncs = s_sync_count;
|
||||||
|
out->sync_seq = s_sync_seq;
|
||||||
|
out->sync_age_ms = s_sync_last_ms != 0 ? now - s_sync_last_ms : UINT32_MAX;
|
||||||
|
out->frames = s_ddp_frames;
|
||||||
|
out->shown = s_ddp_shown;
|
||||||
|
out->held = s_ddp_held_ok;
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
void patterns_shown_pixel(int i, uint8_t out[3])
|
||||||
|
{
|
||||||
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
if (i >= 0 && i < s_fx.n) {
|
||||||
|
out[0] = (uint8_t)s_shown[i].r;
|
||||||
|
out[1] = (uint8_t)s_shown[i].g;
|
||||||
|
out[2] = (uint8_t)s_shown[i].b;
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
#define PATTERN_MAX_COLOURS 8
|
||||||
|
|
||||||
|
// Preset fields follow the MicroPython presets: pattern, colours, background, delay (d), brightness (b),
|
||||||
|
// auto (a), reverse, fade, beat_time (tb) and the pattern-specific numbers n1..n6 (n6 is the style).
|
||||||
|
struct preset_t {
|
||||||
|
char name[32]; // "" for the live settings
|
||||||
|
int pattern; // index into the pattern table
|
||||||
|
int ncol; // 0 uses each pattern's own default colours
|
||||||
|
uint8_t col[PATTERN_MAX_COLOURS][3];
|
||||||
|
uint8_t bg[3]; // background (d off colour)
|
||||||
|
uint32_t delay; // d, ms
|
||||||
|
uint8_t brightness; // b, 0-255
|
||||||
|
bool autorun; // a: keep running; false runs one cycle and holds
|
||||||
|
bool reverse; // run the other way along the strip
|
||||||
|
uint32_t fade; // crossfade in from the previous frame, ms
|
||||||
|
bool beat_time; // tb: durations are quarter beats (500 ms beat here)
|
||||||
|
int n[7]; // n[1]..n[6]
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @brief Start the LED strip and the pattern task, with the strip settings. */
|
||||||
|
void patterns_start(const struct hw_cfg_t &hw);
|
||||||
|
|
||||||
|
/** @brief Apply new strip settings (count, colour order, brightness ceiling) while running. */
|
||||||
|
esp_err_t patterns_set_hardware(const struct hw_cfg_t &hw);
|
||||||
|
|
||||||
|
/** @brief Run one frame of the pattern engine and show it. The pattern task calls it every 10 ms. */
|
||||||
|
void patterns_frame(void);
|
||||||
|
|
||||||
|
/** @brief Live update of the preset on the strip. A new pattern restarts; other changes keep its place. */
|
||||||
|
void patterns_set(const preset_t &p);
|
||||||
|
|
||||||
|
/** @brief Select a preset: always restarts the pattern, crossfading from the frame on the strip. */
|
||||||
|
void patterns_select(const preset_t &p);
|
||||||
|
|
||||||
|
/** @brief DDP pixel data for the strip: byte offset into the RGB buffer, data, length. Replaces the pattern. */
|
||||||
|
void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push);
|
||||||
|
void patterns_ddp_sync(uint32_t seq);
|
||||||
|
|
||||||
|
/** @brief Whether DDP pixels are arriving, and how many packets have come in. */
|
||||||
|
void patterns_ddp_status(bool *active, uint32_t *packets);
|
||||||
|
|
||||||
|
/** @brief Frame sync counters, for diagnosing the sync test. */
|
||||||
|
typedef struct {
|
||||||
|
uint32_t syncs; // sync packets received
|
||||||
|
uint32_t sync_seq; // seq of the last sync
|
||||||
|
uint32_t sync_age_ms; // ms since the last sync (UINT32_MAX: never)
|
||||||
|
uint32_t frames; // DDP frames completed (PUSH)
|
||||||
|
uint32_t shown; // frames shown on the strip
|
||||||
|
bool held; // a frame is waiting for the next sync
|
||||||
|
} patterns_ddp_debug_t;
|
||||||
|
void patterns_ddp_debug(patterns_ddp_debug_t *out);
|
||||||
|
|
||||||
|
/** @brief The colour last shown on LED i, as RGB. */
|
||||||
|
void patterns_shown_pixel(int i, uint8_t out[3]);
|
||||||
|
|
||||||
|
/** @brief Live brightness for every pattern, 0-255 (applied under the max brightness ceiling). */
|
||||||
|
void patterns_set_global(uint8_t level);
|
||||||
|
uint8_t patterns_get_global(void);
|
||||||
|
|
||||||
|
/** @brief Master scale for this device, 0-255: multiplies the device brightness (under the max brightness ceiling). */
|
||||||
|
void patterns_set_master(uint8_t level);
|
||||||
|
uint8_t patterns_get_master(void);
|
||||||
|
|
||||||
|
/** @brief Copy of the preset being shown. */
|
||||||
|
void patterns_get(preset_t *out);
|
||||||
|
|
||||||
|
/** @brief Number of patterns. */
|
||||||
|
int patterns_count(void);
|
||||||
|
|
||||||
|
/** @brief Name of pattern i, e.g. "chase". */
|
||||||
|
const char *patterns_name(int i);
|
||||||
|
|
||||||
|
/** @brief Index for a pattern name, or -1 if unknown. */
|
||||||
|
int patterns_index(const char *name);
|
||||||
|
|
||||||
|
/** @brief Fill a preset with the defaults for a pattern: colours and timing as the MicroPython presets. */
|
||||||
|
void preset_defaults(preset_t *p, int pattern);
|
||||||
@@ -0,0 +1,533 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Named presets, stored in NVS as one JSON list (as the MicroPython presets.json), with a startup preset.
|
||||||
|
*/
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "nvs.h"
|
||||||
|
#include "presets.h"
|
||||||
|
|
||||||
|
static const char *TAG = "presets";
|
||||||
|
static const char *NS = "presets";
|
||||||
|
|
||||||
|
static preset_t s_list[PRESETS_MAX];
|
||||||
|
static size_t s_count;
|
||||||
|
static char s_startup[32];
|
||||||
|
static char s_selected[32];
|
||||||
|
|
||||||
|
static int find(const char *name)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < s_count; i++) {
|
||||||
|
if (strcmp(s_list[i].name, name) == 0) {
|
||||||
|
return (int)i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static cJSON *rgb_json(const uint8_t *c)
|
||||||
|
{
|
||||||
|
cJSON *a = cJSON_CreateArray();
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
cJSON_AddItemToArray(a, cJSON_CreateNumber(c[i]));
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool read_rgb(const cJSON *a, uint8_t *out)
|
||||||
|
{
|
||||||
|
// The controller sends colours as "#RRGGBB" text
|
||||||
|
if (cJSON_IsString(a)) {
|
||||||
|
const char *s = a->valuestring[0] == '#' ? a->valuestring + 1 : a->valuestring;
|
||||||
|
char *end = nullptr;
|
||||||
|
unsigned long v = strtoul(s, &end, 16);
|
||||||
|
if (end != s + 6 || s[0] == '+' || s[0] == '-' || s[0] == ' ') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
out[0] = (uint8_t)(v >> 16);
|
||||||
|
out[1] = (uint8_t)((v >> 8) & 0xFF);
|
||||||
|
out[2] = (uint8_t)(v & 0xFF);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!cJSON_IsArray(a) || cJSON_GetArraySize(a) != 3) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
cJSON *v = cJSON_GetArrayItem(a, i);
|
||||||
|
if (!cJSON_IsNumber(v)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int x = v->valueint;
|
||||||
|
out[i] = (uint8_t)(x < 0 ? 0 : (x > 255 ? 255 : x));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON *preset_to_json(const preset_t *p)
|
||||||
|
{
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(o, "name", p->name);
|
||||||
|
cJSON_AddStringToObject(o, "pattern", patterns_name(p->pattern));
|
||||||
|
cJSON *colors = cJSON_AddArrayToObject(o, "colors");
|
||||||
|
for (int i = 0; i < p->ncol; i++) {
|
||||||
|
cJSON_AddItemToArray(colors, rgb_json(p->col[i]));
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(o, "background", rgb_json(p->bg));
|
||||||
|
cJSON_AddNumberToObject(o, "delay", p->delay);
|
||||||
|
cJSON_AddNumberToObject(o, "brightness", p->brightness);
|
||||||
|
cJSON_AddBoolToObject(o, "auto", p->autorun);
|
||||||
|
cJSON_AddBoolToObject(o, "reverse", p->reverse);
|
||||||
|
cJSON_AddNumberToObject(o, "fade", p->fade);
|
||||||
|
cJSON_AddBoolToObject(o, "beat_time", p->beat_time);
|
||||||
|
cJSON_AddNumberToObject(o, "n1", p->n[1]);
|
||||||
|
cJSON_AddNumberToObject(o, "n2", p->n[2]);
|
||||||
|
cJSON_AddNumberToObject(o, "n3", p->n[3]);
|
||||||
|
cJSON_AddNumberToObject(o, "n4", p->n[4]);
|
||||||
|
cJSON_AddNumberToObject(o, "mode", p->n[6]); // n6: the pattern's style
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool preset_from_json(const cJSON *o, preset_t *p)
|
||||||
|
{
|
||||||
|
if (!cJSON_IsObject(o)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
cJSON *v = cJSON_GetObjectItem(o, "name");
|
||||||
|
if (cJSON_IsString(v)) {
|
||||||
|
strncpy(p->name, v->valuestring, sizeof(p->name) - 1);
|
||||||
|
p->name[sizeof(p->name) - 1] = '\0';
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(o, "pattern");
|
||||||
|
if (cJSON_IsString(v)) {
|
||||||
|
int idx = patterns_index(v->valuestring);
|
||||||
|
if (idx < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
p->pattern = idx;
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(o, "colors");
|
||||||
|
if (cJSON_IsArray(v)) {
|
||||||
|
int n = cJSON_GetArraySize(v);
|
||||||
|
if (n > PATTERN_MAX_COLOURS) n = PATTERN_MAX_COLOURS;
|
||||||
|
p->ncol = 0;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
if (read_rgb(cJSON_GetArrayItem(v, i), p->col[p->ncol])) {
|
||||||
|
p->ncol++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
read_rgb(cJSON_GetObjectItem(o, "background"), p->bg);
|
||||||
|
v = cJSON_GetObjectItem(o, "delay");
|
||||||
|
if (cJSON_IsNumber(v)) p->delay = (uint32_t)(v->valueint < 0 ? 0 : v->valueint);
|
||||||
|
v = cJSON_GetObjectItem(o, "brightness");
|
||||||
|
if (cJSON_IsNumber(v)) p->brightness = (uint8_t)(v->valueint < 0 ? 0 : (v->valueint > 255 ? 255 : v->valueint));
|
||||||
|
v = cJSON_GetObjectItem(o, "auto");
|
||||||
|
if (cJSON_IsBool(v)) p->autorun = cJSON_IsTrue(v);
|
||||||
|
v = cJSON_GetObjectItem(o, "reverse");
|
||||||
|
if (cJSON_IsBool(v)) p->reverse = cJSON_IsTrue(v);
|
||||||
|
v = cJSON_GetObjectItem(o, "fade");
|
||||||
|
if (cJSON_IsNumber(v)) p->fade = (uint32_t)(v->valueint < 0 ? 0 : v->valueint);
|
||||||
|
v = cJSON_GetObjectItem(o, "beat_time");
|
||||||
|
if (cJSON_IsBool(v)) p->beat_time = cJSON_IsTrue(v);
|
||||||
|
static const char *keys[] = { "n1", "n2", "n3", "n4", "n5", "n6" };
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
v = cJSON_GetObjectItem(o, keys[i]);
|
||||||
|
if (cJSON_IsNumber(v)) p->n[i + 1] = v->valueint;
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(o, "mode");
|
||||||
|
if (cJSON_IsNumber(v)) p->n[6] = v->valueint;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One key per preset ("p00".."p63"), so a save writes one small entry instead of the whole list.
|
||||||
|
// NVS_SLOTS is the most keys any build has written; the 24 KB nvs partition holds about 50 presets.
|
||||||
|
#define NVS_SLOTS 64
|
||||||
|
static void entry_key(char *out, size_t n, size_t i)
|
||||||
|
{
|
||||||
|
snprintf(out, n, "p%02u", (unsigned)i);
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t save_entry(nvs_handle_t h, size_t i)
|
||||||
|
{
|
||||||
|
cJSON *o = preset_to_json(&s_list[i]);
|
||||||
|
char *s = cJSON_PrintUnformatted(o);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
if (!s) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
char key[8];
|
||||||
|
entry_key(key, sizeof(key), i);
|
||||||
|
esp_err_t err = nvs_set_str(h, key, s);
|
||||||
|
cJSON_free(s);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write every preset, the count and the startup name. Erases keys past the new count and the old blob.
|
||||||
|
static esp_err_t save_list(void)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
for (size_t i = 0; i < s_count && err == ESP_OK; i++) {
|
||||||
|
err = save_entry(h, i);
|
||||||
|
}
|
||||||
|
for (size_t i = s_count; i < NVS_SLOTS; i++) {
|
||||||
|
char key[8];
|
||||||
|
entry_key(key, sizeof(key), i);
|
||||||
|
nvs_erase_key(h, key); // also keys left by an older build with a bigger limit
|
||||||
|
}
|
||||||
|
nvs_erase_key(h, "list"); // the single blob written by older firmware
|
||||||
|
if (err == ESP_OK) err = nvs_set_u32(h, "n", (uint32_t)s_count);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "startup", s_startup);
|
||||||
|
if (err == ESP_OK) err = nvs_commit(h);
|
||||||
|
nvs_close(h);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write one preset (slot idx) and the count
|
||||||
|
static esp_err_t save_one(size_t idx)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
err = save_entry(h, idx);
|
||||||
|
if (err == ESP_OK) err = nvs_set_u32(h, "n", (uint32_t)s_count);
|
||||||
|
if (err == ESP_OK) err = nvs_commit(h);
|
||||||
|
nvs_close(h);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The presets a new board starts with (added by presets_add_defaults, and on a board that has none saved)
|
||||||
|
static int build_defaults(preset_t *out, int max)
|
||||||
|
{
|
||||||
|
int n = 0;
|
||||||
|
auto add = [&](const char *name, const char *pattern) -> preset_t * {
|
||||||
|
if (n >= max) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
preset_t *p = &out[n++];
|
||||||
|
preset_defaults(p, patterns_index(pattern));
|
||||||
|
strncpy(p->name, name, sizeof(p->name) - 1);
|
||||||
|
p->name[sizeof(p->name) - 1] = '\0';
|
||||||
|
return p;
|
||||||
|
};
|
||||||
|
preset_t *p;
|
||||||
|
if ((p = add("Rainbow", "colour_cycle"))) {
|
||||||
|
p->n[6] = 1; // rainbow wheel
|
||||||
|
p->n[1] = 2;
|
||||||
|
p->delay = 60;
|
||||||
|
p->brightness = 160;
|
||||||
|
}
|
||||||
|
if ((p = add("Chase", "chase"))) {
|
||||||
|
p->ncol = 2;
|
||||||
|
p->col[0][0] = 255; p->col[0][1] = 80; p->col[0][2] = 0;
|
||||||
|
p->col[1][0] = 0; p->col[1][1] = 120; p->col[1][2] = 255;
|
||||||
|
p->n[1] = 4; p->n[2] = 4; p->n[3] = 1; p->n[4] = 1;
|
||||||
|
p->delay = 150;
|
||||||
|
p->brightness = 180;
|
||||||
|
}
|
||||||
|
if ((p = add("Chase Marquee", "chase"))) {
|
||||||
|
p->ncol = 1;
|
||||||
|
p->col[0][0] = 255; p->col[0][1] = 200; p->col[0][2] = 80;
|
||||||
|
p->n[1] = 3; p->n[2] = 2; p->n[3] = 1; p->n[6] = 1; // dashes that scroll
|
||||||
|
p->delay = 120;
|
||||||
|
p->brightness = 180;
|
||||||
|
}
|
||||||
|
if ((p = add("Chase Reverse", "chase"))) {
|
||||||
|
p->ncol = 2;
|
||||||
|
p->col[0][0] = 0; p->col[0][1] = 255; p->col[0][2] = 120;
|
||||||
|
p->col[1][0] = 120; p->col[1][1] = 0; p->col[1][2] = 255;
|
||||||
|
p->n[1] = 6; p->n[2] = 6; p->n[3] = -1; p->n[4] = -1; // negative steps run it backwards
|
||||||
|
p->delay = 120;
|
||||||
|
p->brightness = 180;
|
||||||
|
}
|
||||||
|
if ((p = add("Aurora", "aurora"))) {
|
||||||
|
p->n[1] = 3;
|
||||||
|
p->n[2] = 40;
|
||||||
|
p->delay = 40;
|
||||||
|
p->brightness = 150;
|
||||||
|
}
|
||||||
|
if ((p = add("Candle", "candle_glow"))) {
|
||||||
|
p->ncol = 3;
|
||||||
|
p->col[0][0] = 255; p->col[0][1] = 140; p->col[0][2] = 40;
|
||||||
|
p->col[1][0] = 255; p->col[1][1] = 200; p->col[1][2] = 120;
|
||||||
|
p->col[2][0] = 255; p->col[2][1] = 90; p->col[2][2] = 20;
|
||||||
|
p->n[1] = 4; p->n[2] = 3; p->n[3] = 90;
|
||||||
|
p->delay = 120;
|
||||||
|
p->brightness = 200;
|
||||||
|
}
|
||||||
|
if ((p = add("Twinkle", "twinkle"))) {
|
||||||
|
p->ncol = 1;
|
||||||
|
p->col[0][0] = 200; p->col[0][1] = 220; p->col[0][2] = 255;
|
||||||
|
p->bg[2] = 20;
|
||||||
|
p->n[1] = 48; p->n[2] = 128;
|
||||||
|
p->delay = 100;
|
||||||
|
p->brightness = 200;
|
||||||
|
}
|
||||||
|
if ((p = add("Flame", "flame"))) {
|
||||||
|
p->delay = 40;
|
||||||
|
p->brightness = 255;
|
||||||
|
p->n[2] = 2500;
|
||||||
|
}
|
||||||
|
if ((p = add("Sweep", "sweep"))) {
|
||||||
|
p->ncol = 2;
|
||||||
|
p->col[0][0] = 255; p->col[0][1] = 0; p->col[0][2] = 120;
|
||||||
|
p->col[1][0] = 0; p->col[1][1] = 200; p->col[1][2] = 255;
|
||||||
|
p->n[1] = 90; p->n[2] = 200; p->n[3] = 200;
|
||||||
|
p->delay = 2000;
|
||||||
|
p->brightness = 200;
|
||||||
|
}
|
||||||
|
if ((p = add("Off", "off"))) {
|
||||||
|
p->brightness = 255;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the default presets whose names aren't in the list yet. Returns how many were added.
|
||||||
|
int presets_add_defaults(void)
|
||||||
|
{
|
||||||
|
preset_t defs[16];
|
||||||
|
int n = build_defaults(defs, 16);
|
||||||
|
int added = 0;
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
if (find(defs[i].name) < 0 && s_count < PRESETS_MAX) {
|
||||||
|
s_list[s_count++] = defs[i];
|
||||||
|
added++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (added > 0) {
|
||||||
|
save_list();
|
||||||
|
}
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the one JSON list written by older firmware. Returns false if there is none.
|
||||||
|
static bool load_legacy(nvs_handle_t h)
|
||||||
|
{
|
||||||
|
size_t len = 0;
|
||||||
|
if (nvs_get_blob(h, "list", NULL, &len) != ESP_OK || len == 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
char *buf = (char *)malloc(len + 1);
|
||||||
|
if (!buf) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
bool ok = false;
|
||||||
|
if (nvs_get_blob(h, "list", buf, &len) == ESP_OK) {
|
||||||
|
buf[len] = '\0';
|
||||||
|
cJSON *arr = cJSON_Parse(buf);
|
||||||
|
cJSON *o;
|
||||||
|
cJSON_ArrayForEach(o, arr) {
|
||||||
|
if (s_count >= PRESETS_MAX) break;
|
||||||
|
preset_t p;
|
||||||
|
preset_defaults(&p, 0);
|
||||||
|
if (preset_from_json(o, &p) && p.name[0]) {
|
||||||
|
s_list[s_count++] = p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cJSON_Delete(arr);
|
||||||
|
ok = true;
|
||||||
|
}
|
||||||
|
free(buf);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void load_entry(nvs_handle_t h, uint32_t i)
|
||||||
|
{
|
||||||
|
char key[8];
|
||||||
|
entry_key(key, sizeof(key), i);
|
||||||
|
size_t len = 0;
|
||||||
|
if (nvs_get_str(h, key, NULL, &len) != ESP_OK || len == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
char *buf = (char *)malloc(len);
|
||||||
|
if (!buf) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (nvs_get_str(h, key, buf, &len) == ESP_OK) {
|
||||||
|
cJSON *o = cJSON_Parse(buf);
|
||||||
|
preset_t p;
|
||||||
|
preset_defaults(&p, 0);
|
||||||
|
if (o && preset_from_json(o, &p) && p.name[0] && s_count < PRESETS_MAX) {
|
||||||
|
s_list[s_count++] = p;
|
||||||
|
}
|
||||||
|
cJSON_Delete(o);
|
||||||
|
}
|
||||||
|
free(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t presets_init(void)
|
||||||
|
{
|
||||||
|
s_count = 0;
|
||||||
|
s_startup[0] = '\0';
|
||||||
|
s_selected[0] = '\0';
|
||||||
|
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
|
||||||
|
presets_add_defaults(); // a new board
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
uint32_t n = 0;
|
||||||
|
bool have_list = nvs_get_u32(h, "n", &n) == ESP_OK;
|
||||||
|
bool legacy = false;
|
||||||
|
if (have_list) {
|
||||||
|
if (n > PRESETS_MAX) {
|
||||||
|
ESP_LOGW(TAG, "%u presets saved, room for %d: the rest are not loaded", (unsigned)n, PRESETS_MAX);
|
||||||
|
}
|
||||||
|
for (uint32_t i = 0; i < n && i < PRESETS_MAX; i++) {
|
||||||
|
load_entry(h, i);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
legacy = load_legacy(h);
|
||||||
|
have_list = legacy;
|
||||||
|
}
|
||||||
|
size_t len = sizeof(s_startup);
|
||||||
|
if (nvs_get_str(h, "startup", s_startup, &len) != ESP_OK) {
|
||||||
|
s_startup[0] = '\0';
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
if (legacy) {
|
||||||
|
save_list(); // move the old blob to per-preset keys
|
||||||
|
}
|
||||||
|
if (!have_list) {
|
||||||
|
presets_add_defaults(); // nothing saved yet: start with the defaults
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "%u presets loaded", (unsigned)s_count);
|
||||||
|
for (size_t i = 0; i < s_count; i++) {
|
||||||
|
ESP_LOGI(TAG, " [%u] %s", (unsigned)i, s_list[i].name);
|
||||||
|
}
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t presets_count(void)
|
||||||
|
{
|
||||||
|
return s_count;
|
||||||
|
}
|
||||||
|
|
||||||
|
const preset_t *presets_at(size_t i)
|
||||||
|
{
|
||||||
|
return i < s_count ? &s_list[i] : NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t s_dropped; // saves refused because the store was full
|
||||||
|
|
||||||
|
uint32_t presets_dropped(void)
|
||||||
|
{
|
||||||
|
return s_dropped;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t presets_save(const preset_t *preset)
|
||||||
|
{
|
||||||
|
int idx = find(preset->name);
|
||||||
|
bool added = idx < 0;
|
||||||
|
if (added) {
|
||||||
|
if (s_count >= PRESETS_MAX) {
|
||||||
|
s_dropped++;
|
||||||
|
ESP_LOGW(TAG, "store full (%d presets): '%s' not saved", PRESETS_MAX, preset->name);
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
idx = (int)s_count++;
|
||||||
|
}
|
||||||
|
s_list[idx] = *preset;
|
||||||
|
ESP_LOGI(TAG, "save '%s' (%s), %u presets", preset->name, added ? "new" : "update", (unsigned)s_count);
|
||||||
|
esp_err_t err = save_one((size_t)idx);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
s_dropped++;
|
||||||
|
ESP_LOGW(TAG, "'%s' not saved to flash: %s", preset->name, esp_err_to_name(err));
|
||||||
|
if (added) {
|
||||||
|
s_count--; // keep RAM and flash the same
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t presets_set_order(const char *const *names, size_t n)
|
||||||
|
{
|
||||||
|
// Static: this is too big for the HTTP server's task stack, and only that task calls it
|
||||||
|
static preset_t fresh[PRESETS_MAX];
|
||||||
|
bool used[PRESETS_MAX] = { false };
|
||||||
|
size_t m = 0;
|
||||||
|
for (size_t k = 0; k < n && m < s_count; k++) {
|
||||||
|
int idx = find(names[k]);
|
||||||
|
if (idx >= 0 && !used[idx]) {
|
||||||
|
used[idx] = true;
|
||||||
|
fresh[m++] = s_list[idx];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (size_t i = 0; i < s_count; i++) {
|
||||||
|
if (!used[i]) {
|
||||||
|
fresh[m++] = s_list[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
memcpy(s_list, fresh, m * sizeof(preset_t));
|
||||||
|
ESP_LOGI(TAG, "order: %u presets (was %u)", (unsigned)m, (unsigned)s_count);
|
||||||
|
s_count = m;
|
||||||
|
return save_list();
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t presets_delete(const char *name)
|
||||||
|
{
|
||||||
|
int idx = find(name);
|
||||||
|
if (idx < 0) {
|
||||||
|
return ESP_ERR_NOT_FOUND;
|
||||||
|
}
|
||||||
|
for (size_t i = (size_t)idx; i + 1 < s_count; i++) {
|
||||||
|
s_list[i] = s_list[i + 1];
|
||||||
|
}
|
||||||
|
s_count--;
|
||||||
|
ESP_LOGI(TAG, "delete '%s', %u presets", name, (unsigned)s_count);
|
||||||
|
if (strcmp(s_startup, name) == 0) {
|
||||||
|
s_startup[0] = '\0';
|
||||||
|
}
|
||||||
|
if (strcmp(s_selected, name) == 0) {
|
||||||
|
s_selected[0] = '\0';
|
||||||
|
}
|
||||||
|
return save_list();
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t presets_select(const char *name)
|
||||||
|
{
|
||||||
|
int idx = find(name);
|
||||||
|
if (idx < 0) {
|
||||||
|
return ESP_ERR_NOT_FOUND;
|
||||||
|
}
|
||||||
|
patterns_select(s_list[idx]);
|
||||||
|
strncpy(s_selected, name, sizeof(s_selected) - 1);
|
||||||
|
s_selected[sizeof(s_selected) - 1] = '\0';
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *presets_selected(void)
|
||||||
|
{
|
||||||
|
return s_selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t presets_set_startup(const char *name)
|
||||||
|
{
|
||||||
|
if (name[0] && find(name) < 0) {
|
||||||
|
return ESP_ERR_NOT_FOUND;
|
||||||
|
}
|
||||||
|
strncpy(s_startup, name, sizeof(s_startup) - 1);
|
||||||
|
s_startup[sizeof(s_startup) - 1] = '\0';
|
||||||
|
return save_list();
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *presets_startup(void)
|
||||||
|
{
|
||||||
|
return s_startup;
|
||||||
|
}
|
||||||
|
|
||||||
|
void presets_apply_startup(void)
|
||||||
|
{
|
||||||
|
if (s_startup[0] && presets_select(s_startup) == ESP_OK) {
|
||||||
|
ESP_LOGI(TAG, "Startup preset: %s", s_startup);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "patterns.h"
|
||||||
|
|
||||||
|
// Flash holds about 50 presets (the nvs partition is 24 KB); 48 leaves room for garbage collection
|
||||||
|
#define PRESETS_MAX 48
|
||||||
|
|
||||||
|
/** @brief Load the saved presets and the startup name from NVS. Call after NVS is initialised. */
|
||||||
|
esp_err_t presets_init(void);
|
||||||
|
|
||||||
|
/** @brief Add the default presets whose names are not in the list yet. Returns how many were added. */
|
||||||
|
int presets_add_defaults(void);
|
||||||
|
|
||||||
|
/** @brief Number of presets. */
|
||||||
|
size_t presets_count(void);
|
||||||
|
|
||||||
|
/** @brief Preset at index i (0 <= i < presets_count()). */
|
||||||
|
const preset_t *presets_at(size_t i);
|
||||||
|
|
||||||
|
/** @brief Create a preset, or update the one with the same name. ESP_ERR_NO_MEM when full. */
|
||||||
|
esp_err_t presets_save(const preset_t *preset);
|
||||||
|
|
||||||
|
/** @brief Saves refused since boot: store full, or flash write failed. */
|
||||||
|
uint32_t presets_dropped(void);
|
||||||
|
|
||||||
|
/** @brief Put the presets in this order. Names not given keep their place at the end. */
|
||||||
|
esp_err_t presets_set_order(const char *const *names, size_t n);
|
||||||
|
|
||||||
|
/** @brief Delete a preset by name. Clears the startup name if it was that preset. */
|
||||||
|
esp_err_t presets_delete(const char *name);
|
||||||
|
|
||||||
|
/** @brief Select a preset: crossfades in and restarts its pattern. ESP_ERR_NOT_FOUND if no such name. */
|
||||||
|
esp_err_t presets_select(const char *name);
|
||||||
|
|
||||||
|
/** @brief Name of the last preset selected since boot, or "". */
|
||||||
|
const char *presets_selected(void);
|
||||||
|
|
||||||
|
/** @brief Set the preset applied at boot. An empty name clears it. */
|
||||||
|
esp_err_t presets_set_startup(const char *name);
|
||||||
|
|
||||||
|
/** @brief Name of the startup preset, or "". */
|
||||||
|
const char *presets_startup(void);
|
||||||
|
|
||||||
|
/** @brief Apply the startup preset, if one is set and still exists. */
|
||||||
|
void presets_apply_startup(void);
|
||||||
|
|
||||||
|
/** @brief A preset as JSON, with the MicroPython field names. The caller frees it with cJSON_Delete. */
|
||||||
|
cJSON *preset_to_json(const preset_t *p);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Apply the fields present in JSON onto p; missing fields keep their value.
|
||||||
|
* @return false if a field is malformed (an unknown pattern name, for example).
|
||||||
|
*/
|
||||||
|
bool preset_from_json(const cJSON *o, preset_t *p);
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "nvs.h"
|
||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
static const char *NS = "led";
|
||||||
|
|
||||||
|
esp_err_t settings_load_wifi(wifi_creds_t *c)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
size_t len = sizeof(c->ssid);
|
||||||
|
err = nvs_get_str(h, "sta_ssid", c->ssid, &len);
|
||||||
|
if (err == ESP_OK) {
|
||||||
|
len = sizeof(c->pass);
|
||||||
|
err = nvs_get_str(h, "sta_pass", c->pass, &len);
|
||||||
|
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
||||||
|
c->pass[0] = '\0';
|
||||||
|
err = ESP_OK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t settings_save_wifi(const wifi_creds_t *c)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
err = nvs_set_str(h, "sta_ssid", c->ssid);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "sta_pass", c->pass);
|
||||||
|
if (err == ESP_OK) err = nvs_commit(h);
|
||||||
|
nvs_close(h);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t settings_load_hw(hw_cfg_t *c)
|
||||||
|
{
|
||||||
|
strncpy(c->order, "grb", sizeof(c->order));
|
||||||
|
c->max_brightness = 255;
|
||||||
|
c->num_leds = 119;
|
||||||
|
c->pin = 10;
|
||||||
|
c->global_brightness = 255;
|
||||||
|
c->master_brightness = 255;
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
size_t len = sizeof(c->order);
|
||||||
|
if (nvs_get_str(h, "rgb_order", c->order, &len) != ESP_OK) {
|
||||||
|
strncpy(c->order, "grb", sizeof(c->order));
|
||||||
|
}
|
||||||
|
uint8_t mb;
|
||||||
|
if (nvs_get_u8(h, "max_bright", &mb) == ESP_OK) {
|
||||||
|
c->max_brightness = mb;
|
||||||
|
}
|
||||||
|
int32_t n;
|
||||||
|
if (nvs_get_i32(h, "num_leds", &n) == ESP_OK) {
|
||||||
|
c->num_leds = (int)n;
|
||||||
|
}
|
||||||
|
if (nvs_get_i32(h, "pin", &n) == ESP_OK) {
|
||||||
|
c->pin = (int)n;
|
||||||
|
}
|
||||||
|
if (nvs_get_u8(h, "global_bright", &mb) == ESP_OK) {
|
||||||
|
c->global_brightness = mb;
|
||||||
|
}
|
||||||
|
if (nvs_get_u8(h, "master_bright", &mb) == ESP_OK) {
|
||||||
|
c->master_brightness = mb;
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t settings_save_hw(const hw_cfg_t *c)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
err = nvs_set_str(h, "rgb_order", c->order);
|
||||||
|
if (err == ESP_OK) err = nvs_set_u8(h, "max_bright", c->max_brightness);
|
||||||
|
if (err == ESP_OK) err = nvs_set_i32(h, "num_leds", c->num_leds);
|
||||||
|
if (err == ESP_OK) err = nvs_set_i32(h, "pin", c->pin);
|
||||||
|
if (err == ESP_OK) err = nvs_set_u8(h, "global_bright", c->global_brightness);
|
||||||
|
if (err == ESP_OK) err = nvs_set_u8(h, "master_bright", c->master_brightness);
|
||||||
|
if (err == ESP_OK) err = nvs_commit(h);
|
||||||
|
nvs_close(h);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read a string key; use def when it is missing or unreadable
|
||||||
|
static void get_str(nvs_handle_t h, const char *key, char *buf, size_t len, const char *def)
|
||||||
|
{
|
||||||
|
size_t n = len;
|
||||||
|
if (nvs_get_str(h, key, buf, &n) != ESP_OK) {
|
||||||
|
strncpy(buf, def, len - 1);
|
||||||
|
buf[len - 1] = '\0';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t settings_load_net(net_cfg_t *c)
|
||||||
|
{
|
||||||
|
memset(c, 0, sizeof(*c));
|
||||||
|
c->ap_enabled = true;
|
||||||
|
c->ddp_enabled = true;
|
||||||
|
c->espnow_enabled = true;
|
||||||
|
c->espnow_channel = 6;
|
||||||
|
nvs_handle_t h;
|
||||||
|
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
|
||||||
|
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
||||||
|
// Nothing saved yet: defaults
|
||||||
|
strncpy(c->hostname, "led", sizeof(c->hostname) - 1);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
get_str(h, "hostname", c->hostname, sizeof(c->hostname), "led");
|
||||||
|
char mode[8];
|
||||||
|
get_str(h, "ip_mode", mode, sizeof(mode), "dhcp");
|
||||||
|
c->use_static = strcmp(mode, "static") == 0;
|
||||||
|
get_str(h, "ip", c->ip, sizeof(c->ip), "");
|
||||||
|
get_str(h, "netmask", c->netmask, sizeof(c->netmask), "");
|
||||||
|
get_str(h, "gateway", c->gateway, sizeof(c->gateway), "");
|
||||||
|
get_str(h, "dns", c->dns, sizeof(c->dns), "");
|
||||||
|
char ap[8];
|
||||||
|
get_str(h, "ap", ap, sizeof(ap), "on");
|
||||||
|
c->ap_enabled = strcmp(ap, "off") != 0;
|
||||||
|
get_str(h, "ap_ssid", c->ap_ssid, sizeof(c->ap_ssid), "");
|
||||||
|
get_str(h, "ap_pass", c->ap_pass, sizeof(c->ap_pass), "");
|
||||||
|
char ddp[8];
|
||||||
|
get_str(h, "ddp", ddp, sizeof(ddp), "on");
|
||||||
|
c->ddp_enabled = strcmp(ddp, "off") != 0;
|
||||||
|
char espnow[8];
|
||||||
|
get_str(h, "espnow", espnow, sizeof(espnow), "on");
|
||||||
|
c->espnow_enabled = strcmp(espnow, "off") != 0;
|
||||||
|
int64_t ch = 6;
|
||||||
|
nvs_get_i64(h, "espnow_ch", &ch);
|
||||||
|
c->espnow_channel = (uint8_t)(ch >= 1 && ch <= 13 ? ch : 6);
|
||||||
|
nvs_close(h);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t settings_save_net(const net_cfg_t *c)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
err = nvs_set_str(h, "hostname", c->hostname);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "ip_mode", c->use_static ? "static" : "dhcp");
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "ip", c->ip);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "netmask", c->netmask);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "gateway", c->gateway);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "dns", c->dns);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "ap", c->ap_enabled ? "on" : "off");
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "ap_ssid", c->ap_ssid);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "ap_pass", c->ap_pass);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "ddp", c->ddp_enabled ? "on" : "off");
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "espnow", c->espnow_enabled ? "on" : "off");
|
||||||
|
if (err == ESP_OK) err = nvs_set_i64(h, "espnow_ch", c->espnow_channel);
|
||||||
|
if (err == ESP_OK) err = nvs_commit(h);
|
||||||
|
nvs_close(h);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
struct wifi_creds_t {
|
||||||
|
char ssid[33];
|
||||||
|
char pass[65];
|
||||||
|
};
|
||||||
|
|
||||||
|
struct net_cfg_t {
|
||||||
|
char hostname[64]; // mDNS name, without ".local"
|
||||||
|
bool use_static; // false: DHCP on the client interface
|
||||||
|
char ip[16]; // static client address, dotted quad
|
||||||
|
char netmask[16];
|
||||||
|
char gateway[16];
|
||||||
|
char dns[16]; // optional; empty uses the gateway
|
||||||
|
bool ap_enabled; // the access point (led-XXXXXX) is on; default on
|
||||||
|
char ap_ssid[33]; // access point name; empty uses led-XXXXXX from the MAC
|
||||||
|
char ap_pass[65]; // access point password, 8-63 characters (WPA2); empty is an open network
|
||||||
|
bool ddp_enabled; // DDP pixels and frame sync are received; default on
|
||||||
|
bool espnow_enabled; // ESP-NOW link to led-controller (0x4C wire protocol); default on
|
||||||
|
uint8_t espnow_channel; // Wi-Fi channel shared with the controller and its bridge; default 6
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @brief Read saved Wi-Fi client credentials. ESP_ERR_NVS_NOT_FOUND if none are saved. */
|
||||||
|
esp_err_t settings_load_wifi(wifi_creds_t *c);
|
||||||
|
|
||||||
|
/** @brief Save Wi-Fi client credentials to NVS. */
|
||||||
|
esp_err_t settings_save_wifi(const wifi_creds_t *c);
|
||||||
|
|
||||||
|
struct hw_cfg_t {
|
||||||
|
char order[4]; // colour order of the strip: rgb, rbg, grb, gbr, brg or bgr
|
||||||
|
uint8_t max_brightness; // ceiling for every output colour, 0-255
|
||||||
|
int num_leds; // 1-512
|
||||||
|
int pin; // GPIO for the data line
|
||||||
|
uint8_t global_brightness; // this device's own brightness, 0-255 (under max_brightness)
|
||||||
|
uint8_t master_brightness; // master scale for this device, 0-255, set from "All devices"
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @brief Read the LED strip settings. Missing keys get their defaults (grb, 255, 119). */
|
||||||
|
esp_err_t settings_load_hw(hw_cfg_t *c);
|
||||||
|
|
||||||
|
/** @brief Save the LED strip settings. */
|
||||||
|
esp_err_t settings_save_hw(const hw_cfg_t *c);
|
||||||
|
|
||||||
|
/** @brief Read network settings. Missing keys get their defaults (hostname "led", DHCP). */
|
||||||
|
esp_err_t settings_load_net(net_cfg_t *c);
|
||||||
|
|
||||||
|
/** @brief Save network settings to NVS. */
|
||||||
|
esp_err_t settings_save_net(const net_cfg_t *c);
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include <cstdarg>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include "driver/usb_serial_jtag.h"
|
||||||
|
#include "driver/usb_serial_jtag_vfs.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_system.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
#include "usb_cfg.h"
|
||||||
|
#include "web.h"
|
||||||
|
|
||||||
|
static const char *TAG = "usb_cfg";
|
||||||
|
|
||||||
|
static const char API_PREFIX[] = "@api ";
|
||||||
|
static const char REBOOT[] = "@reboot";
|
||||||
|
|
||||||
|
// The driver's TX buffer takes a write whole or not at all, so a long reply goes out in chunks.
|
||||||
|
// Log output takes the same lock (log_vprintf), so no log line can land inside a reply.
|
||||||
|
static SemaphoreHandle_t s_tx_lock;
|
||||||
|
static vprintf_like_t s_log_vprintf;
|
||||||
|
|
||||||
|
static int log_vprintf(const char *fmt, va_list args)
|
||||||
|
{
|
||||||
|
// A log from inside a reply write (none today) would deadlock, so only wait if we don't hold it
|
||||||
|
const bool locked = s_tx_lock && xSemaphoreGetMutexHolder(s_tx_lock) != xTaskGetCurrentTaskHandle()
|
||||||
|
&& xSemaphoreTake(s_tx_lock, portMAX_DELAY) == pdTRUE;
|
||||||
|
int r = s_log_vprintf(fmt, args);
|
||||||
|
if (locked) {
|
||||||
|
fflush(stdout);
|
||||||
|
xSemaphoreGive(s_tx_lock);
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void write_line(const char *s)
|
||||||
|
{
|
||||||
|
static const size_t CHUNK = 256;
|
||||||
|
xSemaphoreTake(s_tx_lock, portMAX_DELAY);
|
||||||
|
fflush(stdout); // finish any log text already in stdio's buffer first
|
||||||
|
for (size_t n = strlen(s); n > 0;) {
|
||||||
|
size_t k = n < CHUNK ? n : CHUNK;
|
||||||
|
if (usb_serial_jtag_write_bytes(s, k, pdMS_TO_TICKS(500)) != (int)k) {
|
||||||
|
break; // no host reading: drop the rest rather than hold up the logs
|
||||||
|
}
|
||||||
|
s += k;
|
||||||
|
n -= k;
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_tx_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
// An "@api" line: run it and send back the envelope, with the request's id added
|
||||||
|
static void handle_api(const char *json, char *reply, size_t cap)
|
||||||
|
{
|
||||||
|
web_api_call(json, reply, cap);
|
||||||
|
|
||||||
|
cJSON *req = cJSON_Parse(json);
|
||||||
|
const cJSON *id = req ? cJSON_GetObjectItem(req, "id") : NULL;
|
||||||
|
cJSON *env = cJSON_Parse(reply);
|
||||||
|
if (!env) {
|
||||||
|
env = cJSON_CreateObject();
|
||||||
|
cJSON_AddNumberToObject(env, "status", 500);
|
||||||
|
cJSON_AddStringToObject(env, "body", "{\"error\":\"reply too large\"}");
|
||||||
|
}
|
||||||
|
if (cJSON_IsNumber(id)) {
|
||||||
|
cJSON_AddNumberToObject(env, "id", id->valuedouble);
|
||||||
|
}
|
||||||
|
char *s = cJSON_PrintUnformatted(env);
|
||||||
|
cJSON_Delete(env);
|
||||||
|
cJSON_Delete(req);
|
||||||
|
if (!s) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
size_t n = strlen(s);
|
||||||
|
// A leading newline ends any log line that was half written, so the reply starts its own line
|
||||||
|
const size_t pre = sizeof(API_PREFIX) - 1;
|
||||||
|
char *line = (char *)malloc(1 + pre + n + 2);
|
||||||
|
if (line) {
|
||||||
|
line[0] = '\n';
|
||||||
|
memcpy(line + 1, API_PREFIX, pre);
|
||||||
|
memcpy(line + 1 + pre, s, n);
|
||||||
|
line[1 + pre + n] = '\n';
|
||||||
|
line[2 + pre + n] = '\0';
|
||||||
|
write_line(line);
|
||||||
|
free(line);
|
||||||
|
}
|
||||||
|
cJSON_free(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handle_line(char *line, char *reply, size_t cap)
|
||||||
|
{
|
||||||
|
size_t n = strlen(line);
|
||||||
|
while (n && (line[n - 1] == '\r' || line[n - 1] == ' ')) {
|
||||||
|
line[--n] = '\0';
|
||||||
|
}
|
||||||
|
if (strncmp(line, API_PREFIX, sizeof(API_PREFIX) - 1) == 0) {
|
||||||
|
handle_api(line + sizeof(API_PREFIX) - 1, reply, cap);
|
||||||
|
} else if (strcmp(line, REBOOT) == 0) {
|
||||||
|
write_line("\n@ok\n");
|
||||||
|
usb_serial_jtag_wait_tx_done(pdMS_TO_TICKS(200));
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(100));
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
// Anything else (a stray keypress in a monitor) is ignored
|
||||||
|
}
|
||||||
|
|
||||||
|
static void usb_cfg_task(void *)
|
||||||
|
{
|
||||||
|
char *line = (char *)malloc(WEB_API_MSG_MAX + 1);
|
||||||
|
char *reply = (char *)malloc(WEB_API_REPLY_MAX);
|
||||||
|
if (!line || !reply) {
|
||||||
|
ESP_LOGE(TAG, "out of memory");
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
size_t len = 0;
|
||||||
|
bool overflow = false; // the current line is too long: drop it up to its newline
|
||||||
|
uint8_t buf[64];
|
||||||
|
for (;;) {
|
||||||
|
int got = usb_serial_jtag_read_bytes(buf, sizeof(buf), portMAX_DELAY);
|
||||||
|
for (int i = 0; i < got; i++) {
|
||||||
|
char c = (char)buf[i];
|
||||||
|
if (c == '\n') {
|
||||||
|
if (!overflow) {
|
||||||
|
line[len] = '\0';
|
||||||
|
handle_line(line, reply, WEB_API_REPLY_MAX);
|
||||||
|
}
|
||||||
|
len = 0;
|
||||||
|
overflow = false;
|
||||||
|
} else if (!overflow) {
|
||||||
|
if (len < WEB_API_MSG_MAX) {
|
||||||
|
line[len++] = c;
|
||||||
|
} else {
|
||||||
|
overflow = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t usb_cfg_start(void)
|
||||||
|
{
|
||||||
|
usb_serial_jtag_driver_config_t cfg = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT();
|
||||||
|
cfg.rx_buffer_size = 1024;
|
||||||
|
cfg.tx_buffer_size = 2048;
|
||||||
|
esp_err_t err = usb_serial_jtag_driver_install(&cfg);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "USB serial driver install failed: %s", esp_err_to_name(err));
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
// Logs go through the driver too, so they and the replies share one queue
|
||||||
|
usb_serial_jtag_vfs_use_driver();
|
||||||
|
s_tx_lock = xSemaphoreCreateMutex();
|
||||||
|
if (!s_tx_lock) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_log_vprintf = esp_log_set_vprintf(log_vprintf);
|
||||||
|
if (xTaskCreate(usb_cfg_task, "usb_cfg", 6144, NULL, 4, NULL) != pdPASS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "Config API on the USB serial port");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Serve the JSON API on the USB serial port (USB-Serial-JTAG), for led-tool.
|
||||||
|
*
|
||||||
|
* One request per line, one reply per line; every other line on the port is log output:
|
||||||
|
* @api {"id": n, "method": "GET" or "POST", "path": "/api/...", "body": ..., "host": optional}
|
||||||
|
* -> @api {"id": n, "status": 200, "body": "<JSON text>"}
|
||||||
|
* @reboot -> @ok, then the device restarts
|
||||||
|
*/
|
||||||
|
esp_err_t usb_cfg_start(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
+1472
File diff suppressed because it is too large.
Load diff
+34
@@ -0,0 +1,34 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
#include "esp_http_server.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define WEB_API_MSG_MAX 2048 // a request message: {"method","path","body","host"}
|
||||||
|
#define WEB_API_REPLY_MAX 16384 // a reply envelope: {"status","body"}
|
||||||
|
|
||||||
|
/** @brief Start the HTTP server on port 80 (UI and JSON API). */
|
||||||
|
esp_err_t web_start(void);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Add Access-Control-Allow-Origin for a LAN or localhost page that asked (the Origin header).
|
||||||
|
* Call before the response is sent. Other origins get no header, so the browser blocks them.
|
||||||
|
*/
|
||||||
|
void web_allow_lan_origin(httpd_req_t *req);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Run one API request without HTTP, as the WebSocket does: msg is
|
||||||
|
* {"method": "GET" or "POST", "path": "/api/...", "body": ..., "host": optional relay target}.
|
||||||
|
* out gets the envelope {"status": n, "body": "<JSON text>"}. Used by the USB config port.
|
||||||
|
*/
|
||||||
|
void web_api_call(const char *msg, char *out, size_t cap);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
+258
@@ -0,0 +1,258 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include "ws2812.h"
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "esp_check.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
|
||||||
|
static const char *TAG = "ws2812";
|
||||||
|
|
||||||
|
/* ---- RMT encoder: turns RGB bytes into WS2812 waveform symbols ---- */
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
rmt_encoder_t base;
|
||||||
|
rmt_encoder_t *bytes_encoder;
|
||||||
|
rmt_encoder_t *copy_encoder;
|
||||||
|
int state;
|
||||||
|
rmt_symbol_word_t reset_code;
|
||||||
|
} rmt_ws2812_encoder_t;
|
||||||
|
|
||||||
|
RMT_ENCODER_FUNC_ATTR
|
||||||
|
static size_t rmt_encode_ws2812(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state)
|
||||||
|
{
|
||||||
|
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
|
||||||
|
rmt_encoder_handle_t bytes_encoder = led_encoder->bytes_encoder;
|
||||||
|
rmt_encoder_handle_t copy_encoder = led_encoder->copy_encoder;
|
||||||
|
rmt_encode_state_t session_state = RMT_ENCODING_RESET;
|
||||||
|
rmt_encode_state_t state = RMT_ENCODING_RESET;
|
||||||
|
size_t encoded_symbols = 0;
|
||||||
|
switch (led_encoder->state) {
|
||||||
|
case 0: // send RGB data
|
||||||
|
encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, primary_data, data_size, &session_state);
|
||||||
|
if (session_state & RMT_ENCODING_COMPLETE) {
|
||||||
|
led_encoder->state = 1; // switch to next state when current encoding session finished
|
||||||
|
}
|
||||||
|
if (session_state & RMT_ENCODING_MEM_FULL) {
|
||||||
|
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_MEM_FULL);
|
||||||
|
goto out; // yield if there's no free space for encoding artifacts
|
||||||
|
}
|
||||||
|
// fall-through
|
||||||
|
case 1: // send reset code
|
||||||
|
encoded_symbols += copy_encoder->encode(copy_encoder, channel, &led_encoder->reset_code,
|
||||||
|
sizeof(led_encoder->reset_code), &session_state);
|
||||||
|
if (session_state & RMT_ENCODING_COMPLETE) {
|
||||||
|
led_encoder->state = RMT_ENCODING_RESET; // back to the initial encoding session
|
||||||
|
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_COMPLETE);
|
||||||
|
}
|
||||||
|
if (session_state & RMT_ENCODING_MEM_FULL) {
|
||||||
|
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_MEM_FULL);
|
||||||
|
goto out; // yield if there's no free space for encoding artifacts
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out:
|
||||||
|
*ret_state = state;
|
||||||
|
return encoded_symbols;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t rmt_del_ws2812_encoder(rmt_encoder_t *encoder)
|
||||||
|
{
|
||||||
|
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
|
||||||
|
rmt_del_encoder(led_encoder->bytes_encoder);
|
||||||
|
rmt_del_encoder(led_encoder->copy_encoder);
|
||||||
|
free(led_encoder);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
RMT_ENCODER_FUNC_ATTR
|
||||||
|
static esp_err_t rmt_ws2812_encoder_reset(rmt_encoder_t *encoder)
|
||||||
|
{
|
||||||
|
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
|
||||||
|
rmt_encoder_reset(led_encoder->bytes_encoder);
|
||||||
|
rmt_encoder_reset(led_encoder->copy_encoder);
|
||||||
|
led_encoder->state = RMT_ENCODING_RESET;
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
static esp_err_t new_ws2812_encoder(uint32_t resolution, rmt_encoder_handle_t *ret_encoder)
|
||||||
|
{
|
||||||
|
// Declared up front: the error path jumps forward to `err`, which C++ forbids
|
||||||
|
// across initialised declarations.
|
||||||
|
esp_err_t ret = ESP_OK;
|
||||||
|
rmt_ws2812_encoder_t *led_encoder = NULL;
|
||||||
|
rmt_bytes_encoder_config_t bytes_encoder_config = {};
|
||||||
|
rmt_copy_encoder_config_t copy_encoder_config = {};
|
||||||
|
uint32_t reset_ticks = 0;
|
||||||
|
|
||||||
|
ESP_GOTO_ON_FALSE(ret_encoder, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument");
|
||||||
|
led_encoder = static_cast<rmt_ws2812_encoder_t *>(rmt_alloc_encoder_mem(sizeof(rmt_ws2812_encoder_t)));
|
||||||
|
ESP_GOTO_ON_FALSE(led_encoder, ESP_ERR_NO_MEM, err, TAG, "no mem for ws2812 encoder");
|
||||||
|
led_encoder->base.encode = rmt_encode_ws2812;
|
||||||
|
led_encoder->base.del = rmt_del_ws2812_encoder;
|
||||||
|
led_encoder->base.reset = rmt_ws2812_encoder_reset;
|
||||||
|
|
||||||
|
// WS2812 timing
|
||||||
|
bytes_encoder_config.bit0.level0 = 1;
|
||||||
|
bytes_encoder_config.bit0.duration0 = 0.3 * resolution / 1000000; // T0H=0.3us
|
||||||
|
bytes_encoder_config.bit0.level1 = 0;
|
||||||
|
bytes_encoder_config.bit0.duration1 = 0.9 * resolution / 1000000; // T0L=0.9us
|
||||||
|
bytes_encoder_config.bit1.level0 = 1;
|
||||||
|
bytes_encoder_config.bit1.duration0 = 0.9 * resolution / 1000000; // T1H=0.9us
|
||||||
|
bytes_encoder_config.bit1.level1 = 0;
|
||||||
|
bytes_encoder_config.bit1.duration1 = 0.3 * resolution / 1000000; // T1L=0.3us
|
||||||
|
bytes_encoder_config.flags.msb_first = 1; // WS2812 transfer bit order: G7...G0R7...R0B7...B0
|
||||||
|
ESP_GOTO_ON_ERROR(rmt_new_bytes_encoder(&bytes_encoder_config, &led_encoder->bytes_encoder), err, TAG, "create bytes encoder failed");
|
||||||
|
ESP_GOTO_ON_ERROR(rmt_new_copy_encoder(©_encoder_config, &led_encoder->copy_encoder), err, TAG, "create copy encoder failed");
|
||||||
|
|
||||||
|
reset_ticks = resolution / 1000000 * 50 / 2; // reset code duration defaults to 50us
|
||||||
|
led_encoder->reset_code.level0 = 0;
|
||||||
|
led_encoder->reset_code.duration0 = reset_ticks;
|
||||||
|
led_encoder->reset_code.level1 = 0;
|
||||||
|
led_encoder->reset_code.duration1 = reset_ticks;
|
||||||
|
|
||||||
|
*ret_encoder = &led_encoder->base;
|
||||||
|
return ESP_OK;
|
||||||
|
err:
|
||||||
|
if (led_encoder) {
|
||||||
|
if (led_encoder->bytes_encoder) {
|
||||||
|
rmt_del_encoder(led_encoder->bytes_encoder);
|
||||||
|
}
|
||||||
|
if (led_encoder->copy_encoder) {
|
||||||
|
rmt_del_encoder(led_encoder->copy_encoder);
|
||||||
|
}
|
||||||
|
free(led_encoder);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- WS2812 strip ---- */
|
||||||
|
|
||||||
|
WS2812::WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz)
|
||||||
|
: num_leds_(num_leds), pixels_(num_leds * 3, 0), tx_pixels_(num_leds * 3, 0)
|
||||||
|
{
|
||||||
|
rmt_tx_channel_config_t tx_chan_config = {};
|
||||||
|
tx_chan_config.clk_src = RMT_CLK_SRC_DEFAULT;
|
||||||
|
tx_chan_config.gpio_num = gpio;
|
||||||
|
tx_chan_config.mem_block_symbols = 64; // larger blocks reduce flicker
|
||||||
|
tx_chan_config.resolution_hz = resolution_hz;
|
||||||
|
tx_chan_config.trans_queue_depth = 4;
|
||||||
|
ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &channel_));
|
||||||
|
|
||||||
|
ESP_ERROR_CHECK(new_ws2812_encoder(resolution_hz, &encoder_));
|
||||||
|
|
||||||
|
ESP_ERROR_CHECK(rmt_enable(channel_));
|
||||||
|
tx_config_.loop_count = 0; // send once per write()
|
||||||
|
|
||||||
|
ESP_LOGI(TAG, "Strip ready: %zu LEDs on GPIO %d", num_leds_, (int)gpio);
|
||||||
|
}
|
||||||
|
|
||||||
|
WS2812::~WS2812()
|
||||||
|
{
|
||||||
|
if (channel_) {
|
||||||
|
rmt_tx_wait_all_done(channel_, portMAX_DELAY);
|
||||||
|
rmt_disable(channel_);
|
||||||
|
rmt_del_channel(channel_);
|
||||||
|
}
|
||||||
|
if (encoder_) {
|
||||||
|
encoder_->del(encoder_);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void WS2812::set(size_t index, uint8_t r, uint8_t g, uint8_t b)
|
||||||
|
{
|
||||||
|
if (index >= num_leds_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint8_t *p = &pixels_[index * 3];
|
||||||
|
uint8_t c[3] = { r, g, b };
|
||||||
|
p[0] = c[order_[0]];
|
||||||
|
p[1] = c[order_[1]];
|
||||||
|
p[2] = c[order_[2]];
|
||||||
|
}
|
||||||
|
|
||||||
|
void WS2812::setOrder(const char *order)
|
||||||
|
{
|
||||||
|
if (!order || strlen(order) != 3) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint8_t idx[3];
|
||||||
|
for (int i = 0; i < 3; i++) {
|
||||||
|
switch (order[i]) {
|
||||||
|
case 'r': idx[i] = 0; break;
|
||||||
|
case 'g': idx[i] = 1; break;
|
||||||
|
case 'b': idx[i] = 2; break;
|
||||||
|
default: return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (idx[0] == idx[1] || idx[1] == idx[2] || idx[0] == idx[2]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
memcpy(order_, idx, sizeof(order_));
|
||||||
|
}
|
||||||
|
|
||||||
|
void WS2812::fill(uint8_t r, uint8_t g, uint8_t b)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < num_leds_; i++) {
|
||||||
|
set(i, r, g, b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t WS2812::write()
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < pixels_.size(); i++) {
|
||||||
|
tx_pixels_[i] = static_cast<uint8_t>(pixels_[i] * brightness_ / 255);
|
||||||
|
}
|
||||||
|
esp_err_t ret = rmt_transmit(channel_, encoder_, tx_pixels_.data(), tx_pixels_.size(), &tx_config_);
|
||||||
|
if (ret != ESP_OK) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
return rmt_tx_wait_all_done(channel_, portMAX_DELAY);
|
||||||
|
}
|
||||||
|
|
||||||
|
void WS2812::hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b)
|
||||||
|
{
|
||||||
|
h %= 360; // h -> [0,360]
|
||||||
|
uint32_t rgb_max = v * 2.55f;
|
||||||
|
uint32_t rgb_min = rgb_max * (100 - s) / 100.0f;
|
||||||
|
|
||||||
|
uint32_t i = h / 60;
|
||||||
|
uint32_t diff = h % 60;
|
||||||
|
|
||||||
|
// RGB adjustment amount by hue
|
||||||
|
uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60;
|
||||||
|
|
||||||
|
switch (i) {
|
||||||
|
case 0:
|
||||||
|
*r = rgb_max;
|
||||||
|
*g = rgb_min + rgb_adj;
|
||||||
|
*b = rgb_min;
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
*r = rgb_max - rgb_adj;
|
||||||
|
*g = rgb_max;
|
||||||
|
*b = rgb_min;
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
*r = rgb_min;
|
||||||
|
*g = rgb_max;
|
||||||
|
*b = rgb_min + rgb_adj;
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
*r = rgb_min;
|
||||||
|
*g = rgb_max - rgb_adj;
|
||||||
|
*b = rgb_max;
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
*r = rgb_min + rgb_adj;
|
||||||
|
*g = rgb_min;
|
||||||
|
*b = rgb_max;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
*r = rgb_max;
|
||||||
|
*g = rgb_min;
|
||||||
|
*b = rgb_max - rgb_adj;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "driver/gpio.h"
|
||||||
|
#include "driver/rmt_encoder.h"
|
||||||
|
#include "driver/rmt_tx.h"
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief WS2812-style addressable LED strip driven through the RMT peripheral.
|
||||||
|
*
|
||||||
|
* Pixel data is kept in a local buffer. set() and fill() only update that buffer;
|
||||||
|
* call write() to push the buffer out to the strip.
|
||||||
|
*/
|
||||||
|
class WS2812 {
|
||||||
|
public:
|
||||||
|
/**
|
||||||
|
* @param gpio GPIO connected to the strip's data input (DI)
|
||||||
|
* @param num_leds Number of LEDs in the strip
|
||||||
|
* @param resolution_hz RMT tick resolution; 10 MHz gives 0.1 us ticks, which WS2812 needs
|
||||||
|
*/
|
||||||
|
WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz = 10000000);
|
||||||
|
~WS2812();
|
||||||
|
|
||||||
|
WS2812(const WS2812 &) = delete;
|
||||||
|
WS2812 &operator=(const WS2812 &) = delete;
|
||||||
|
|
||||||
|
/** @brief Set one pixel in the buffer. Out-of-range indices are ignored. */
|
||||||
|
void set(size_t index, uint8_t r, uint8_t g, uint8_t b);
|
||||||
|
|
||||||
|
/** @brief Set every pixel in the buffer to the same colour. */
|
||||||
|
void fill(uint8_t r, uint8_t g, uint8_t b);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Transmit the buffer to the strip and wait until the transfer finishes.
|
||||||
|
* @return ESP_OK on success, or an error from the RMT driver.
|
||||||
|
*/
|
||||||
|
esp_err_t write();
|
||||||
|
|
||||||
|
/** @brief Number of LEDs in the strip. */
|
||||||
|
size_t size() const { return num_leds_; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Set the output brightness, 0 (off) to 255 (full). Applied in write();
|
||||||
|
* the pixel buffer keeps its full-colour values. Defaults to 255.
|
||||||
|
*/
|
||||||
|
void setBrightness(uint8_t level) { brightness_ = level; }
|
||||||
|
|
||||||
|
/** @brief Current output brightness, 0-255. */
|
||||||
|
uint8_t brightness() const { return brightness_; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Convert HSV to RGB.
|
||||||
|
*
|
||||||
|
* h is the hue in degrees (wrapped to [0, 360)); s and v are 0-100 percent.
|
||||||
|
* Wiki: https://en.wikipedia.org/wiki/HSL_and_HSV
|
||||||
|
*/
|
||||||
|
static void hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Byte order of the strip, as the letters of the colours in the order they are sent.
|
||||||
|
* "grb" (the default) is the WS2812 norm; "rgb", "rbg", "gbr", "brg" and "bgr" cover the rest.
|
||||||
|
* Unknown names keep the current order.
|
||||||
|
*/
|
||||||
|
void setOrder(const char *order);
|
||||||
|
|
||||||
|
private:
|
||||||
|
size_t num_leds_;
|
||||||
|
uint8_t order_[3] = { 1, 0, 2 }; // indices into (r, g, b) for each byte sent: GRB
|
||||||
|
std::vector<uint8_t> pixels_; // 3 bytes per LED, in the strip's byte order
|
||||||
|
std::vector<uint8_t> tx_pixels_; // pixels_ scaled by brightness_, sent by write()
|
||||||
|
uint8_t brightness_ = 255;
|
||||||
|
rmt_channel_handle_t channel_ = nullptr;
|
||||||
|
rmt_encoder_handle_t encoder_ = nullptr;
|
||||||
|
rmt_transmit_config_t tx_config_ = {};
|
||||||
|
};
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include "ws_client.h"
|
||||||
|
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_random.h"
|
||||||
|
#include "lwip/netdb.h"
|
||||||
|
#include "lwip/sockets.h"
|
||||||
|
|
||||||
|
static const char *TAG = "ws_client";
|
||||||
|
#define WS_TIMEOUT_MS 2000
|
||||||
|
|
||||||
|
// Read until the buffer holds the end of the handshake reply. Returns the bytes read, or -1.
|
||||||
|
static int read_handshake(int fd, char *buf, size_t cap)
|
||||||
|
{
|
||||||
|
size_t got = 0;
|
||||||
|
while (got < cap - 1) {
|
||||||
|
int r = recv(fd, buf + got, cap - 1 - got, 0);
|
||||||
|
if (r <= 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
got += r;
|
||||||
|
buf[got] = '\0';
|
||||||
|
if (strstr(buf, "\r\n\r\n")) {
|
||||||
|
return (int)got;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ws_client_connect(const char *host, const char *path)
|
||||||
|
{
|
||||||
|
struct addrinfo hints = {};
|
||||||
|
struct addrinfo *res = NULL;
|
||||||
|
hints.ai_family = AF_INET;
|
||||||
|
hints.ai_socktype = SOCK_STREAM;
|
||||||
|
if (getaddrinfo(host, "80", &hints, &res) != 0 || !res) {
|
||||||
|
ESP_LOGW(TAG, "cannot resolve %s", host);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int fd = socket(res->ai_family, res->ai_socktype, 0);
|
||||||
|
if (fd < 0) {
|
||||||
|
freeaddrinfo(res);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
struct timeval tv = { .tv_sec = WS_TIMEOUT_MS / 1000, .tv_usec = (WS_TIMEOUT_MS % 1000) * 1000 };
|
||||||
|
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||||
|
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||||||
|
int one = 1;
|
||||||
|
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); // one frame, one segment
|
||||||
|
if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
|
||||||
|
freeaddrinfo(res);
|
||||||
|
close(fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
freeaddrinfo(res);
|
||||||
|
|
||||||
|
char req[256];
|
||||||
|
int n = snprintf(req, sizeof(req),
|
||||||
|
"GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
|
||||||
|
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n",
|
||||||
|
path, host);
|
||||||
|
if (n <= 0 || send(fd, req, n, 0) != n) {
|
||||||
|
close(fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
char reply[256];
|
||||||
|
if (read_handshake(fd, reply, sizeof(reply)) < 0 || strncmp(reply, "HTTP/1.1 101", 12) != 0) {
|
||||||
|
ESP_LOGW(TAG, "handshake with %s failed", host);
|
||||||
|
close(fd);
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client frames are masked (RFC 6455). The mask only has to vary, not be secret.
|
||||||
|
esp_err_t ws_client_send_text(int fd, const char *data, size_t len)
|
||||||
|
{
|
||||||
|
if (len > 2048) {
|
||||||
|
return ESP_ERR_INVALID_SIZE;
|
||||||
|
}
|
||||||
|
size_t hdr = len < 126 ? 2 : 4; // 2-byte or 16-bit length
|
||||||
|
size_t total = hdr + 4 + len;
|
||||||
|
uint8_t *frame = (uint8_t *)malloc(total);
|
||||||
|
if (!frame) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
uint8_t mask[4];
|
||||||
|
esp_fill_random(mask, sizeof(mask));
|
||||||
|
frame[0] = 0x81; // FIN, text
|
||||||
|
if (len < 126) {
|
||||||
|
frame[1] = 0x80 | (uint8_t)len;
|
||||||
|
} else {
|
||||||
|
frame[1] = 0x80 | 126;
|
||||||
|
frame[2] = (uint8_t)(len >> 8);
|
||||||
|
frame[3] = (uint8_t)len;
|
||||||
|
}
|
||||||
|
memcpy(&frame[hdr], mask, 4);
|
||||||
|
for (size_t i = 0; i < len; i++) {
|
||||||
|
frame[hdr + 4 + i] = (uint8_t)data[i] ^ mask[i & 3];
|
||||||
|
}
|
||||||
|
esp_err_t err = send(fd, frame, total, 0) == (ssize_t)total ? ESP_OK : ESP_FAIL;
|
||||||
|
free(frame);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read exactly n bytes
|
||||||
|
static bool read_n(int fd, uint8_t *dst, size_t n)
|
||||||
|
{
|
||||||
|
size_t got = 0;
|
||||||
|
while (got < n) {
|
||||||
|
int r = recv(fd, dst + got, n - got, 0);
|
||||||
|
if (r <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
got += r;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server frames are not masked. Only text frames are returned; other opcodes are skipped.
|
||||||
|
int ws_client_recv_text(int fd, char *buf, size_t cap)
|
||||||
|
{
|
||||||
|
for (;;) {
|
||||||
|
uint8_t h[2];
|
||||||
|
if (!read_n(fd, h, 2)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
size_t len = h[1] & 0x7F;
|
||||||
|
if (len == 126) {
|
||||||
|
uint8_t ext[2];
|
||||||
|
if (!read_n(fd, ext, 2)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
len = (ext[0] << 8) | ext[1];
|
||||||
|
} else if (len == 127) {
|
||||||
|
return -1; // larger than this client accepts
|
||||||
|
}
|
||||||
|
bool masked = (h[1] & 0x80) != 0;
|
||||||
|
uint8_t mask[4] = {};
|
||||||
|
if (masked && !read_n(fd, mask, 4)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if (len >= cap) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if (!read_n(fd, (uint8_t *)buf, len)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
for (size_t i = 0; masked && i < len; i++) {
|
||||||
|
buf[i] ^= mask[i & 3];
|
||||||
|
}
|
||||||
|
if ((h[0] & 0x0F) == 0x1) { // text
|
||||||
|
buf[len] = '\0';
|
||||||
|
return (int)len;
|
||||||
|
}
|
||||||
|
if ((h[0] & 0x0F) == 0x8) { // close
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ws_client_close(int fd)
|
||||||
|
{
|
||||||
|
if (fd >= 0) {
|
||||||
|
close(fd);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Minimal WebSocket client for talking to another driver. One connection is kept open per peer.
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
/** @brief Open (or reuse) a WebSocket to host:/ws. Returns the socket, or -1. */
|
||||||
|
int ws_client_connect(const char *host, const char *path);
|
||||||
|
|
||||||
|
/** @brief Send one text frame. */
|
||||||
|
esp_err_t ws_client_send_text(int fd, const char *data, size_t len);
|
||||||
|
|
||||||
|
/** @brief Receive one text frame into buf (NUL-terminated). Returns the length, or -1 on error. */
|
||||||
|
int ws_client_recv_text(int fd, char *buf, size_t cap);
|
||||||
|
|
||||||
|
/** @brief Close a socket from ws_client_connect. */
|
||||||
|
void ws_client_close(int fd);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
e788323270d90738662d66fffa910bfe1fba019bba087f01557e70c40485b469
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"version":"1.0","algorithm":"sha256","created_at":"2026-03-30T15:24:33.754457+00:00","files":[{"path":"CMakeLists.txt","size":299,"hash":"ed52bedef7b81ab94f0229eb17680e1c90de6776110e2d24a1ff12fd4b4a4d8d"},{"path":"Kconfig","size":763,"hash":"b6b494bf761d2a358abc941fcba2b9a2bd961ccf4dd6a5cedaf7cde19830003c"},{"path":"LICENSE","size":1084,"hash":"a36dda207c36db5818729c54e7ad4e8b0c6fba847491ba64f372c1a2037b6d5c"},{"path":"README.md","size":27630,"hash":"a3947fea0e24b4069f93a5379e2fb3103b48c339c1dd4368f714469fa8da4904"},{"path":"idf_component.yml","size":331,"hash":"8cf02081bf037b8d0b89e613f5803d463d4a93d2eab892c4bbe20020cdbd4396"},{"path":"sbom_cJSON.yml","size":313,"hash":"a47df162c2671b1f4bc79a84875ba5e2cc2021c5cb73a60150951c1c16265e3d"},{"path":"cJSON/.editorconfig","size":428,"hash":"b2b78dbe3b29690f9ac605b0c6d998ca25e89d578198d3cba935cd66c94dede1"},{"path":"cJSON/.git","size":39,"hash":"2af511596d328b1e545b079746663861fe439d64f4f7bac297cbd22dce46a4f4"},{"path":"cJSON/.gitattributes","size":340,"hash":"51901378d0408db37a541af075c3673f919feb8c50dc4fb077e31d086fcf3f3b"},{"path":"cJSON/.gitignore","size":171,"hash":"c894dad853994898d6328bfee88fb6e4a01ad15ec587c66d149841acdeb7716d"},{"path":"cJSON/.travis.yml","size":602,"hash":"5e0eb8ed93a5e590ce7e72a6fe26db8df20804e872ea253254f46dfe29ac5fe2"},{"path":"cJSON/CHANGELOG.md","size":25980,"hash":"adec9eeee3c855842a770e75f2b4538a3bb21cc998d832395fff361dbd21d316"},{"path":"cJSON/CMakeLists.txt","size":10205,"hash":"160c8e123cdc5fa89edbb3866eeaa17a7a40503985b26f8ffc6d3f92ab6c4763"},{"path":"cJSON/CONTRIBUTORS.md","size":4131,"hash":"48b3c704097b40d9ef908db883001041bafd051b4d2787957438f2a71f7fb63c"},{"path":"cJSON/LICENSE","size":1084,"hash":"a36dda207c36db5818729c54e7ad4e8b0c6fba847491ba64f372c1a2037b6d5c"},{"path":"cJSON/Makefile","size":4650,"hash":"410bdeb55e6b8ecd49a6d34f61ce53e2e7643136c8aebe148ba1baa28c505b94"},{"path":"cJSON/README.md","size":27630,"hash":"a3947fea0e24b4069f93a5379e2fb3103b48c339c1dd4368f714469fa8da4904"},{"path":"cJSON/SECURITY.md","size":713,"hash":"213c3a4c10fb81ba6b431ab259513c262023685191d6a6be2cca0b39ce6fd1e0"},{"path":"cJSON/appveyor.yml","size":2284,"hash":"48e9f4f585df68114d2213b6f9113d7d32ec3626689a90dfb63a2450d72b7509"},{"path":"cJSON/cJSON.c","size":80692,"hash":"607e756460fa0de37d20a7a9181f2de29c97bfb7ce5a0e6c2f548243836cd852"},{"path":"cJSON/cJSON.h","size":16394,"hash":"25b0145150d500498e4d209cec69c18c42cf818bffcc54690be3b895a2a16dee"},{"path":"cJSON/cJSON_Utils.c","size":40736,"hash":"bf3092696763a9a446c39365d7c35f23e5acfdca1bd1da33ef66c1161f9243e9"},{"path":"cJSON/cJSON_Utils.h","size":3938,"hash":"1050a7cce8ffe352c509e0c1faad505b9b8a09cac3a1c45c544447868e05f3b5"},{"path":"cJSON/test.c","size":7711,"hash":"9073e70d626d83f202768c3a486aa5496ac33277b7f265fdba200888fc93941e"},{"path":"cJSON/valgrind.supp","size":61,"hash":"5f721f7cff3acb7712af9836cdec19b7f352b851d73829b8e37e994e6f513ec1"},{"path":"cJSON/fuzzing/.gitignore","size":10,"hash":"95b6e450406b13395e5e449b105b785a42c1c67d439762d5ba1b8fbd8dad9419"},{"path":"cJSON/fuzzing/CMakeLists.txt","size":1169,"hash":"80a356c8ad968c1f88498d89e263a20f46765b8fb343f2b82c290e2fbf8f7065"},{"path":"cJSON/fuzzing/afl-prepare-linux.sh","size":153,"hash":"c86a6dfee8758becb7e44e184a429225f1e99ea705b28fcf37a24f7327a06170"},{"path":"cJSON/fuzzing/afl.c","size":4192,"hash":"179261ee7e9a55e1bd1609bbe9f1995f17e6a5e1611378abed85b4eddb1cdd31"},{"path":"cJSON/fuzzing/afl.sh","size":192,"hash":"9614b91989583e8fe2e1961b56b47e660ff053dfccb9b28ecf221320c207b3b5"},{"path":"cJSON/fuzzing/cjson_read_fuzzer.c","size":1695,"hash":"a8e9443438bfb323dcaed5af86dfc3fae7dfbc970a992b0af569a58e1b8c9376"},{"path":"cJSON/fuzzing/fuzz_main.c","size":992,"hash":"880426b8d17e75f41157f0b06d26716d99801b3f9578245183cd4bf718c8c882"},{"path":"cJSON/fuzzing/json.dict","size":914,"hash":"715638fc7ae17e2fad98c7f5db17e5834f134e9aa03fe7e89d6c9816646ff12e"},{"path":"cJSON/fuzzing/ossfuzz.sh","size":529,"hash":"a832e5c52839fa54637b052d3cfd9f63da8deb66f3ea6890af3adf4ff6557927"},{"path":"cJSON/library_config/cJSONConfig.cmake.in","size":802,"hash":"ce9b592eae998427aad7b506e4a7661db303ef038c524f2fcc7ba56319a26c65"},{"path":"cJSON/library_config/cJSONConfigVersion.cmake.in","size":379,"hash":"8a8e1a78f45a121db7732cd81800530b82fc5ace4cd410aa401ade6aa49315af"},{"path":"cJSON/library_config/libcjson.pc.in","size":304,"hash":"051388ae79065c08400dae18cfedf32abbaa34b6a4db9cf547d8db2ff5b04b9b"},{"path":"cJSON/library_config/libcjson_utils.pc.in","size":351,"hash":"9df4bd96583141c2b735b3215d0fb66c0d28364b39278de41ef676c0b27beb68"},{"path":"cJSON/library_config/uninstall.cmake","size":726,"hash":"3b0cf68d1babfb6a72ea673ef24276795c062432c785a0de77fb69ff11145124"},{"path":"cJSON/tests/CMakeLists.txt","size":4530,"hash":"4f98fd9f350148ca49e7f0c3a41875288ed67ae63694add225b01144fd40856d"},{"path":"cJSON/tests/cjson_add.c","size":12774,"hash":"4b9bf117c07e2be9d1ce5db32a63f57e479369516f97a91b5f4d6c8aaccff30e"},{"path":"cJSON/tests/common.h","size":4166Line truncated
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
idf_component_register(SRCS "cJSON/cJSON.c"
|
||||||
|
"cJSON/cJSON_Utils.c"
|
||||||
|
INCLUDE_DIRS "cJSON")
|
||||||
|
|
||||||
|
target_compile_definitions(${COMPONENT_LIB} PUBLIC
|
||||||
|
CJSON_NESTING_LIMIT=${CONFIG_CJSON_NESTING_LIMIT}
|
||||||
|
CJSON_CIRCULAR_LIMIT=${CONFIG_CJSON_CIRCULAR_LIMIT})
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
menu "cJSON"
|
||||||
|
|
||||||
|
config CJSON_NESTING_LIMIT
|
||||||
|
int "Maximum nesting depth for JSON parsing"
|
||||||
|
default 1000
|
||||||
|
help
|
||||||
|
Limits how deeply nested arrays/objects can be before cJSON
|
||||||
|
rejects to parse them. This is to prevent stack overflows.
|
||||||
|
Lower values use less stack, higher values allow deeper nesting.
|
||||||
|
|
||||||
|
config CJSON_CIRCULAR_LIMIT
|
||||||
|
int "Maximum depth for circular reference detection"
|
||||||
|
default 10000
|
||||||
|
help
|
||||||
|
Limits the depth for circular reference detection during
|
||||||
|
printing/comparison operations. This prevents infinite loops
|
||||||
|
and stack overflows when processing JSON structures with
|
||||||
|
circular references. Lower values use less stack.
|
||||||
|
|
||||||
|
endmenu
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
@@ -0,0 +1,590 @@
|
|||||||
|
# cJSON
|
||||||
|
|
||||||
|
Ultralightweight JSON parser in ANSI C.
|
||||||
|
|
||||||
|
## Table of contents
|
||||||
|
* [License](#license)
|
||||||
|
* [Usage](#usage)
|
||||||
|
* [Welcome to cJSON](#welcome-to-cjson)
|
||||||
|
* [Building](#building)
|
||||||
|
* [Copying the source](#copying-the-source)
|
||||||
|
* [CMake](#cmake)
|
||||||
|
* [Makefile](#makefile)
|
||||||
|
* [Meson](#meson)
|
||||||
|
* [Vcpkg](#Vcpkg)
|
||||||
|
* [Including cJSON](#including-cjson)
|
||||||
|
* [Data Structure](#data-structure)
|
||||||
|
* [Working with the data structure](#working-with-the-data-structure)
|
||||||
|
* [Basic types](#basic-types)
|
||||||
|
* [Arrays](#arrays)
|
||||||
|
* [Objects](#objects)
|
||||||
|
* [Parsing JSON](#parsing-json)
|
||||||
|
* [Printing JSON](#printing-json)
|
||||||
|
* [Example](#example)
|
||||||
|
* [Printing](#printing)
|
||||||
|
* [Parsing](#parsing)
|
||||||
|
* [Caveats](#caveats)
|
||||||
|
* [Zero Character](#zero-character)
|
||||||
|
* [Character Encoding](#character-encoding)
|
||||||
|
* [C Standard](#c-standard)
|
||||||
|
* [Floating Point Numbers](#floating-point-numbers)
|
||||||
|
* [Deep Nesting Of Arrays And Objects](#deep-nesting-of-arrays-and-objects)
|
||||||
|
* [Thread Safety](#thread-safety)
|
||||||
|
* [Case Sensitivity](#case-sensitivity)
|
||||||
|
* [Duplicate Object Members](#duplicate-object-members)
|
||||||
|
* [Enjoy cJSON!](#enjoy-cjson)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
> Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||||
|
>
|
||||||
|
> 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.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Welcome to cJSON.
|
||||||
|
|
||||||
|
cJSON aims to be the dumbest possible parser that you can get your job done with.
|
||||||
|
It's a single file of C, and a single header file.
|
||||||
|
|
||||||
|
JSON is described best here: http://www.json.org/
|
||||||
|
It's like XML, but fat-free. You use it to move data around, store things, or just
|
||||||
|
generally represent your program's state.
|
||||||
|
|
||||||
|
As a library, cJSON exists to take away as much legwork as it can, but not get in your way.
|
||||||
|
As a point of pragmatism (i.e. ignoring the truth), I'm going to say that you can use it
|
||||||
|
in one of two modes: Auto and Manual. Let's have a quick run-through.
|
||||||
|
|
||||||
|
I lifted some JSON from this page: http://www.json.org/fatfree.html
|
||||||
|
That page inspired me to write cJSON, which is a parser that tries to share the same
|
||||||
|
philosophy as JSON itself. Simple, dumb, out of the way.
|
||||||
|
|
||||||
|
### Building
|
||||||
|
|
||||||
|
There are several ways to incorporate cJSON into your project.
|
||||||
|
|
||||||
|
#### copying the source
|
||||||
|
|
||||||
|
Because the entire library is only one C file and one header file, you can just copy `cJSON.h` and `cJSON.c` to your projects source and start using it.
|
||||||
|
|
||||||
|
cJSON is written in ANSI C (C89) in order to support as many platforms and compilers as possible.
|
||||||
|
|
||||||
|
#### CMake
|
||||||
|
|
||||||
|
With CMake, cJSON supports a full blown build system. This way you get the most features. CMake with an equal or higher version than 3.5 is supported. With CMake it is recommended to do an out of tree build, meaning the compiled files are put in a directory separate from the source files. So in order to build cJSON with CMake on a Unix platform, make a `build` directory and run CMake inside it.
|
||||||
|
|
||||||
|
```
|
||||||
|
mkdir build
|
||||||
|
cd build
|
||||||
|
cmake ..
|
||||||
|
```
|
||||||
|
|
||||||
|
This will create a Makefile and a bunch of other files. You can then compile it:
|
||||||
|
|
||||||
|
```
|
||||||
|
make
|
||||||
|
```
|
||||||
|
|
||||||
|
And install it with `make install` if you want. By default it installs the headers `/usr/local/include/cjson` and the libraries to `/usr/local/lib`. It also installs files for pkg-config to make it easier to detect and use an existing installation of CMake. And it installs CMake config files, that can be used by other CMake based projects to discover the library.
|
||||||
|
|
||||||
|
You can change the build process with a list of different options that you can pass to CMake. Turn them on with `On` and off with `Off`:
|
||||||
|
|
||||||
|
* `-DENABLE_CJSON_TEST=On`: Enable building the tests. (on by default)
|
||||||
|
* `-DENABLE_CJSON_UTILS=On`: Enable building cJSON_Utils. (off by default)
|
||||||
|
* `-DENABLE_TARGET_EXPORT=On`: Enable the export of CMake targets. Turn off if it makes problems. (on by default)
|
||||||
|
* `-DENABLE_CUSTOM_COMPILER_FLAGS=On`: Enable custom compiler flags (currently for Clang, GCC and MSVC). Turn off if it makes problems. (on by default)
|
||||||
|
* `-DENABLE_VALGRIND=On`: Run tests with [valgrind](http://valgrind.org). (off by default)
|
||||||
|
* `-DENABLE_SANITIZERS=On`: Compile cJSON with [AddressSanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer) and [UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) enabled (if possible). (off by default)
|
||||||
|
* `-DENABLE_SAFE_STACK`: Enable the [SafeStack](https://clang.llvm.org/docs/SafeStack.html) instrumentation pass. Currently only works with the Clang compiler. (off by default)
|
||||||
|
* `-DBUILD_SHARED_LIBS=On`: Build the shared libraries. (on by default)
|
||||||
|
* `-DBUILD_SHARED_AND_STATIC_LIBS=On`: Build both shared and static libraries. (off by default)
|
||||||
|
* `-DCMAKE_INSTALL_PREFIX=/usr`: Set a prefix for the installation.
|
||||||
|
* `-DENABLE_LOCALES=On`: Enable the usage of localeconv method. ( on by default )
|
||||||
|
* `-DCJSON_OVERRIDE_BUILD_SHARED_LIBS=On`: Enable overriding the value of `BUILD_SHARED_LIBS` with `-DCJSON_BUILD_SHARED_LIBS`.
|
||||||
|
* `-DENABLE_CJSON_VERSION_SO`: Enable cJSON so version. ( on by default )
|
||||||
|
|
||||||
|
If you are packaging cJSON for a distribution of Linux, you would probably take these steps for example:
|
||||||
|
```
|
||||||
|
mkdir build
|
||||||
|
cd build
|
||||||
|
cmake .. -DENABLE_CJSON_UTILS=On -DENABLE_CJSON_TEST=Off -DCMAKE_INSTALL_PREFIX=/usr
|
||||||
|
make
|
||||||
|
make DESTDIR=$pkgdir install
|
||||||
|
```
|
||||||
|
|
||||||
|
On Windows CMake is usually used to create a Visual Studio solution file by running it inside the Developer Command Prompt for Visual Studio, for exact steps follow the official documentation from CMake and Microsoft and use the online search engine of your choice. The descriptions of the the options above still generally apply, although not all of them work on Windows.
|
||||||
|
|
||||||
|
#### Makefile
|
||||||
|
|
||||||
|
**NOTE:** This Method is deprecated. Use CMake if at all possible. Makefile support is limited to fixing bugs.
|
||||||
|
|
||||||
|
If you don't have CMake available, but still have GNU make. You can use the makefile to build cJSON:
|
||||||
|
|
||||||
|
Run this command in the directory with the source code and it will automatically compile static and shared libraries and a little test program (not the full test suite).
|
||||||
|
|
||||||
|
```
|
||||||
|
make all
|
||||||
|
```
|
||||||
|
|
||||||
|
If you want, you can install the compiled library to your system using `make install`. By default it will install the headers in `/usr/local/include/cjson` and the libraries in `/usr/local/lib`. But you can change this behavior by setting the `PREFIX` and `DESTDIR` variables: `make PREFIX=/usr DESTDIR=temp install`. And uninstall them with: `make PREFIX=/usr DESTDIR=temp uninstall`.
|
||||||
|
|
||||||
|
#### Meson
|
||||||
|
|
||||||
|
To make cjson work in a project using meson, the libcjson dependency has to be included:
|
||||||
|
|
||||||
|
```meson
|
||||||
|
project('c-json-example', 'c')
|
||||||
|
|
||||||
|
cjson = dependency('libcjson')
|
||||||
|
|
||||||
|
example = executable(
|
||||||
|
'example',
|
||||||
|
'example.c',
|
||||||
|
dependencies: [cjson],
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
#### Vcpkg
|
||||||
|
|
||||||
|
You can download and install cJSON using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager:
|
||||||
|
```
|
||||||
|
git clone https://github.com/Microsoft/vcpkg.git
|
||||||
|
cd vcpkg
|
||||||
|
./bootstrap-vcpkg.sh
|
||||||
|
./vcpkg integrate install
|
||||||
|
vcpkg install cjson
|
||||||
|
```
|
||||||
|
|
||||||
|
The cJSON port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
|
||||||
|
|
||||||
|
### Including cJSON
|
||||||
|
|
||||||
|
If you installed it via CMake or the Makefile, you can include cJSON like this:
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include <cjson/cJSON.h>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Data Structure
|
||||||
|
|
||||||
|
cJSON represents JSON data using the `cJSON` struct data type:
|
||||||
|
|
||||||
|
```c
|
||||||
|
/* The cJSON structure: */
|
||||||
|
typedef struct cJSON
|
||||||
|
{
|
||||||
|
struct cJSON *next;
|
||||||
|
struct cJSON *prev;
|
||||||
|
struct cJSON *child;
|
||||||
|
int type;
|
||||||
|
char *valuestring;
|
||||||
|
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
|
||||||
|
int valueint;
|
||||||
|
double valuedouble;
|
||||||
|
char *string;
|
||||||
|
} cJSON;
|
||||||
|
```
|
||||||
|
|
||||||
|
An item of this type represents a JSON value. The type is stored in `type` as a bit-flag (**this means that you cannot find out the type by just comparing the value of `type`**).
|
||||||
|
|
||||||
|
To check the type of an item, use the corresponding `cJSON_Is...` function. It does a `NULL` check followed by a type check and returns a boolean value if the item is of this type.
|
||||||
|
|
||||||
|
The type can be one of the following:
|
||||||
|
|
||||||
|
* `cJSON_Invalid` (check with `cJSON_IsInvalid`): Represents an invalid item that doesn't contain any value. You automatically have this type if you set the item to all zero bytes.
|
||||||
|
* `cJSON_False` (check with `cJSON_IsFalse`): Represents a `false` boolean value. You can also check for boolean values in general with `cJSON_IsBool`.
|
||||||
|
* `cJSON_True` (check with `cJSON_IsTrue`): Represents a `true` boolean value. You can also check for boolean values in general with `cJSON_IsBool`.
|
||||||
|
* `cJSON_NULL` (check with `cJSON_IsNull`): Represents a `null` value.
|
||||||
|
* `cJSON_Number` (check with `cJSON_IsNumber`): Represents a number value. The value is stored as a double in `valuedouble` and also in `valueint`. If the number is outside of the range of an integer, `INT_MAX` or `INT_MIN` are used for `valueint`.
|
||||||
|
* `cJSON_String` (check with `cJSON_IsString`): Represents a string value. It is stored in the form of a zero terminated string in `valuestring`.
|
||||||
|
* `cJSON_Array` (check with `cJSON_IsArray`): Represent an array value. This is implemented by pointing `child` to a linked list of `cJSON` items that represent the values in the array. The elements are linked together using `next` and `prev`, where the first element has `prev.next == NULL` and the last element `next == NULL`.
|
||||||
|
* `cJSON_Object` (check with `cJSON_IsObject`): Represents an object value. Objects are stored same way as an array, the only difference is that the items in the object store their keys in `string`.
|
||||||
|
* `cJSON_Raw` (check with `cJSON_IsRaw`): Represents any kind of JSON that is stored as a zero terminated array of characters in `valuestring`. This can be used, for example, to avoid printing the same static JSON over and over again to save performance. cJSON will never create this type when parsing. Also note that cJSON doesn't check if it is valid JSON.
|
||||||
|
|
||||||
|
Additionally there are the following two flags:
|
||||||
|
|
||||||
|
* `cJSON_IsReference`: Specifies that the item that `child` points to and/or `valuestring` is not owned by this item, it is only a reference. So `cJSON_Delete` and other functions will only deallocate this item, not its `child`/`valuestring`.
|
||||||
|
* `cJSON_StringIsConst`: This means that `string` points to a constant string. This means that `cJSON_Delete` and other functions will not try to deallocate `string`.
|
||||||
|
|
||||||
|
### Working with the data structure
|
||||||
|
|
||||||
|
For every value type there is a `cJSON_Create...` function that can be used to create an item of that type.
|
||||||
|
All of these will allocate a `cJSON` struct that can later be deleted with `cJSON_Delete`.
|
||||||
|
Note that you have to delete them at some point, otherwise you will get a memory leak.
|
||||||
|
**Important**: If you have added an item to an array or an object already, you **mustn't** delete it with `cJSON_Delete`. Adding it to an array or object transfers its ownership so that when that array or object is deleted,
|
||||||
|
it gets deleted as well. You also could use `cJSON_SetValuestring` to change a `cJSON_String`'s `valuestring`, and you needn't to free the previous `valuestring` manually.
|
||||||
|
|
||||||
|
#### Basic types
|
||||||
|
|
||||||
|
* **null** is created with `cJSON_CreateNull`
|
||||||
|
* **booleans** are created with `cJSON_CreateTrue`, `cJSON_CreateFalse` or `cJSON_CreateBool`
|
||||||
|
* **numbers** are created with `cJSON_CreateNumber`. This will set both `valuedouble` and `valueint`. If the number is outside of the range of an integer, `INT_MAX` or `INT_MIN` are used for `valueint`
|
||||||
|
* **strings** are created with `cJSON_CreateString` (copies the string) or with `cJSON_CreateStringReference` (directly points to the string. This means that `valuestring` won't be deleted by `cJSON_Delete` and you are responsible for its lifetime, useful for constants)
|
||||||
|
|
||||||
|
#### Arrays
|
||||||
|
|
||||||
|
You can create an empty array with `cJSON_CreateArray`. `cJSON_CreateArrayReference` can be used to create an array that doesn't "own" its content, so its content doesn't get deleted by `cJSON_Delete`.
|
||||||
|
|
||||||
|
To add items to an array, use `cJSON_AddItemToArray` to append items to the end.
|
||||||
|
Using `cJSON_AddItemReferenceToArray` an element can be added as a reference to another item, array or string. This means that `cJSON_Delete` will not delete that items `child` or `valuestring` properties, so no double frees are occurring if they are already used elsewhere.
|
||||||
|
To insert items in the middle, use `cJSON_InsertItemInArray`. It will insert an item at the given 0 based index and shift all the existing items to the right.
|
||||||
|
|
||||||
|
If you want to take an item out of an array at a given index and continue using it, use `cJSON_DetachItemFromArray`, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak.
|
||||||
|
|
||||||
|
Deleting items is done with `cJSON_DeleteItemFromArray`. It works like `cJSON_DetachItemFromArray`, but deletes the detached item via `cJSON_Delete`.
|
||||||
|
|
||||||
|
You can also replace an item in an array in place. Either with `cJSON_ReplaceItemInArray` using an index or with `cJSON_ReplaceItemViaPointer` given a pointer to an element. `cJSON_ReplaceItemViaPointer` will return `0` if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place.
|
||||||
|
|
||||||
|
To get the size of an array, use `cJSON_GetArraySize`. Use `cJSON_GetArrayItem` to get an element at a given index.
|
||||||
|
|
||||||
|
Because an array is stored as a linked list, iterating it via index is inefficient (`O(n²)`), so you can iterate over an array using the `cJSON_ArrayForEach` macro in `O(n)` time complexity.
|
||||||
|
|
||||||
|
#### Objects
|
||||||
|
|
||||||
|
You can create an empty object with `cJSON_CreateObject`. `cJSON_CreateObjectReference` can be used to create an object that doesn't "own" its content, so its content doesn't get deleted by `cJSON_Delete`.
|
||||||
|
|
||||||
|
To add items to an object, use `cJSON_AddItemToObject`. Use `cJSON_AddItemToObjectCS` to add an item to an object with a name that is a constant or reference (key of the item, `string` in the `cJSON` struct), so that it doesn't get freed by `cJSON_Delete`.
|
||||||
|
Using `cJSON_AddItemReferenceToArray` an element can be added as a reference to another object, array or string. This means that `cJSON_Delete` will not delete that items `child` or `valuestring` properties, so no double frees are occurring if they are already used elsewhere.
|
||||||
|
|
||||||
|
If you want to take an item out of an object, use `cJSON_DetachItemFromObjectCaseSensitive`, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak.
|
||||||
|
|
||||||
|
Deleting items is done with `cJSON_DeleteItemFromObjectCaseSensitive`. It works like `cJSON_DetachItemFromObjectCaseSensitive` followed by `cJSON_Delete`.
|
||||||
|
|
||||||
|
You can also replace an item in an object in place. Either with `cJSON_ReplaceItemInObjectCaseSensitive` using a key or with `cJSON_ReplaceItemViaPointer` given a pointer to an element. `cJSON_ReplaceItemViaPointer` will return `0` if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place.
|
||||||
|
|
||||||
|
To get the size of an object, you can use `cJSON_GetArraySize`, this works because internally objects are stored as arrays.
|
||||||
|
|
||||||
|
If you want to access an item in an object, use `cJSON_GetObjectItemCaseSensitive`.
|
||||||
|
|
||||||
|
To iterate over an object, you can use the `cJSON_ArrayForEach` macro the same way as for arrays.
|
||||||
|
|
||||||
|
cJSON also provides convenient helper functions for quickly creating a new item and adding it to an object, like `cJSON_AddNullToObject`. They return a pointer to the new item or `NULL` if they failed.
|
||||||
|
|
||||||
|
### Parsing JSON
|
||||||
|
|
||||||
|
Given some JSON in a zero terminated string, you can parse it with `cJSON_Parse`.
|
||||||
|
|
||||||
|
```c
|
||||||
|
cJSON *json = cJSON_Parse(string);
|
||||||
|
```
|
||||||
|
|
||||||
|
Given some JSON in a string (whether zero terminated or not), you can parse it with `cJSON_ParseWithLength`.
|
||||||
|
|
||||||
|
```c
|
||||||
|
cJSON *json = cJSON_ParseWithLength(string, buffer_length);
|
||||||
|
```
|
||||||
|
|
||||||
|
It will parse the JSON and allocate a tree of `cJSON` items that represents it. Once it returns, you are fully responsible for deallocating it after use with `cJSON_Delete`.
|
||||||
|
|
||||||
|
The allocator used by `cJSON_Parse` is `malloc` and `free` by default but can be changed (globally) with `cJSON_InitHooks`.
|
||||||
|
|
||||||
|
If an error occurs a pointer to the position of the error in the input string can be accessed using `cJSON_GetErrorPtr`. Note though that this can produce race conditions in multithreading scenarios, in that case it is better to use `cJSON_ParseWithOpts` with `return_parse_end`.
|
||||||
|
By default, characters in the input string that follow the parsed JSON will not be considered as an error.
|
||||||
|
|
||||||
|
If you want more options, use `cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)`.
|
||||||
|
`return_parse_end` returns a pointer to the end of the JSON in the input string or the position that an error occurs at (thereby replacing `cJSON_GetErrorPtr` in a thread safe way). `require_null_terminated`, if set to `1` will make it an error if the input string contains data after the JSON.
|
||||||
|
|
||||||
|
If you want more options giving buffer length, use `cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated)`.
|
||||||
|
|
||||||
|
### Printing JSON
|
||||||
|
|
||||||
|
Given a tree of `cJSON` items, you can print them as a string using `cJSON_Print`.
|
||||||
|
|
||||||
|
```c
|
||||||
|
char *string = cJSON_Print(json);
|
||||||
|
```
|
||||||
|
|
||||||
|
It will allocate a string and print a JSON representation of the tree into it. Once it returns, you are fully responsible for deallocating it after use with your allocator. (usually `free`, depends on what has been set with `cJSON_InitHooks`).
|
||||||
|
|
||||||
|
`cJSON_Print` will print with whitespace for formatting. If you want to print without formatting, use `cJSON_PrintUnformatted`.
|
||||||
|
|
||||||
|
If you have a rough idea of how big your resulting string will be, you can use `cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)`. `fmt` is a boolean to turn formatting with whitespace on and off. `prebuffer` specifies the first buffer size to use for printing. `cJSON_Print` currently uses 256 bytes for its first buffer size. Once printing runs out of space, a new buffer is allocated and the old gets copied over before printing is continued.
|
||||||
|
|
||||||
|
These dynamic buffer allocations can be completely avoided by using `cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)`. It takes a buffer to a pointer to print to and its length. If the length is reached, printing will fail and it returns `0`. In case of success, `1` is returned. Note that you should provide 5 bytes more than is actually needed, because cJSON is not 100% accurate in estimating if the provided memory is enough.
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
In this example we want to build and parse the following JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "Awesome 4K",
|
||||||
|
"resolutions": [
|
||||||
|
{
|
||||||
|
"width": 1280,
|
||||||
|
"height": 720
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 1920,
|
||||||
|
"height": 1080
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 3840,
|
||||||
|
"height": 2160
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Printing
|
||||||
|
|
||||||
|
Let's build the above JSON and print it to a string:
|
||||||
|
|
||||||
|
```c
|
||||||
|
//create a monitor with a list of supported resolutions
|
||||||
|
//NOTE: Returns a heap allocated string, you are required to free it after use.
|
||||||
|
char *create_monitor(void)
|
||||||
|
{
|
||||||
|
const unsigned int resolution_numbers[3][2] = {
|
||||||
|
{1280, 720},
|
||||||
|
{1920, 1080},
|
||||||
|
{3840, 2160}
|
||||||
|
};
|
||||||
|
char *string = NULL;
|
||||||
|
cJSON *name = NULL;
|
||||||
|
cJSON *resolutions = NULL;
|
||||||
|
cJSON *resolution = NULL;
|
||||||
|
cJSON *width = NULL;
|
||||||
|
cJSON *height = NULL;
|
||||||
|
size_t index = 0;
|
||||||
|
|
||||||
|
cJSON *monitor = cJSON_CreateObject();
|
||||||
|
if (monitor == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
name = cJSON_CreateString("Awesome 4K");
|
||||||
|
if (name == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
/* after creation was successful, immediately add it to the monitor,
|
||||||
|
* thereby transferring ownership of the pointer to it */
|
||||||
|
cJSON_AddItemToObject(monitor, "name", name);
|
||||||
|
|
||||||
|
resolutions = cJSON_CreateArray();
|
||||||
|
if (resolutions == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(monitor, "resolutions", resolutions);
|
||||||
|
|
||||||
|
for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
|
||||||
|
{
|
||||||
|
resolution = cJSON_CreateObject();
|
||||||
|
if (resolution == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToArray(resolutions, resolution);
|
||||||
|
|
||||||
|
width = cJSON_CreateNumber(resolution_numbers[index][0]);
|
||||||
|
if (width == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(resolution, "width", width);
|
||||||
|
|
||||||
|
height = cJSON_CreateNumber(resolution_numbers[index][1]);
|
||||||
|
if (height == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(resolution, "height", height);
|
||||||
|
}
|
||||||
|
|
||||||
|
string = cJSON_Print(monitor);
|
||||||
|
if (string == NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to print monitor.\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
end:
|
||||||
|
cJSON_Delete(monitor);
|
||||||
|
return string;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Alternatively we can use the `cJSON_Add...ToObject` helper functions to make our lives a little easier:
|
||||||
|
|
||||||
|
```c
|
||||||
|
//NOTE: Returns a heap allocated string, you are required to free it after use.
|
||||||
|
char *create_monitor_with_helpers(void)
|
||||||
|
{
|
||||||
|
const unsigned int resolution_numbers[3][2] = {
|
||||||
|
{1280, 720},
|
||||||
|
{1920, 1080},
|
||||||
|
{3840, 2160}
|
||||||
|
};
|
||||||
|
char *string = NULL;
|
||||||
|
cJSON *resolutions = NULL;
|
||||||
|
size_t index = 0;
|
||||||
|
|
||||||
|
cJSON *monitor = cJSON_CreateObject();
|
||||||
|
|
||||||
|
if (cJSON_AddStringToObject(monitor, "name", "Awesome 4K") == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolutions = cJSON_AddArrayToObject(monitor, "resolutions");
|
||||||
|
if (resolutions == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
|
||||||
|
{
|
||||||
|
cJSON *resolution = cJSON_CreateObject();
|
||||||
|
|
||||||
|
if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON_AddItemToArray(resolutions, resolution);
|
||||||
|
}
|
||||||
|
|
||||||
|
string = cJSON_Print(monitor);
|
||||||
|
if (string == NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to print monitor.\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
end:
|
||||||
|
cJSON_Delete(monitor);
|
||||||
|
return string;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Parsing
|
||||||
|
|
||||||
|
In this example we will parse a JSON in the above format and check if the monitor supports a Full HD resolution while printing some diagnostic output:
|
||||||
|
|
||||||
|
```c
|
||||||
|
/* return 1 if the monitor supports full hd, 0 otherwise */
|
||||||
|
int supports_full_hd(const char * const monitor)
|
||||||
|
{
|
||||||
|
const cJSON *resolution = NULL;
|
||||||
|
const cJSON *resolutions = NULL;
|
||||||
|
const cJSON *name = NULL;
|
||||||
|
int status = 0;
|
||||||
|
cJSON *monitor_json = cJSON_Parse(monitor);
|
||||||
|
if (monitor_json == NULL)
|
||||||
|
{
|
||||||
|
const char *error_ptr = cJSON_GetErrorPtr();
|
||||||
|
if (error_ptr != NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Error before: %s\n", error_ptr);
|
||||||
|
}
|
||||||
|
status = 0;
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
name = cJSON_GetObjectItemCaseSensitive(monitor_json, "name");
|
||||||
|
if (cJSON_IsString(name) && (name->valuestring != NULL))
|
||||||
|
{
|
||||||
|
printf("Checking monitor \"%s\"\n", name->valuestring);
|
||||||
|
}
|
||||||
|
|
||||||
|
resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions");
|
||||||
|
cJSON_ArrayForEach(resolution, resolutions)
|
||||||
|
{
|
||||||
|
cJSON *width = cJSON_GetObjectItemCaseSensitive(resolution, "width");
|
||||||
|
cJSON *height = cJSON_GetObjectItemCaseSensitive(resolution, "height");
|
||||||
|
|
||||||
|
if (!cJSON_IsNumber(width) || !cJSON_IsNumber(height))
|
||||||
|
{
|
||||||
|
status = 0;
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((width->valuedouble == 1920) && (height->valuedouble == 1080))
|
||||||
|
{
|
||||||
|
status = 1;
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
end:
|
||||||
|
cJSON_Delete(monitor_json);
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that there are no NULL checks except for the result of `cJSON_Parse` because `cJSON_GetObjectItemCaseSensitive` checks for `NULL` inputs already, so a `NULL` value is just propagated and `cJSON_IsNumber` and `cJSON_IsString` return `0` if the input is `NULL`.
|
||||||
|
|
||||||
|
### Caveats
|
||||||
|
|
||||||
|
#### Zero Character
|
||||||
|
|
||||||
|
cJSON doesn't support strings that contain the zero character `'\0'` or `\u0000`. This is impossible with the current API because strings are zero terminated.
|
||||||
|
|
||||||
|
#### Character Encoding
|
||||||
|
|
||||||
|
cJSON only supports UTF-8 encoded input. In most cases it doesn't reject invalid UTF-8 as input though, it just propagates it through as is. As long as the input doesn't contain invalid UTF-8, the output will always be valid UTF-8.
|
||||||
|
|
||||||
|
#### C Standard
|
||||||
|
|
||||||
|
cJSON is written in ANSI C (or C89, C90). If your compiler or C library doesn't follow this standard, correct behavior is not guaranteed.
|
||||||
|
|
||||||
|
NOTE: ANSI C is not C++ therefore it shouldn't be compiled with a C++ compiler. You can compile it with a C compiler and link it with your C++ code however. Although compiling with a C++ compiler might work, correct behavior is not guaranteed.
|
||||||
|
|
||||||
|
#### Floating Point Numbers
|
||||||
|
|
||||||
|
cJSON does not officially support any `double` implementations other than IEEE754 double precision floating point numbers. It might still work with other implementations but bugs with these will be considered invalid.
|
||||||
|
|
||||||
|
The maximum length of a floating point literal that cJSON supports is currently 63 characters.
|
||||||
|
|
||||||
|
#### Deep Nesting Of Arrays And Objects
|
||||||
|
|
||||||
|
cJSON doesn't support arrays and objects that are nested too deeply because this would result in a stack overflow. To prevent this cJSON limits the depth to `CJSON_NESTING_LIMIT` which is 1000 by default but can be changed at compile time.
|
||||||
|
|
||||||
|
#### Thread Safety
|
||||||
|
|
||||||
|
In general cJSON is **not thread safe**.
|
||||||
|
|
||||||
|
However it is thread safe under the following conditions:
|
||||||
|
|
||||||
|
* `cJSON_GetErrorPtr` is never used (the `return_parse_end` parameter of `cJSON_ParseWithOpts` can be used instead)
|
||||||
|
* `cJSON_InitHooks` is only ever called before using cJSON in any threads.
|
||||||
|
* `setlocale` is never called before all calls to cJSON functions have returned.
|
||||||
|
|
||||||
|
#### Case Sensitivity
|
||||||
|
|
||||||
|
When cJSON was originally created, it didn't follow the JSON standard and didn't make a distinction between uppercase and lowercase letters. If you want the correct, standard compliant, behavior, you need to use the `CaseSensitive` functions where available.
|
||||||
|
|
||||||
|
#### Duplicate Object Members
|
||||||
|
|
||||||
|
cJSON supports parsing and printing JSON that contains objects that have multiple members with the same name. `cJSON_GetObjectItemCaseSensitive` however will always only return the first one.
|
||||||
|
|
||||||
|
# Enjoy cJSON!
|
||||||
|
|
||||||
|
- Dave Gamble (original author)
|
||||||
|
- Max Bruckner and Alan Wang (current maintainer)
|
||||||
|
- and the other [cJSON contributors](CONTRIBUTORS.md)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
|
||||||
|
[*]
|
||||||
|
indent_style = space
|
||||||
|
indent_size = 4
|
||||||
|
end_of_line = lf
|
||||||
|
charset = utf-8
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
insert_final_newline = true
|
||||||
|
|
||||||
|
[Makefile]
|
||||||
|
indent_style = tab
|
||||||
|
indent_size = unset
|
||||||
|
|
||||||
|
# ignore external repositories and test inputs
|
||||||
|
[tests/{unity,json-patch-tests,inputs}/*]
|
||||||
|
indent_style = unset
|
||||||
|
indent_size = unset
|
||||||
|
end_of_line = unset
|
||||||
|
charset = unset
|
||||||
|
trim_trailing_whitespace = unset
|
||||||
|
insert_final_newline = unset
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
* text=auto
|
||||||
|
/tests/inputs/* text eol=lf
|
||||||
|
|
||||||
|
.gitattributes export-ignore
|
||||||
|
.gitignore export-ignore
|
||||||
|
.github export-ignore
|
||||||
|
.editorconfig export-ignore
|
||||||
|
.travis.yml export-ignore
|
||||||
|
|
||||||
|
# Linguist incorrectly identified the headers as C++, manually override this.
|
||||||
|
*.h linguist-language=C
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
.svn
|
||||||
|
test
|
||||||
|
*.o
|
||||||
|
*.a
|
||||||
|
*.so
|
||||||
|
*.swp
|
||||||
|
*.patch
|
||||||
|
tags
|
||||||
|
*.dylib*
|
||||||
|
build/
|
||||||
|
cJSON_test
|
||||||
|
cJSON_test_utils
|
||||||
|
libcjson.so.*
|
||||||
|
libcjson_utils.so.*
|
||||||
|
*.orig
|
||||||
|
.vscode
|
||||||
|
.idea
|
||||||
|
cmake-build-debug
|
||||||
|
*.lst
|
||||||
|
*.lss
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
dist: trusty
|
||||||
|
sudo: false
|
||||||
|
language: c
|
||||||
|
env:
|
||||||
|
matrix:
|
||||||
|
- VALGRIND=On SANITIZERS=Off
|
||||||
|
- VALGRIND=Off SANITIZERS=Off
|
||||||
|
- VALGRIND=Off SANITIZERS=On
|
||||||
|
compiler:
|
||||||
|
- gcc
|
||||||
|
- clang
|
||||||
|
addons:
|
||||||
|
apt:
|
||||||
|
packages:
|
||||||
|
- valgrind
|
||||||
|
- libasan0
|
||||||
|
- lib32asan0
|
||||||
|
# currently not supported on travis:
|
||||||
|
# - libasan1
|
||||||
|
# - libasan2
|
||||||
|
# - libubsan0
|
||||||
|
- llvm
|
||||||
|
script:
|
||||||
|
- mkdir build
|
||||||
|
- cd build
|
||||||
|
- cmake .. -DENABLE_CJSON_UTILS=On -DENABLE_VALGRIND="${VALGRIND}" -DENABLE_SAFE_STACK="${VALGRIND}" -DENABLE_SANITIZERS="${SANITIZERS}"
|
||||||
|
- make
|
||||||
|
- make test CTEST_OUTPUT_ON_FAILURE=On
|
||||||
@@ -0,0 +1,476 @@
|
|||||||
|
1.7.19 (Sep 9, 2025)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix indentation (should use spaces), see #814
|
||||||
|
* Fix spelling errors found by CodeSpell, see #841
|
||||||
|
* Check for NULL in cJSON_DetachItemViaPointer, fixes #882, see #886
|
||||||
|
* Fix #881, check overlap before calling strcpy in cJSON_SetValuestring, see #885
|
||||||
|
* Fix #880 Max recursion depth for cJSON_Duplicate to prevent stack exhaustion, see #888
|
||||||
|
* Allocate memory for the temporary buffer when paring numbers, see #939
|
||||||
|
* fix the incorrect check in decode_array_index_from_pointer, see #957
|
||||||
|
|
||||||
|
1.7.18 (May 13, 2024)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Add NULL check to cJSON_SetValuestring()(CVE-2024-31755), see #839 and #840
|
||||||
|
* Remove non-functional list handling of compiler flags, see #851
|
||||||
|
* Fix heap buffer overflow, see #852
|
||||||
|
* remove misused optimization flag -01, see #854
|
||||||
|
* Set free'd pointers to NULL whenever they are not reassigned immediately after, see #855 and #833
|
||||||
|
|
||||||
|
1.7.17 (Dec 26, 2023)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix null reference in cJSON_SetValuestring(CVE-2023-50472), see #809
|
||||||
|
* Fix null reference in cJSON_InsertItemInArray(CVE-2023-50471), see #809 and #810
|
||||||
|
|
||||||
|
1.7.16 (Jul 5, 2023)
|
||||||
|
======
|
||||||
|
Features:
|
||||||
|
------
|
||||||
|
* Add an option for ENABLE_CJSON_VERSION_SO in CMakeLists.txt, see #534
|
||||||
|
* Add cmake_policy to CMakeLists.txt, see #163
|
||||||
|
* Add cJSON_SetBoolValue, see #639
|
||||||
|
* Add meson documentation, see #761
|
||||||
|
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix memory leak in merge_patch, see #611
|
||||||
|
* Fix conflicting target names 'uninstall', see #617
|
||||||
|
* Bump cmake version to 3.0 and use new version syntax, see #587
|
||||||
|
* Print int without decimal places, see #630
|
||||||
|
* Fix 'cjson_utils-static' target not exist, see #625
|
||||||
|
* Add allocate check for replace_item_in_object, see #675
|
||||||
|
* Fix a null pointer crash in cJSON_ReplaceItemViaPointer, see #726
|
||||||
|
|
||||||
|
1.7.15 (Aug 25, 2021)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix potential core dumped for strrchr, see [#546](https://github.com/DaveGamble/cJSON/pull/546)
|
||||||
|
* Fix null pointer crash in cJSON_CreateXxArray, see [#538](https://github.com/DaveGamble/cJSON/pull/538)
|
||||||
|
* Fix several null pointer problems on allocation failure, see [#526](https://github.com/DaveGamble/cJSON/pull/526)
|
||||||
|
* Fix a possible dereference of null pointer, see [#519](https://github.com/DaveGamble/cJSON/pull/519)
|
||||||
|
* Fix windows build failure about defining nan, see [#518](https://github.com/DaveGamble/cJSON/pull/518)
|
||||||
|
|
||||||
|
1.7.14 (Sep 3, 2020)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* optimize the way to find tail node, see [#503](https://github.com/DaveGamble/cJSON/pull/503)
|
||||||
|
* Fix WError error on macosx because NAN is a float. Thanks @sappo, see [#484](https://github.com/DaveGamble/cJSON/pull/484)
|
||||||
|
* Fix some bugs in detach and replace. Thanks @miaoerduo, see [#456](https://github.com/DaveGamble/cJSON/pull/456)
|
||||||
|
|
||||||
|
1.7.13 (Apr 2, 2020)
|
||||||
|
======
|
||||||
|
Features:
|
||||||
|
---------
|
||||||
|
* add new API of cJSON_ParseWithLength without breaking changes. Thanks @caglarivriz, see [#358](https://github.com/DaveGamble/cJSON/pull/358)
|
||||||
|
* add new API of cJSON_GetNumberValue. Thanks @Intuition, see[#385](https://github.com/DaveGamble/cJSON/pull/385)
|
||||||
|
* add uninstall target function for CMake. See [#402](https://github.com/DaveGamble/cJSON/pull/402)
|
||||||
|
* Improve performance of adding item to array. Thanks @xiaomianhehe, see [#430](https://github.com/DaveGamble/cJSON/pull/430), [#448](https://github.com/DaveGamble/cJSON/pull/448)
|
||||||
|
* add new API of cJSON_SetValuestring, for changing the valuestring safely. See [#451](https://github.com/DaveGamble/cJSON/pull/451)
|
||||||
|
* add return value for cJSON_AddItemTo... and cJSON_ReplaceItem... (check if the operation successful). See [#453](https://github.com/DaveGamble/cJSON/pull/453)
|
||||||
|
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix clang -Wfloat-equal warning. Thanks @paulmalovanyi, see [#368](https://github.com/DaveGamble/cJSON/pull/368)
|
||||||
|
* Fix make failed in mac os. See [#405](https://github.com/DaveGamble/cJSON/pull/405)
|
||||||
|
* Fix memory leak in cJSONUtils_FindPointerFromObjectTo. Thanks @andywolk for reporting, see [#414](https://github.com/DaveGamble/cJSON/issues/414)
|
||||||
|
* Fix bug in encode_string_as_pointer. Thanks @AIChangJiang for reporting, see [#439](https://github.com/DaveGamble/cJSON/issues/439)
|
||||||
|
|
||||||
|
1.7.12 (May 17, 2019)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix infinite loop in `cJSON_Minify` (potential Denial of Service). Thanks @Alanscut for reporting, see [#354](https://github.com/DaveGamble/cJSON/issues/354)
|
||||||
|
* Fix link error for Visual Studio. Thanks @tan-wei, see [#352](https://github.com/DaveGamble/cJSON/pull/352).
|
||||||
|
* Undefine `true` and `false` for `cJSON_Utils` before redefining them. Thanks @raiden00pl, see [#347](https://github.com/DaveGamble/cJSON/pull/347).
|
||||||
|
|
||||||
|
1.7.11 (Apr 15, 2019)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix a bug where cJSON_Minify could overflow it's buffer, both reading and writing. This is a security issue, see [#338](https://github.com/DaveGamble/cJSON/issues/338). Big thanks @bigric3 for reporting.
|
||||||
|
* Unset `true` and `false` macros before setting them if they exist. See [#339](https://github.com/DaveGamble/cJSON/issues/339), thanks @raiden00pl for reporting
|
||||||
|
|
||||||
|
1.7.10 (Dec 21, 2018)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix package config file for `libcjson`. Thanks @shiluotang for reporting [#321](https://github.com/DaveGamble/cJSON/issues/321)
|
||||||
|
* Correctly split lists in `cJSON_Utils`'s merge sort. Thanks @andysCaplin for the fix [#322](https://github.com/DaveGamble/cJSON/issues/322)
|
||||||
|
|
||||||
|
1.7.9 (Dec 16, 2018)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix a bug where `cJSON_GetObjectItemCaseSensitive` would pass a nullpointer to `strcmp` when called on an array, see [#315](https://github.com/DaveGamble/cJSON/issues/315). Thanks @yuweol for reporting.
|
||||||
|
* Fix error in `cJSON_Utils` where the case sensitivity was not respected, see [#317](https://github.com/DaveGamble/cJSON/pull/317). Thanks @yuta-oxo for fixing.
|
||||||
|
* Fix some warnings detected by the Visual Studio Static Analyzer, see [#307](https://github.com/DaveGamble/cJSON/pull/307). Thanks @bnason-nf
|
||||||
|
|
||||||
|
1.7.8 (Sep 22, 2018)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* cJSON now works with the `__stdcall` calling convention on Windows, see [#295](https://github.com/DaveGamble/cJSON/pull/295), thanks @zhindes for contributing
|
||||||
|
|
||||||
|
1.7.7 (May 22, 2018)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix a memory leak when realloc fails, see [#267](https://github.com/DaveGamble/cJSON/issues/267), thanks @AlfieDeng for reporting
|
||||||
|
* Fix a typo in the header file, see [#266](https://github.com/DaveGamble/cJSON/pull/266), thanks @zhaozhixu
|
||||||
|
|
||||||
|
1.7.6 (Apr 13, 2018)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Add `SONAME` to the ELF files built by the Makefile, see [#252](https://github.com/DaveGamble/cJSON/issues/252), thanks @YanhaoMo for reporting
|
||||||
|
* Add include guards and `extern "C"` to `cJSON_Utils.h`, see [#256](https://github.com/DaveGamble/cJSON/issues/256), thanks @daschfg for reporting
|
||||||
|
|
||||||
|
Other changes:
|
||||||
|
* Mark the Makefile as deprecated in the README.
|
||||||
|
|
||||||
|
1.7.5 (Mar 23, 2018)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix a bug in the JSON Patch implementation of `cJSON Utils`, see [#251](https://github.com/DaveGamble/cJSON/pull/251), thanks @bobkocisko.
|
||||||
|
|
||||||
|
1.7.4 (Mar 3, 2018)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix potential use after free if the `string` parameter to `cJSON_AddItemToObject` is an alias of the `string` property of the object that is added,see [#248](https://github.com/DaveGamble/cJSON/issues/248). Thanks @hhallen for reporting.
|
||||||
|
|
||||||
|
1.7.3 (Feb 8, 2018)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix potential double free, thanks @projectgus for reporting [#241](https://github.com/DaveGamble/cJSON/issues/241)
|
||||||
|
|
||||||
|
1.7.2 (Feb 6, 2018)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix the use of GNUInstallDirs variables and the pkgconfig file. Thanks @zeerd for reporting [#240](https://github.com/DaveGamble/cJSON/pull/240)
|
||||||
|
|
||||||
|
1.7.1 (Jan 10, 2018)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fixed an Off-By-One error that could lead to an out of bounds write. Thanks @liuyunbin for reporting [#230](https://github.com/DaveGamble/cJSON/issues/230)
|
||||||
|
* Fixed two errors with buffered printing. Thanks @liuyunbin for reporting [#230](https://github.com/DaveGamble/cJSON/issues/230)
|
||||||
|
|
||||||
|
1.7.0 (Dec 31, 2017)
|
||||||
|
=====
|
||||||
|
Features:
|
||||||
|
---------
|
||||||
|
* Large rewrite of the documentation, see [#215](https://github.com/DaveGamble/cJSON/pull/215)
|
||||||
|
* Added the `cJSON_GetStringValue` function
|
||||||
|
* Added the `cJSON_CreateStringReference` function
|
||||||
|
* Added the `cJSON_CreateArrayReference` function
|
||||||
|
* Added the `cJSON_CreateObjectReference` function
|
||||||
|
* The `cJSON_Add...ToObject` macros are now functions that return a pointer to the added item, see [#226](https://github.com/DaveGamble/cJSON/pull/226)
|
||||||
|
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix a problem with `GNUInstallDirs` in the CMakeLists.txt, thanks @yangfl, see [#210](https://github.com/DaveGamble/cJSON/pull/210)
|
||||||
|
* Fix linking the tests when building as static library, see [#213](https://github.com/DaveGamble/cJSON/issues/213)
|
||||||
|
* New overrides for the CMake option `BUILD_SHARED_LIBS`, see [#207](https://github.com/DaveGamble/cJSON/issues/207)
|
||||||
|
|
||||||
|
Other Changes:
|
||||||
|
--------------
|
||||||
|
* Readme: Explain how to include cJSON, see [#211](https://github.com/DaveGamble/cJSON/pull/211)
|
||||||
|
* Removed some trailing spaces in the code, thanks @yangfl, see [#212](https://github.com/DaveGamble/cJSON/pull/212)
|
||||||
|
* Updated [Unity](https://github.com/ThrowTheSwitch/Unity) and [json-patch-tests](https://github.com/json-patch/json-patch-tests)
|
||||||
|
|
||||||
|
1.6.0 (Oct 9, 2017)
|
||||||
|
=====
|
||||||
|
Features:
|
||||||
|
---------
|
||||||
|
* You can now build cJSON as both shared and static library at once with CMake using `-DBUILD_SHARED_AND_STATIC_LIBS=On`, see [#178](https://github.com/DaveGamble/cJSON/issues/178)
|
||||||
|
* UTF-8 byte order marks are now ignored, see [#184](https://github.com/DaveGamble/cJSON/issues/184)
|
||||||
|
* Locales can now be disabled with the option `-DENABLE_LOCALES=Off`, see [#202](https://github.com/DaveGamble/cJSON/issues/202), thanks @Casperinous
|
||||||
|
* Better support for MSVC and Visual Studio
|
||||||
|
|
||||||
|
Other Changes:
|
||||||
|
--------------
|
||||||
|
* Add the new warnings `-Wswitch-enum`, `-Wused-but-makred-unused`, `-Wmissing-variable-declarations`, `-Wunused-macro`
|
||||||
|
* More number printing tests.
|
||||||
|
* Continuous integration testing with AppVeyor (semi automatic at this point), thanks @simon-p-r
|
||||||
|
|
||||||
|
1.5.9 (Sep 8, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Set the global error pointer even if `return_parse_end` is passed to `cJSON_ParseWithOpts`, see [#200](https://github.com/DaveGamble/cJSON/pull/200), thanks @rmallins
|
||||||
|
|
||||||
|
1.5.8 (Aug 21, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix `make test` in the Makefile, thanks @YanhaoMo for reporting this [#195](https://github.com/DaveGamble/cJSON/issues/195)
|
||||||
|
|
||||||
|
1.5.7 (Jul 13, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix a bug where realloc failing would return a pointer to an invalid memory address. This is a security issue as it could potentially be used by an attacker to write to arbitrary memory addresses, see [#189](https://github.com/DaveGamble/cJSON/issues/189), fixed in [954d61e](https://github.com/DaveGamble/cJSON/commit/954d61e5e7cb9dc6c480fc28ac1cdceca07dd5bd), big thanks @timothyjohncarney for reporting this issue
|
||||||
|
* Fix a spelling mistake in the AFL fuzzer dictionary, see [#185](https://github.com/DaveGamble/cJSON/pull/185), thanks @jwilk
|
||||||
|
|
||||||
|
1.5.6 (Jun 28, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Make cJSON a lot more tolerant about passing NULL pointers to its functions, it should now fail safely instead of dereferencing the pointer, see [#183](https://github.com/DaveGamble/cJSON/pull/183). Thanks @msichal for reporting [#182](https://github.com/DaveGamble/cJSON/issues/182)
|
||||||
|
|
||||||
|
1.5.5 (Jun 15, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix pointers to nested arrays in cJSON_Utils, see [9abe](https://github.com/DaveGamble/cJSON/commit/9abe75e072050f34732a7169740989a082b65134)
|
||||||
|
* Fix an error with case sensitivity handling in cJSON_Utils, see [b9cc911](https://github.com/DaveGamble/cJSON/commit/b9cc911831b0b3e1bb72f142389428e59f882b38)
|
||||||
|
* Fix cJSON_Compare for arrays that are prefixes of the other and objects that are a subset of the other, see [03ba72f](https://github.com/DaveGamble/cJSON/commit/03ba72faec115160d1f3aea5582d9b6af5d3e473) and [#180](https://github.com/DaveGamble/cJSON/issues/180), thanks @zhengqb for reporting
|
||||||
|
|
||||||
|
1.5.4 (Jun 5, 2017)
|
||||||
|
======
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix build with GCC 7.1.1 and optimization level `-O2`, see [bfbd8fe](https://github.com/DaveGamble/cJSON/commit/bfbd8fe0d85f1dd21e508748fc10fc4c27cc51be)
|
||||||
|
|
||||||
|
Other Changes:
|
||||||
|
--------------
|
||||||
|
* Update [Unity](https://github.com/ThrowTheSwitch/Unity) to 3b69beaa58efc41bbbef70a32a46893cae02719d
|
||||||
|
|
||||||
|
1.5.3 (May 23, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix `cJSON_ReplaceItemInObject` not keeping the name of an item, see [#174](https://github.com/DaveGamble/cJSON/issues/174)
|
||||||
|
|
||||||
|
1.5.2 (May 10, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix a reading buffer overflow in `parse_string`, see [a167d9e](https://github.com/DaveGamble/cJSON/commit/a167d9e381e5c84bc03de4e261757b031c0c690d)
|
||||||
|
* Fix compiling with -Wcomma, see [186cce3](https://github.com/DaveGamble/cJSON/commit/186cce3ece6ce6dfcb58ac8b2a63f7846c3493ad)
|
||||||
|
* Remove leftover attribute from tests, see [b537ca7](https://github.com/DaveGamble/cJSON/commit/b537ca70a35680db66f1f5b8b437f7114daa699a)
|
||||||
|
|
||||||
|
1.5.1 (May 6, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Add gcc version guard to the Makefile, see [#164](https://github.com/DaveGamble/cJSON/pull/164), thanks @juvasquezg
|
||||||
|
* Fix incorrect free in `cJSON_Utils` if custom memory allocator is used, see [#166](https://github.com/DaveGamble/cJSON/pull/166), thanks @prefetchnta
|
||||||
|
|
||||||
|
1.5.0 (May 2, 2017)
|
||||||
|
=====
|
||||||
|
Features:
|
||||||
|
* cJSON finally prints numbers without losing precision, see [#153](https://github.com/DaveGamble/cJSON/pull/153), thanks @DeboraG
|
||||||
|
* `cJSON_Compare` recursively checks if two cJSON items contain the same values, see [#148](https://github.com/DaveGamble/cJSON/pull/148)
|
||||||
|
* Provide case sensitive versions of every function where it matters, see [#158](https://github.com/DaveGamble/cJSON/pull/158) and [#159](https://github.com/DaveGamble/cJSON/pull/159)
|
||||||
|
* Added `cJSON_ReplaceItemViaPointer` and `cJSON_DetachItemViaPointer`
|
||||||
|
* Added `cJSON_free` and `cJSON_malloc` that expose the internal configured memory allocators. see [02a05ee](https://github.com/DaveGamble/cJSON/commit/02a05eea4e6ba41811f130b322660bea8918e1a0)
|
||||||
|
|
||||||
|
|
||||||
|
Enhancements:
|
||||||
|
-------------
|
||||||
|
* Parse into a buffer, this will allow parsing `\u0000` in the future (not quite yet though)
|
||||||
|
* General simplifications and readability improvements
|
||||||
|
* More unit tests
|
||||||
|
* Update [unity](https://github.com/ThrowTheSwitch/Unity) testing library to 2.4.1
|
||||||
|
* Add the [json-patch-tests](https://github.com/json-patch/json-patch-tests) test suite to test cJSON_Utils.
|
||||||
|
* Move all tests from `test_utils.c` to unit tests with unity.
|
||||||
|
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix some warnings with the Microsoft compiler, see [#139](https://github.com/DaveGamble/cJSON/pull/139), thanks @PawelWMS
|
||||||
|
* Fix several bugs in cJSON_Utils, mostly found with [json-patch-tests](https://github.com/json-patch/json-patch-tests)
|
||||||
|
* Prevent a stack overflow by specifying a maximum nesting depth `CJSON_NESTING_LIMIT`
|
||||||
|
|
||||||
|
Other Changes:
|
||||||
|
--------------
|
||||||
|
* Move generated files in the `library_config` subdirectory.
|
||||||
|
|
||||||
|
1.4.7 (Apr 19, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix `cJSONUtils_ApplyPatches`, it was completely broken and apparently nobody noticed (or at least reported it), see [075a06f](https://github.com/DaveGamble/cJSON/commit/075a06f40bdc4f836c7dd7cad690d253a57cfc50)
|
||||||
|
* Fix inconsistent prototype for `cJSON_GetObjectItemCaseSensitive`, see [51d3df6](https://github.com/DaveGamble/cJSON/commit/51d3df6c9f7b56b860c8fb24abe7bab255cd4fa9), thanks @PawelWMS
|
||||||
|
|
||||||
|
1.4.6 (Apr 9, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Several corrections in the README
|
||||||
|
* Making clear that `valueint` should not be written to
|
||||||
|
* Fix overflow detection in `ensure`, see [2683d4d](https://github.com/DaveGamble/cJSON/commit/2683d4d9873df87c4bdccc523903ddd78d1ad250)
|
||||||
|
* Fix a potential null pointer dereference in cJSON_Utils, see [795c3ac](https://github.com/DaveGamble/cJSON/commit/795c3acabed25c9672006b2c0f40be8845064827)
|
||||||
|
* Replace incorrect `sizeof('\0')` with `sizeof("")`, see [84237ff](https://github.com/DaveGamble/cJSON/commit/84237ff48e69825c94261c624eb0376d0c328139)
|
||||||
|
* Add caveats section to the README, see [50b3c30](https://github.com/DaveGamble/cJSON/commit/50b3c30dfa89830f8f477ce33713500740ac3b79)
|
||||||
|
* Make cJSON locale independent, see [#146](https://github.com/DaveGamble/cJSON/pull/146), Thanks @peterh for reporting
|
||||||
|
* Fix compiling without CMake with MSVC, see [#147](https://github.com/DaveGamble/cJSON/pull/147), Thanks @dertuxmalwieder for reporting
|
||||||
|
|
||||||
|
1.4.5 (Mar 28, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix bug in `cJSON_SetNumberHelper`, thanks @mmkeeper, see [#138](https://github.com/DaveGamble/cJSON/issues/138) and [ef34500](https://github.com/DaveGamble/cJSON/commit/ef34500693e8c4a2849d41a4bd66fd19c9ec46c2)
|
||||||
|
* Workaround for internal compiler error in GCC 5.4.0 and 6.3.1 on x86 (2f65e80a3471d053fdc3f8aed23d01dd1782a5cb [GCC bugreport](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80097))
|
||||||
|
|
||||||
|
1.4.4 (Mar 24, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix a theoretical integer overflow, (not sure if it is possible on actual hardware), see [e58f7ec](https://github.com/DaveGamble/cJSON/commit/e58f7ec027d00b7cdcbf63e518c1b5268b29b3da)
|
||||||
|
* Fix an off by one error, see [cc84a44](https://github.com/DaveGamble/cJSON/commit/cc84a446be20cc283bafdc4d94c050ba1111ac02), thanks @gatzka
|
||||||
|
* Double check the offset of the print buffer in `ensure`, see [1934059](https://github.com/DaveGamble/cJSON/commit/1934059554b9a0971e00f79e96900f422cfdd114)
|
||||||
|
|
||||||
|
Improvements:
|
||||||
|
* Add a note in the header about required buffer size when using `cJSON_PrintPreallocated`, see [4bfb8800](https://github.com/DaveGamble/cJSON/commit/4bfb88009342fb568295a7f6dc4b7fee74fbf022)
|
||||||
|
|
||||||
|
1.4.3 (Mar 19, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix compilation of the tests on 32 bit PowerPC and potentially other systems, see [4ec6e76](https://github.com/DaveGamble/cJSON/commit/4ec6e76ea2eec16f54b58e8c95b4c734e59481e4)
|
||||||
|
* Fix compilation with old GCC compilers (4.3+ were tested), see [227d33](https://github.com/DaveGamble/cJSON/commit/227d3398d6b967879761ebe02c1b63dbd6ea6e0d), [466eb8e](https://github.com/DaveGamble/cJSON/commit/466eb8e3f8a65080f2b3ca4a79ab7b72bd539dba), see also [#126](https://github.com/DaveGamble/cJSON/issues/126)
|
||||||
|
|
||||||
|
1.4.2 (Mar 16, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fix minimum required cmake version, see [30e1e7a](https://github.com/DaveGamble/cJSON/commit/30e1e7af7c63db9b55f5a3cda977a6c032f0b132)
|
||||||
|
* Fix detection of supported compiler flags, see [76e5296](https://github.com/DaveGamble/cJSON/commit/76e5296d0d05ceb3018a9901639e0e171b44a557)
|
||||||
|
* Run `cJSON_test` and `cJSON_test_utils` along with unity tests, see [c597601](https://github.com/DaveGamble/cJSON/commit/c597601cf151a757dcf800548f18034d4ddfe2cb)
|
||||||
|
|
||||||
|
1.4.1 (Mar 16, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Make `print_number` abort with a failure in out of memory situations, see [cf1842](https://github.com/DaveGamble/cJSON/commit/cf1842dc6f64c49451a022308b4415e4d468be0a)
|
||||||
|
|
||||||
|
1.4.0 (Mar 4, 2017)
|
||||||
|
=====
|
||||||
|
Features
|
||||||
|
--------
|
||||||
|
* Functions to check the type of an item, see [#120](https://github.com/DaveGamble/cJSON/pull/120)
|
||||||
|
* Use dllexport on windows and fvisibility on Unix systems for public functions, see [#116](https://github.com/DaveGamble/cJSON/pull/116), thanks @mjerris
|
||||||
|
* Remove trailing zeroes from printed numbers, see [#123](https://github.com/DaveGamble/cJSON/pull/123)
|
||||||
|
* Expose the internal boolean type `cJSON_bool` in the header, see [2d3520e](https://github.com/DaveGamble/cJSON/commit/2d3520e0b9d0eb870e8886e8a21c571eeddbb310)
|
||||||
|
|
||||||
|
Fixes
|
||||||
|
* Fix handling of NULL pointers in `cJSON_ArrayForEach`, see [b47d0e3](https://github.com/DaveGamble/cJSON/commit/b47d0e34caaef298edfb7bd09a72cfff21d231ff)
|
||||||
|
* Make it compile with GCC 7 (fix -Wimplicit-fallthrough warning), see [9d07917](https://github.com/DaveGamble/cJSON/commit/9d07917feb1b613544a7513d19233d4c851ad7ad)
|
||||||
|
|
||||||
|
Other Improvements
|
||||||
|
* internally use realloc if available ([#110](https://github.com/DaveGamble/cJSON/pull/110))
|
||||||
|
* builtin support for fuzzing with [afl](http://lcamtuf.coredump.cx/afl/) ([#111](https://github.com/DaveGamble/cJSON/pull/111))
|
||||||
|
* unit tests for the print functions ([#112](https://github.com/DaveGamble/cJSON/pull/112))
|
||||||
|
* Always use buffered printing ([#113](https://github.com/DaveGamble/cJSON/pull/113))
|
||||||
|
* simplify the print functions ([#114](https://github.com/DaveGamble/cJSON/pull/114))
|
||||||
|
* Add the compiler flags `-Wdouble-conversion`, `-Wparentheses` and `-Wcomma` ([#122](https://github.com/DaveGamble/cJSON/pull/122))
|
||||||
|
|
||||||
|
1.3.2 (Mar 1, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Don't build the unity library if testing is disabled, see [#121](https://github.com/DaveGamble/cJSON/pull/121). Thanks @ffontaine
|
||||||
|
|
||||||
|
1.3.1 (Feb 27, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Bugfix release that fixes an out of bounds read, see [#118](https://github.com/DaveGamble/cJSON/pull/118). This shouldn't have any security implications.
|
||||||
|
|
||||||
|
1.3.0 (Feb 17, 2017)
|
||||||
|
=====
|
||||||
|
This release includes a lot of rework in the parser and includes the Cunity unit testing framework, as well as some fixes. I increased the minor version number because there were quite a lot of internal changes.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
* New type for cJSON structs: `cJSON_Invalid`, see [#108](https://github.com/DaveGamble/cJSON/pull/108)
|
||||||
|
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* runtime checks for a lot of potential integer overflows
|
||||||
|
* fix incorrect return in cJSON_PrintBuffered [cf9d57d](https://github.com/DaveGamble/cJSON/commit/cf9d57d56cac21fc59465b8d26cf29bf6d2a87b3)
|
||||||
|
* fix several potential issues found by [Coverity](https://scan.coverity.com/projects/cjson)
|
||||||
|
* fix potentially undefined behavior when assigning big numbers to `valueint` ([41e2837](https://github.com/DaveGamble/cJSON/commit/41e2837df1b1091643aff073f2313f6ff3cc10f4))
|
||||||
|
* Numbers exceeding `INT_MAX` or lower than `INT_MIN` will be explicitly assigned to `valueint` as `INT_MAX` and `INT_MIN` respectively (saturation on overflow).
|
||||||
|
* fix the `cJSON_SetNumberValue` macro ([87f7727](https://github.com/DaveGamble/cJSON/commit/87f77274de6b3af00fb9b9a7f3b900ef382296c2)), this slightly changes the behavior, see commit message
|
||||||
|
|
||||||
|
Introduce unit tests
|
||||||
|
--------------------
|
||||||
|
|
||||||
|
* Started writing unit tests with the [Cunity](https://github.com/ThrowTheSwitch/Unity) testing framework. Currently this covers the parser functions.
|
||||||
|
|
||||||
|
Also:
|
||||||
|
* Support for running the tests with [Valgrind](http://valgrind.org)
|
||||||
|
* Support for compiling the tests with [AddressSanitizer](https://github.com/google/sanitizers) and [UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html).
|
||||||
|
* `travis.yml` file for running unit tests on travis. (not enabled for the repository yet though [#102](https://github.com/DaveGamble/cJSON/issues/102)
|
||||||
|
|
||||||
|
Simplifications
|
||||||
|
---------------
|
||||||
|
|
||||||
|
After having unit tests for the parser function in place, I started refactoring the parser functions (as well as others) and making them easier to read and maintain.
|
||||||
|
* Use `strtod` from the standard library for parsing numbers ([0747669](https://github.com/DaveGamble/cJSON/commit/074766997246481dfc72bfa78f07898a2716473f))
|
||||||
|
* Use goto-fail in several parser functions ([#100](https://github.com/DaveGamble/cJSON/pull/100))
|
||||||
|
* Rewrite/restructure all of the parsing functions to be easier to understand and have less code paths doing the same as another. ([#109](https://github.com/DaveGamble/cJSON/pull/109))
|
||||||
|
* Simplify the buffer allocation strategy to always doubling the needed amount ([9f6fa94](https://github.com/DaveGamble/cJSON/commit/9f6fa94c91a87b71e4c6868dbf2ce431a48517b0))
|
||||||
|
* Combined `cJSON_AddItemToObject` and `cJSON_AddItemToObjectCS` to one function ([cf862d](https://github.com/DaveGamble/cJSON/commit/cf862d0fed7f9407e4b046d78d3d8050d2080d12))
|
||||||
|
|
||||||
|
Other changes
|
||||||
|
-------------
|
||||||
|
* Prevent the usage of incompatible C and header versions via preprocessor directive ([123bb1](https://github.com/DaveGamble/cJSON/commit/123bb1af7bfae41d805337fef4b41045ef6c7d25))
|
||||||
|
* Let CMake automatically detect compiler flags
|
||||||
|
* Add new compiler flags (`-Wundef`, `-Wswitch-default`, `-Wconversion`, `-fstack-protector-strong`) ([#98](https://github.com/DaveGamble/cJSON/pull/98))
|
||||||
|
* Change internal sizes from `int` to `size_t` ([ecd5678](https://github.com/DaveGamble/cJSON/commit/ecd5678527a6bc422da694e5be9e9979878fe6a0))
|
||||||
|
* Change internal strings from `char*` to `unsigned char*` ([28b9ba4](https://github.com/DaveGamble/cJSON/commit/28b9ba4334e0f7309e867e874a31f395c0ac2474))
|
||||||
|
* Add `const` in more places
|
||||||
|
|
||||||
|
1.2.1 (Jan 31, 2017)
|
||||||
|
=====
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Fixes a potential null pointer dereference in cJSON_Utils, discovered using clang's static analyzer by @bnason-nf, see [#96](https://github.com/DaveGamble/cJSON/issues/96)
|
||||||
|
|
||||||
|
1.2.0 (Jan 9, 2017)
|
||||||
|
=====
|
||||||
|
Features:
|
||||||
|
---------
|
||||||
|
* Add a new type of cJSON item for raw JSON and support printing it. Thanks @loigu, see [#65](https://github.com/DaveGamble/cJSON/pull/65), [#90](https://github.com/DaveGamble/cJSON/pull/90)
|
||||||
|
|
||||||
|
Fixes:
|
||||||
|
------
|
||||||
|
* Compiler warning if const is casted away, Thanks @gatzka, see [#83](https://github.com/DaveGamble/cJSON/pull/83)
|
||||||
|
* Fix compile error with strict-overflow on PowerPC, see [#85](https://github.com/DaveGamble/cJSON/issues/85)
|
||||||
|
* Fix typo in the README, thanks @MicroJoe, see [#88](https://github.com/DaveGamble/cJSON/pull/88)
|
||||||
|
* Add compile flag for compatibility with C++ compilers
|
||||||
|
|
||||||
|
1.1.0 (Dec 6, 2016)
|
||||||
|
=====
|
||||||
|
* Add a function `cJSON_PrintPreallocated` to print to a preallocated buffer, thanks @ChisholmKyle, see [#72](https://github.com/DaveGamble/cJSON/pull/72)
|
||||||
|
* More compiler warnings when using Clang or GCC, thanks @gatzka, see [#75](https://github.com/DaveGamble/cJSON/pull/75), [#78](https://github.com/DaveGamble/cJSON/pull/78)
|
||||||
|
* fixed a memory leak in `cJSON_Duplicate`, thanks @alperakcan, see [#81](https://github.com/DaveGamble/cJSON/pull/81)
|
||||||
|
* fix the `ENABLE_CUSTOM_COMPILER_FLAGS` cmake option
|
||||||
|
|
||||||
|
1.0.2 (Nov 25, 2016)
|
||||||
|
=====
|
||||||
|
* Rename internal boolean type, see [#71](https://github.com/DaveGamble/cJSON/issues/71).
|
||||||
|
|
||||||
|
1.0.1 (Nov 20, 2016)
|
||||||
|
=====
|
||||||
|
Small bugfix release.
|
||||||
|
* Fixes a bug with the use of the cJSON structs type in cJSON_Utils, see [d47339e](https://github.com/DaveGamble/cJSON/commit/d47339e2740360e6e0994527d5e4752007480f3a)
|
||||||
|
* improve code readability
|
||||||
|
* initialize all variables
|
||||||
|
|
||||||
|
1.0.0 (Nov 17, 2016)
|
||||||
|
=====
|
||||||
|
This is the first official versioned release of cJSON. It provides an API version for the shared library and improved Makefile and CMake build files.
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
set(CMAKE_LEGACY_CYGWIN_WIN32 0)
|
||||||
|
cmake_minimum_required(VERSION 3.5)
|
||||||
|
|
||||||
|
project(cJSON
|
||||||
|
VERSION 1.7.19
|
||||||
|
LANGUAGES C)
|
||||||
|
|
||||||
|
cmake_policy(SET CMP0054 NEW) # set CMP0054 policy
|
||||||
|
|
||||||
|
include(GNUInstallDirs)
|
||||||
|
|
||||||
|
set(CJSON_VERSION_SO 1)
|
||||||
|
set(CJSON_UTILS_VERSION_SO 1)
|
||||||
|
|
||||||
|
set(custom_compiler_flags)
|
||||||
|
|
||||||
|
include(CheckCCompilerFlag)
|
||||||
|
option(ENABLE_CUSTOM_COMPILER_FLAGS "Enables custom compiler flags" ON)
|
||||||
|
if (ENABLE_CUSTOM_COMPILER_FLAGS)
|
||||||
|
if (("${CMAKE_C_COMPILER_ID}" STREQUAL "Clang") OR ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU"))
|
||||||
|
list(APPEND custom_compiler_flags
|
||||||
|
-std=c89
|
||||||
|
-pedantic
|
||||||
|
-Wall
|
||||||
|
-Wextra
|
||||||
|
-Werror
|
||||||
|
-Wstrict-prototypes
|
||||||
|
-Wwrite-strings
|
||||||
|
-Wshadow
|
||||||
|
-Winit-self
|
||||||
|
-Wcast-align
|
||||||
|
-Wformat=2
|
||||||
|
-Wmissing-prototypes
|
||||||
|
-Wstrict-overflow=2
|
||||||
|
-Wcast-qual
|
||||||
|
-Wundef
|
||||||
|
-Wswitch-default
|
||||||
|
-Wconversion
|
||||||
|
-Wc++-compat
|
||||||
|
-fstack-protector-strong
|
||||||
|
-Wcomma
|
||||||
|
-Wdouble-promotion
|
||||||
|
-Wparentheses
|
||||||
|
-Wformat-overflow
|
||||||
|
-Wunused-macros
|
||||||
|
-Wmissing-variable-declarations
|
||||||
|
-Wused-but-marked-unused
|
||||||
|
-Wswitch-enum
|
||||||
|
)
|
||||||
|
elseif("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC")
|
||||||
|
# Disable warning c4001 - nonstandard extension 'single line comment' was used
|
||||||
|
# Define _CRT_SECURE_NO_WARNINGS to disable deprecation warnings for "insecure" C library functions
|
||||||
|
list(APPEND custom_compiler_flags
|
||||||
|
/GS
|
||||||
|
/Za
|
||||||
|
/sdl
|
||||||
|
/W4
|
||||||
|
/wd4001
|
||||||
|
/D_CRT_SECURE_NO_WARNINGS
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(ENABLE_SANITIZERS "Enables AddressSanitizer and UndefinedBehaviorSanitizer." OFF)
|
||||||
|
if (ENABLE_SANITIZERS)
|
||||||
|
list(APPEND custom_compiler_flags
|
||||||
|
-fno-omit-frame-pointer
|
||||||
|
-fsanitize=address
|
||||||
|
-fsanitize=undefined
|
||||||
|
-fsanitize=float-cast-overflow
|
||||||
|
-fsanitize-address-use-after-scope
|
||||||
|
-fsanitize=integer
|
||||||
|
-fno-sanitize-recover
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(ENABLE_SAFE_STACK "Enables the SafeStack instrumentation pass by the Code Pointer Integrity Project" OFF)
|
||||||
|
if (ENABLE_SAFE_STACK)
|
||||||
|
if (ENABLE_SANITIZERS)
|
||||||
|
message(FATAL_ERROR "ENABLE_SAFE_STACK cannot be used in combination with ENABLE_SANITIZERS")
|
||||||
|
endif()
|
||||||
|
list(APPEND custom_compiler_flags
|
||||||
|
-fsanitize=safe-stack
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(ENABLE_PUBLIC_SYMBOLS "Export library symbols." On)
|
||||||
|
if (ENABLE_PUBLIC_SYMBOLS)
|
||||||
|
list(APPEND custom_compiler_flags -fvisibility=hidden)
|
||||||
|
add_definitions(-DCJSON_EXPORT_SYMBOLS -DCJSON_API_VISIBILITY)
|
||||||
|
endif()
|
||||||
|
option(ENABLE_HIDDEN_SYMBOLS "Hide library symbols." Off)
|
||||||
|
if (ENABLE_HIDDEN_SYMBOLS)
|
||||||
|
add_definitions(-DCJSON_HIDE_SYMBOLS -UCJSON_API_VISIBILITY)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# apply custom compiler flags
|
||||||
|
foreach(compiler_flag ${custom_compiler_flags})
|
||||||
|
#remove problematic characters
|
||||||
|
string(REGEX REPLACE "[^a-zA-Z0-9]" "" current_variable ${compiler_flag})
|
||||||
|
|
||||||
|
CHECK_C_COMPILER_FLAG(${compiler_flag} "FLAG_SUPPORTED_${current_variable}")
|
||||||
|
if (FLAG_SUPPORTED_${current_variable})
|
||||||
|
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${compiler_flag}")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
|
||||||
|
option(ENABLE_TARGET_EXPORT "Enable exporting of CMake targets. Disable when it causes problems!" ON)
|
||||||
|
|
||||||
|
#cJSON
|
||||||
|
set(CJSON_LIB cjson)
|
||||||
|
|
||||||
|
file(GLOB HEADERS cJSON.h)
|
||||||
|
set(SOURCES cJSON.c)
|
||||||
|
|
||||||
|
option(BUILD_SHARED_AND_STATIC_LIBS "Build both shared and static libraries" Off)
|
||||||
|
option(CJSON_OVERRIDE_BUILD_SHARED_LIBS "Override BUILD_SHARED_LIBS with CJSON_BUILD_SHARED_LIBS" OFF)
|
||||||
|
option(CJSON_BUILD_SHARED_LIBS "Overrides BUILD_SHARED_LIBS if CJSON_OVERRIDE_BUILD_SHARED_LIBS is enabled" ON)
|
||||||
|
option(ENABLE_CJSON_VERSION_SO "Enables cJSON so version" ON)
|
||||||
|
|
||||||
|
if ((CJSON_OVERRIDE_BUILD_SHARED_LIBS AND CJSON_BUILD_SHARED_LIBS) OR ((NOT CJSON_OVERRIDE_BUILD_SHARED_LIBS) AND BUILD_SHARED_LIBS))
|
||||||
|
set(CJSON_LIBRARY_TYPE SHARED)
|
||||||
|
else()
|
||||||
|
set(CJSON_LIBRARY_TYPE STATIC)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
|
||||||
|
if (NOT BUILD_SHARED_AND_STATIC_LIBS)
|
||||||
|
add_library("${CJSON_LIB}" "${CJSON_LIBRARY_TYPE}" "${HEADERS}" "${SOURCES}")
|
||||||
|
else()
|
||||||
|
# See https://cmake.org/Wiki/CMake_FAQ#How_do_I_make_my_shared_and_static_libraries_have_the_same_root_name.2C_but_different_suffixes.3F
|
||||||
|
add_library("${CJSON_LIB}" SHARED "${HEADERS}" "${SOURCES}")
|
||||||
|
add_library("${CJSON_LIB}-static" STATIC "${HEADERS}" "${SOURCES}")
|
||||||
|
set_target_properties("${CJSON_LIB}-static" PROPERTIES OUTPUT_NAME "${CJSON_LIB}")
|
||||||
|
set_target_properties("${CJSON_LIB}-static" PROPERTIES PREFIX "lib")
|
||||||
|
endif()
|
||||||
|
if (NOT WIN32)
|
||||||
|
target_link_libraries("${CJSON_LIB}" m)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/library_config/libcjson.pc.in"
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/libcjson.pc" @ONLY)
|
||||||
|
|
||||||
|
install(FILES cJSON.h DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}/cjson")
|
||||||
|
install (FILES "${CMAKE_CURRENT_BINARY_DIR}/libcjson.pc" DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/pkgconfig")
|
||||||
|
install(TARGETS "${CJSON_LIB}"
|
||||||
|
EXPORT "${CJSON_LIB}"
|
||||||
|
ARCHIVE DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}"
|
||||||
|
LIBRARY DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}"
|
||||||
|
RUNTIME DESTINATION "${CMAKE_INSTALL_FULL_BINDIR}"
|
||||||
|
INCLUDES DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}"
|
||||||
|
)
|
||||||
|
if (BUILD_SHARED_AND_STATIC_LIBS)
|
||||||
|
install(TARGETS "${CJSON_LIB}-static"
|
||||||
|
EXPORT "${CJSON_LIB}"
|
||||||
|
ARCHIVE DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}"
|
||||||
|
INCLUDES DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}"
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
if(ENABLE_TARGET_EXPORT)
|
||||||
|
# export library information for CMake projects
|
||||||
|
install(EXPORT "${CJSON_LIB}" DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/cmake/cJSON")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(ENABLE_CJSON_VERSION_SO)
|
||||||
|
set_target_properties("${CJSON_LIB}"
|
||||||
|
PROPERTIES
|
||||||
|
SOVERSION "${CJSON_VERSION_SO}"
|
||||||
|
VERSION "${PROJECT_VERSION}")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#cJSON_Utils
|
||||||
|
option(ENABLE_CJSON_UTILS "Enable building the cJSON_Utils library." OFF)
|
||||||
|
if(ENABLE_CJSON_UTILS)
|
||||||
|
set(CJSON_UTILS_LIB cjson_utils)
|
||||||
|
|
||||||
|
file(GLOB HEADERS_UTILS cJSON_Utils.h)
|
||||||
|
set(SOURCES_UTILS cJSON_Utils.c)
|
||||||
|
|
||||||
|
if (NOT BUILD_SHARED_AND_STATIC_LIBS)
|
||||||
|
add_library("${CJSON_UTILS_LIB}" "${CJSON_LIBRARY_TYPE}" "${HEADERS_UTILS}" "${SOURCES_UTILS}")
|
||||||
|
target_link_libraries("${CJSON_UTILS_LIB}" "${CJSON_LIB}")
|
||||||
|
else()
|
||||||
|
add_library("${CJSON_UTILS_LIB}" SHARED "${HEADERS_UTILS}" "${SOURCES_UTILS}")
|
||||||
|
target_link_libraries("${CJSON_UTILS_LIB}" "${CJSON_LIB}")
|
||||||
|
add_library("${CJSON_UTILS_LIB}-static" STATIC "${HEADERS_UTILS}" "${SOURCES_UTILS}")
|
||||||
|
target_link_libraries("${CJSON_UTILS_LIB}-static" "${CJSON_LIB}-static")
|
||||||
|
set_target_properties("${CJSON_UTILS_LIB}-static" PROPERTIES OUTPUT_NAME "${CJSON_UTILS_LIB}")
|
||||||
|
set_target_properties("${CJSON_UTILS_LIB}-static" PROPERTIES PREFIX "lib")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/library_config/libcjson_utils.pc.in"
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/libcjson_utils.pc" @ONLY)
|
||||||
|
|
||||||
|
install(TARGETS "${CJSON_UTILS_LIB}"
|
||||||
|
EXPORT "${CJSON_UTILS_LIB}"
|
||||||
|
ARCHIVE DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}"
|
||||||
|
LIBRARY DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}"
|
||||||
|
RUNTIME DESTINATION "${CMAKE_INSTALL_FULL_BINDIR}"
|
||||||
|
INCLUDES DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}"
|
||||||
|
)
|
||||||
|
if (BUILD_SHARED_AND_STATIC_LIBS)
|
||||||
|
install(TARGETS "${CJSON_UTILS_LIB}-static"
|
||||||
|
EXPORT "${CJSON_UTILS_LIB}"
|
||||||
|
ARCHIVE DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}"
|
||||||
|
INCLUDES DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}"
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
install(FILES cJSON_Utils.h DESTINATION "${CMAKE_INSTALL_FULL_INCLUDEDIR}/cjson")
|
||||||
|
install (FILES "${CMAKE_CURRENT_BINARY_DIR}/libcjson_utils.pc" DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/pkgconfig")
|
||||||
|
if(ENABLE_TARGET_EXPORT)
|
||||||
|
# export library information for CMake projects
|
||||||
|
install(EXPORT "${CJSON_UTILS_LIB}" DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/cmake/cJSON")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(ENABLE_CJSON_VERSION_SO)
|
||||||
|
set_target_properties("${CJSON_UTILS_LIB}"
|
||||||
|
PROPERTIES
|
||||||
|
SOVERSION "${CJSON_UTILS_VERSION_SO}"
|
||||||
|
VERSION "${PROJECT_VERSION}")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# create the other package config files
|
||||||
|
configure_file(
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/library_config/cJSONConfig.cmake.in"
|
||||||
|
${PROJECT_BINARY_DIR}/cJSONConfig.cmake @ONLY)
|
||||||
|
configure_file(
|
||||||
|
"${CMAKE_CURRENT_SOURCE_DIR}/library_config/cJSONConfigVersion.cmake.in"
|
||||||
|
${PROJECT_BINARY_DIR}/cJSONConfigVersion.cmake @ONLY)
|
||||||
|
|
||||||
|
if(ENABLE_TARGET_EXPORT)
|
||||||
|
# Install package config files
|
||||||
|
install(FILES ${PROJECT_BINARY_DIR}/cJSONConfig.cmake
|
||||||
|
${PROJECT_BINARY_DIR}/cJSONConfigVersion.cmake
|
||||||
|
DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/cmake/cJSON")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(ENABLE_CJSON_TEST "Enable building cJSON test" ON)
|
||||||
|
if(ENABLE_CJSON_TEST)
|
||||||
|
enable_testing()
|
||||||
|
|
||||||
|
set(TEST_CJSON cJSON_test)
|
||||||
|
add_executable("${TEST_CJSON}" test.c)
|
||||||
|
target_link_libraries("${TEST_CJSON}" "${CJSON_LIB}")
|
||||||
|
|
||||||
|
add_test(NAME ${TEST_CJSON} COMMAND "${CMAKE_CURRENT_BINARY_DIR}/${TEST_CJSON}")
|
||||||
|
|
||||||
|
# Disable -fsanitize=float-divide-by-zero for cJSON_test
|
||||||
|
if (FLAG_SUPPORTED_fsanitizefloatdividebyzero)
|
||||||
|
if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12")
|
||||||
|
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-sanitize=float-divide-by-zero")
|
||||||
|
else()
|
||||||
|
target_compile_options(${TEST_CJSON} PRIVATE "-fno-sanitize=float-divide-by-zero")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#"check" target that automatically builds everything and runs the tests
|
||||||
|
add_custom_target(check
|
||||||
|
COMMAND ${CMAKE_CTEST_COMMAND} --output-on-failure
|
||||||
|
DEPENDS ${TEST_CJSON})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
#Create the uninstall target
|
||||||
|
option(ENABLE_CJSON_UNINSTALL "Enable creating uninstall target" ON)
|
||||||
|
if(ENABLE_CJSON_UNINSTALL)
|
||||||
|
add_custom_target(uninstall "${CMAKE_COMMAND}" -P
|
||||||
|
"${PROJECT_SOURCE_DIR}/library_config/uninstall.cmake")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Enable the use of locales
|
||||||
|
option(ENABLE_LOCALES "Enable the use of locales" ON)
|
||||||
|
if(ENABLE_LOCALES)
|
||||||
|
add_definitions(-DENABLE_LOCALES)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
add_subdirectory(tests)
|
||||||
|
add_subdirectory(fuzzing)
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
Contributors
|
||||||
|
============
|
||||||
|
|
||||||
|
Original Author:
|
||||||
|
- [Dave Gamble](https://github.com/DaveGamble)
|
||||||
|
|
||||||
|
Current Maintainer:
|
||||||
|
- [Max Bruckner](https://github.com/FSMaxB)
|
||||||
|
- [Alan Wang](https://github.com/Alanscut)
|
||||||
|
|
||||||
|
Contributors:
|
||||||
|
* [Ajay Bhargav](https://github.com/ajaybhargav)
|
||||||
|
* [AlexanderVasiljev](https://github.com/AlexanderVasiljev)
|
||||||
|
* [Alper Akcan](https://github.com/alperakcan)
|
||||||
|
* [Andrew Tang](https://github.com/singku)
|
||||||
|
* [Andy](https://github.com/mlh0101)
|
||||||
|
* [Anton Sergeev](https://github.com/anton-sergeev)
|
||||||
|
* [Benbuck Nason](https://github.com/bnason-nf)
|
||||||
|
* [Bernt Johan Damslora](https://github.com/bjda)
|
||||||
|
* [Bob Kocisko](https://github.com/bobkocisko)
|
||||||
|
* [Christian Schulze](https://github.com/ChristianSch)
|
||||||
|
* [Casperinous](https://github.com/Casperinous)
|
||||||
|
* [ChenYuan](https://github.com/zjuchenyuan)
|
||||||
|
* [Debora Grosse](https://github.com/DeboraG)
|
||||||
|
* [dieyushi](https://github.com/dieyushi)
|
||||||
|
* [Dōngwén Huáng (黄东文)](https://github.com/DongwenHuang)
|
||||||
|
* [Dominik](https://github.com/DL6ER)
|
||||||
|
* [Donough Liu](https://github.com/ldm0)
|
||||||
|
* [Erez Oxman](https://github.com/erez-o)
|
||||||
|
* Eswar Yaganti
|
||||||
|
* [Evan Todd](https://github.com/etodd)
|
||||||
|
* [Fabrice Fontaine](https://github.com/ffontaine)
|
||||||
|
* Ian Mobley
|
||||||
|
* Irwan Djadjadi
|
||||||
|
* [hopper-vul](https://github.com/hopper-vul)
|
||||||
|
* [HuKeping](https://github.com/HuKeping)
|
||||||
|
* [IvanVoid](https://github.com/npi3pak)
|
||||||
|
* [Jakub Wilk](https://github.com/jwilk)
|
||||||
|
* [Jiri Zouhar](https://github.com/loigu)
|
||||||
|
* [Jonathan Fether](https://github.com/jfether)
|
||||||
|
* [Joshua Arulsamy](https://github.com/jarulsamy)
|
||||||
|
* [Julian Ste](https://github.com/julian-st)
|
||||||
|
* [Julián Vásquez](https://github.com/juvasquezg)
|
||||||
|
* [Junbo Zheng](https://github.com/Junbo-Zheng)
|
||||||
|
* [Kevin Branigan](https://github.com/kbranigan)
|
||||||
|
* [Kevin Sapper](https://github.com/sappo)
|
||||||
|
* [Kyle Chisholm](https://github.com/ChisholmKyle)
|
||||||
|
* [Linus Wallgren](https://github.com/ecksun)
|
||||||
|
* [Luo Jin](https://github.com/Up-wind)
|
||||||
|
* [Max](https://github.com/maebex)
|
||||||
|
* [MaxBrandtner](https://github.com/MaxBrandtner)
|
||||||
|
* [Mateusz Szafoni](https://github.com/raiden00pl)
|
||||||
|
* Mike Pontillo
|
||||||
|
* [miaoerduo](https://github.com/miaoerduo)
|
||||||
|
* [mohawk2](https://github.com/mohawk2)
|
||||||
|
* [Mike Jerris](https://github.com/mjerris)
|
||||||
|
* [Mike Robinson](https://github.com/mhrobinson)
|
||||||
|
* [Moorthy](https://github.com/moorthy-bs)
|
||||||
|
* [myd7349](https://github.com/myd7349)
|
||||||
|
* [NancyLi1013](https://github.com/NancyLi1013)
|
||||||
|
* [Orri](https://github.com/sbvoxel)
|
||||||
|
* Paulo Antonio Alvarez
|
||||||
|
* [Paweł Malowany](https://github.com/PawelMalowany)
|
||||||
|
* [Pawel Winogrodzki](https://github.com/PawelWMS)
|
||||||
|
* [prefetchnta](https://github.com/prefetchnta)
|
||||||
|
* [Rafael Leal Dias](https://github.com/rafaeldias)
|
||||||
|
* [Randy](https://github.com/randy408)
|
||||||
|
* [raiden00pl](https://github.com/raiden00pl)
|
||||||
|
* [Robin Mallinson](https://github.com/rmallins)
|
||||||
|
* [Rod Vagg](https://github.com/rvagg)
|
||||||
|
* [Roland Meertens](https://github.com/rmeertens)
|
||||||
|
* [Romain Porte](https://github.com/MicroJoe)
|
||||||
|
* [SANJEEV BA](https://github.com/basanjeev)
|
||||||
|
* [Sang-Heon Jeon](https://github.com/lntuition)
|
||||||
|
* [Sayan Bandyopadhyay](https://github.com/saynb)
|
||||||
|
* [Simon Sobisch](https://github.com/GitMensch)
|
||||||
|
* [Simon Ricaldone](https://github.com/simon-p-r)
|
||||||
|
* [Stoian Ivanov](https://github.com/sdrsdr)
|
||||||
|
* [SuperH-0630](https://github.com/SuperH-0630)
|
||||||
|
* [Square789](https://github.com/Square789)
|
||||||
|
* [Stephan Gatzka](https://github.com/gatzka)
|
||||||
|
* [Tony Langhammer](https://github.com/BigBrainAFK)
|
||||||
|
* [Vemake](https://github.com/vemakereporter)
|
||||||
|
* [vwvw](https://github.com/vwvw)
|
||||||
|
* [warmsocks](https://github.com/warmsocks)
|
||||||
|
* [Wei Tan](https://github.com/tan-wei)
|
||||||
|
* [Weston Schmidt](https://github.com/schmidtw)
|
||||||
|
* [xiaomianhehe](https://github.com/xiaomianhehe)
|
||||||
|
* [yangfl](https://github.com/yangfl)
|
||||||
|
* [yuta-oxo](https://github.com/yuta-oxo)
|
||||||
|
* [Zach Hindes](https://github.com/zhindes)
|
||||||
|
* [Zhao Zhixu](https://github.com/zhaozhixu)
|
||||||
|
* [10km](https://github.com/10km)
|
||||||
|
|
||||||
|
And probably more people on [SourceForge](https://sourceforge.net/p/cjson/bugs/search/?q=status%3Aclosed-rejected+or+status%3Aclosed-out-of-date+or+status%3Awont-fix+or+status%3Aclosed-fixed+or+status%3Aclosed&page=0)
|
||||||
|
|
||||||
|
Also thanks to all the people who reported bugs and suggested new features.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
CJSON_OBJ = cJSON.o
|
||||||
|
UTILS_OBJ = cJSON_Utils.o
|
||||||
|
CJSON_LIBNAME = libcjson
|
||||||
|
UTILS_LIBNAME = libcjson_utils
|
||||||
|
CJSON_TEST = cJSON_test
|
||||||
|
|
||||||
|
CJSON_TEST_SRC = cJSON.c test.c
|
||||||
|
|
||||||
|
LDLIBS = -lm
|
||||||
|
|
||||||
|
LIBVERSION = 1.7.19
|
||||||
|
CJSON_SOVERSION = 1
|
||||||
|
UTILS_SOVERSION = 1
|
||||||
|
|
||||||
|
CJSON_SO_LDFLAG=-Wl,-soname=$(CJSON_LIBNAME).so.$(CJSON_SOVERSION)
|
||||||
|
UTILS_SO_LDFLAG=-Wl,-soname=$(UTILS_LIBNAME).so.$(UTILS_SOVERSION)
|
||||||
|
|
||||||
|
PREFIX ?= /usr/local
|
||||||
|
INCLUDE_PATH ?= include/cjson
|
||||||
|
LIBRARY_PATH ?= lib
|
||||||
|
|
||||||
|
INSTALL_INCLUDE_PATH = $(DESTDIR)$(PREFIX)/$(INCLUDE_PATH)
|
||||||
|
INSTALL_LIBRARY_PATH = $(DESTDIR)$(PREFIX)/$(LIBRARY_PATH)
|
||||||
|
|
||||||
|
INSTALL ?= cp -a
|
||||||
|
|
||||||
|
CC = gcc -std=c89
|
||||||
|
|
||||||
|
# validate gcc version for use fstack-protector-strong
|
||||||
|
MIN_GCC_VERSION = "4.9"
|
||||||
|
GCC_VERSION := "`$(CC) -dumpversion`"
|
||||||
|
IS_GCC_ABOVE_MIN_VERSION := $(shell expr "$(GCC_VERSION)" ">=" "$(MIN_GCC_VERSION)")
|
||||||
|
ifeq "$(IS_GCC_ABOVE_MIN_VERSION)" "1"
|
||||||
|
CFLAGS += -fstack-protector-strong
|
||||||
|
else
|
||||||
|
CFLAGS += -fstack-protector
|
||||||
|
endif
|
||||||
|
|
||||||
|
PIC_FLAGS = -fPIC
|
||||||
|
R_CFLAGS = $(PIC_FLAGS) -pedantic -Wall -Werror -Wstrict-prototypes -Wwrite-strings -Wshadow -Winit-self -Wcast-align -Wformat=2 -Wmissing-prototypes -Wstrict-overflow=2 -Wcast-qual -Wc++-compat -Wundef -Wswitch-default -Wconversion $(CFLAGS)
|
||||||
|
|
||||||
|
uname := $(shell sh -c 'uname -s 2>/dev/null || echo false')
|
||||||
|
|
||||||
|
#library file extensions
|
||||||
|
SHARED = so
|
||||||
|
STATIC = a
|
||||||
|
|
||||||
|
## create dynamic (shared) library on Darwin (base OS for MacOSX and IOS)
|
||||||
|
ifeq (Darwin, $(uname))
|
||||||
|
SHARED = dylib
|
||||||
|
CJSON_SO_LDFLAG = ""
|
||||||
|
UTILS_SO_LDFLAG = ""
|
||||||
|
endif
|
||||||
|
|
||||||
|
#cJSON library names
|
||||||
|
CJSON_SHARED = $(CJSON_LIBNAME).$(SHARED)
|
||||||
|
CJSON_SHARED_VERSION = $(CJSON_LIBNAME).$(SHARED).$(LIBVERSION)
|
||||||
|
CJSON_SHARED_SO = $(CJSON_LIBNAME).$(SHARED).$(CJSON_SOVERSION)
|
||||||
|
CJSON_STATIC = $(CJSON_LIBNAME).$(STATIC)
|
||||||
|
|
||||||
|
#cJSON_Utils library names
|
||||||
|
UTILS_SHARED = $(UTILS_LIBNAME).$(SHARED)
|
||||||
|
UTILS_SHARED_VERSION = $(UTILS_LIBNAME).$(SHARED).$(LIBVERSION)
|
||||||
|
UTILS_SHARED_SO = $(UTILS_LIBNAME).$(SHARED).$(UTILS_SOVERSION)
|
||||||
|
UTILS_STATIC = $(UTILS_LIBNAME).$(STATIC)
|
||||||
|
|
||||||
|
SHARED_CMD = $(CC) -shared -o
|
||||||
|
|
||||||
|
.PHONY: all shared static tests clean install
|
||||||
|
|
||||||
|
all: shared static tests
|
||||||
|
|
||||||
|
shared: $(CJSON_SHARED) $(UTILS_SHARED)
|
||||||
|
|
||||||
|
static: $(CJSON_STATIC) $(UTILS_STATIC)
|
||||||
|
|
||||||
|
tests: $(CJSON_TEST)
|
||||||
|
|
||||||
|
test: tests
|
||||||
|
./$(CJSON_TEST)
|
||||||
|
|
||||||
|
.c.o:
|
||||||
|
$(CC) -c $(R_CFLAGS) $<
|
||||||
|
|
||||||
|
#tests
|
||||||
|
#cJSON
|
||||||
|
$(CJSON_TEST): $(CJSON_TEST_SRC) cJSON.h
|
||||||
|
$(CC) $(R_CFLAGS) $(CJSON_TEST_SRC) -o $@ $(LDLIBS) -I.
|
||||||
|
|
||||||
|
#static libraries
|
||||||
|
#cJSON
|
||||||
|
$(CJSON_STATIC): $(CJSON_OBJ)
|
||||||
|
$(AR) rcs $@ $<
|
||||||
|
#cJSON_Utils
|
||||||
|
$(UTILS_STATIC): $(UTILS_OBJ)
|
||||||
|
$(AR) rcs $@ $<
|
||||||
|
|
||||||
|
#shared libraries .so.1.0.0
|
||||||
|
#cJSON
|
||||||
|
$(CJSON_SHARED_VERSION): $(CJSON_OBJ)
|
||||||
|
$(CC) -shared -o $@ $< $(CJSON_SO_LDFLAG) $(LDFLAGS)
|
||||||
|
#cJSON_Utils
|
||||||
|
$(UTILS_SHARED_VERSION): $(UTILS_OBJ)
|
||||||
|
$(CC) -shared -o $@ $< $(CJSON_OBJ) $(UTILS_SO_LDFLAG) $(LDFLAGS)
|
||||||
|
|
||||||
|
#objects
|
||||||
|
#cJSON
|
||||||
|
$(CJSON_OBJ): cJSON.c cJSON.h
|
||||||
|
#cJSON_Utils
|
||||||
|
$(UTILS_OBJ): cJSON_Utils.c cJSON_Utils.h cJSON.h
|
||||||
|
|
||||||
|
|
||||||
|
#links .so -> .so.1 -> .so.1.0.0
|
||||||
|
#cJSON
|
||||||
|
$(CJSON_SHARED_SO): $(CJSON_SHARED_VERSION)
|
||||||
|
ln -s $(CJSON_SHARED_VERSION) $(CJSON_SHARED_SO)
|
||||||
|
$(CJSON_SHARED): $(CJSON_SHARED_SO)
|
||||||
|
ln -s $(CJSON_SHARED_SO) $(CJSON_SHARED)
|
||||||
|
#cJSON_Utils
|
||||||
|
$(UTILS_SHARED_SO): $(UTILS_SHARED_VERSION)
|
||||||
|
ln -s $(UTILS_SHARED_VERSION) $(UTILS_SHARED_SO)
|
||||||
|
$(UTILS_SHARED): $(UTILS_SHARED_SO)
|
||||||
|
ln -s $(UTILS_SHARED_SO) $(UTILS_SHARED)
|
||||||
|
|
||||||
|
#install
|
||||||
|
#cJSON
|
||||||
|
install-cjson:
|
||||||
|
mkdir -p $(INSTALL_LIBRARY_PATH) $(INSTALL_INCLUDE_PATH)
|
||||||
|
$(INSTALL) cJSON.h $(INSTALL_INCLUDE_PATH)
|
||||||
|
$(INSTALL) $(CJSON_SHARED) $(CJSON_SHARED_SO) $(CJSON_SHARED_VERSION) $(INSTALL_LIBRARY_PATH)
|
||||||
|
#cJSON_Utils
|
||||||
|
install-utils: install-cjson
|
||||||
|
$(INSTALL) cJSON_Utils.h $(INSTALL_INCLUDE_PATH)
|
||||||
|
$(INSTALL) $(UTILS_SHARED) $(UTILS_SHARED_SO) $(UTILS_SHARED_VERSION) $(INSTALL_LIBRARY_PATH)
|
||||||
|
|
||||||
|
install: install-cjson install-utils
|
||||||
|
|
||||||
|
#uninstall
|
||||||
|
#cJSON
|
||||||
|
uninstall-cjson: uninstall-utils
|
||||||
|
$(RM) $(INSTALL_LIBRARY_PATH)/$(CJSON_SHARED)
|
||||||
|
$(RM) $(INSTALL_LIBRARY_PATH)/$(CJSON_SHARED_VERSION)
|
||||||
|
$(RM) $(INSTALL_LIBRARY_PATH)/$(CJSON_SHARED_SO)
|
||||||
|
$(RM) $(INSTALL_INCLUDE_PATH)/cJSON.h
|
||||||
|
|
||||||
|
#cJSON_Utils
|
||||||
|
uninstall-utils:
|
||||||
|
$(RM) $(INSTALL_LIBRARY_PATH)/$(UTILS_SHARED)
|
||||||
|
$(RM) $(INSTALL_LIBRARY_PATH)/$(UTILS_SHARED_VERSION)
|
||||||
|
$(RM) $(INSTALL_LIBRARY_PATH)/$(UTILS_SHARED_SO)
|
||||||
|
$(RM) $(INSTALL_INCLUDE_PATH)/cJSON_Utils.h
|
||||||
|
|
||||||
|
remove-dir:
|
||||||
|
$(if $(wildcard $(INSTALL_LIBRARY_PATH)/*.*),,rmdir $(INSTALL_LIBRARY_PATH))
|
||||||
|
$(if $(wildcard $(INSTALL_INCLUDE_PATH)/*.*),,rmdir $(INSTALL_INCLUDE_PATH))
|
||||||
|
|
||||||
|
uninstall: uninstall-utils uninstall-cjson remove-dir
|
||||||
|
|
||||||
|
clean:
|
||||||
|
$(RM) $(CJSON_OBJ) $(UTILS_OBJ) #delete object files
|
||||||
|
$(RM) $(CJSON_SHARED) $(CJSON_SHARED_VERSION) $(CJSON_SHARED_SO) $(CJSON_STATIC) #delete cJSON
|
||||||
|
$(RM) $(UTILS_SHARED) $(UTILS_SHARED_VERSION) $(UTILS_SHARED_SO) $(UTILS_STATIC) #delete cJSON_Utils
|
||||||
|
$(RM) $(CJSON_TEST) #delete test
|
||||||
@@ -0,0 +1,590 @@
|
|||||||
|
# cJSON
|
||||||
|
|
||||||
|
Ultralightweight JSON parser in ANSI C.
|
||||||
|
|
||||||
|
## Table of contents
|
||||||
|
* [License](#license)
|
||||||
|
* [Usage](#usage)
|
||||||
|
* [Welcome to cJSON](#welcome-to-cjson)
|
||||||
|
* [Building](#building)
|
||||||
|
* [Copying the source](#copying-the-source)
|
||||||
|
* [CMake](#cmake)
|
||||||
|
* [Makefile](#makefile)
|
||||||
|
* [Meson](#meson)
|
||||||
|
* [Vcpkg](#Vcpkg)
|
||||||
|
* [Including cJSON](#including-cjson)
|
||||||
|
* [Data Structure](#data-structure)
|
||||||
|
* [Working with the data structure](#working-with-the-data-structure)
|
||||||
|
* [Basic types](#basic-types)
|
||||||
|
* [Arrays](#arrays)
|
||||||
|
* [Objects](#objects)
|
||||||
|
* [Parsing JSON](#parsing-json)
|
||||||
|
* [Printing JSON](#printing-json)
|
||||||
|
* [Example](#example)
|
||||||
|
* [Printing](#printing)
|
||||||
|
* [Parsing](#parsing)
|
||||||
|
* [Caveats](#caveats)
|
||||||
|
* [Zero Character](#zero-character)
|
||||||
|
* [Character Encoding](#character-encoding)
|
||||||
|
* [C Standard](#c-standard)
|
||||||
|
* [Floating Point Numbers](#floating-point-numbers)
|
||||||
|
* [Deep Nesting Of Arrays And Objects](#deep-nesting-of-arrays-and-objects)
|
||||||
|
* [Thread Safety](#thread-safety)
|
||||||
|
* [Case Sensitivity](#case-sensitivity)
|
||||||
|
* [Duplicate Object Members](#duplicate-object-members)
|
||||||
|
* [Enjoy cJSON!](#enjoy-cjson)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
> Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||||
|
>
|
||||||
|
> 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.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Welcome to cJSON.
|
||||||
|
|
||||||
|
cJSON aims to be the dumbest possible parser that you can get your job done with.
|
||||||
|
It's a single file of C, and a single header file.
|
||||||
|
|
||||||
|
JSON is described best here: http://www.json.org/
|
||||||
|
It's like XML, but fat-free. You use it to move data around, store things, or just
|
||||||
|
generally represent your program's state.
|
||||||
|
|
||||||
|
As a library, cJSON exists to take away as much legwork as it can, but not get in your way.
|
||||||
|
As a point of pragmatism (i.e. ignoring the truth), I'm going to say that you can use it
|
||||||
|
in one of two modes: Auto and Manual. Let's have a quick run-through.
|
||||||
|
|
||||||
|
I lifted some JSON from this page: http://www.json.org/fatfree.html
|
||||||
|
That page inspired me to write cJSON, which is a parser that tries to share the same
|
||||||
|
philosophy as JSON itself. Simple, dumb, out of the way.
|
||||||
|
|
||||||
|
### Building
|
||||||
|
|
||||||
|
There are several ways to incorporate cJSON into your project.
|
||||||
|
|
||||||
|
#### copying the source
|
||||||
|
|
||||||
|
Because the entire library is only one C file and one header file, you can just copy `cJSON.h` and `cJSON.c` to your projects source and start using it.
|
||||||
|
|
||||||
|
cJSON is written in ANSI C (C89) in order to support as many platforms and compilers as possible.
|
||||||
|
|
||||||
|
#### CMake
|
||||||
|
|
||||||
|
With CMake, cJSON supports a full blown build system. This way you get the most features. CMake with an equal or higher version than 3.5 is supported. With CMake it is recommended to do an out of tree build, meaning the compiled files are put in a directory separate from the source files. So in order to build cJSON with CMake on a Unix platform, make a `build` directory and run CMake inside it.
|
||||||
|
|
||||||
|
```
|
||||||
|
mkdir build
|
||||||
|
cd build
|
||||||
|
cmake ..
|
||||||
|
```
|
||||||
|
|
||||||
|
This will create a Makefile and a bunch of other files. You can then compile it:
|
||||||
|
|
||||||
|
```
|
||||||
|
make
|
||||||
|
```
|
||||||
|
|
||||||
|
And install it with `make install` if you want. By default it installs the headers `/usr/local/include/cjson` and the libraries to `/usr/local/lib`. It also installs files for pkg-config to make it easier to detect and use an existing installation of CMake. And it installs CMake config files, that can be used by other CMake based projects to discover the library.
|
||||||
|
|
||||||
|
You can change the build process with a list of different options that you can pass to CMake. Turn them on with `On` and off with `Off`:
|
||||||
|
|
||||||
|
* `-DENABLE_CJSON_TEST=On`: Enable building the tests. (on by default)
|
||||||
|
* `-DENABLE_CJSON_UTILS=On`: Enable building cJSON_Utils. (off by default)
|
||||||
|
* `-DENABLE_TARGET_EXPORT=On`: Enable the export of CMake targets. Turn off if it makes problems. (on by default)
|
||||||
|
* `-DENABLE_CUSTOM_COMPILER_FLAGS=On`: Enable custom compiler flags (currently for Clang, GCC and MSVC). Turn off if it makes problems. (on by default)
|
||||||
|
* `-DENABLE_VALGRIND=On`: Run tests with [valgrind](http://valgrind.org). (off by default)
|
||||||
|
* `-DENABLE_SANITIZERS=On`: Compile cJSON with [AddressSanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer) and [UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) enabled (if possible). (off by default)
|
||||||
|
* `-DENABLE_SAFE_STACK`: Enable the [SafeStack](https://clang.llvm.org/docs/SafeStack.html) instrumentation pass. Currently only works with the Clang compiler. (off by default)
|
||||||
|
* `-DBUILD_SHARED_LIBS=On`: Build the shared libraries. (on by default)
|
||||||
|
* `-DBUILD_SHARED_AND_STATIC_LIBS=On`: Build both shared and static libraries. (off by default)
|
||||||
|
* `-DCMAKE_INSTALL_PREFIX=/usr`: Set a prefix for the installation.
|
||||||
|
* `-DENABLE_LOCALES=On`: Enable the usage of localeconv method. ( on by default )
|
||||||
|
* `-DCJSON_OVERRIDE_BUILD_SHARED_LIBS=On`: Enable overriding the value of `BUILD_SHARED_LIBS` with `-DCJSON_BUILD_SHARED_LIBS`.
|
||||||
|
* `-DENABLE_CJSON_VERSION_SO`: Enable cJSON so version. ( on by default )
|
||||||
|
|
||||||
|
If you are packaging cJSON for a distribution of Linux, you would probably take these steps for example:
|
||||||
|
```
|
||||||
|
mkdir build
|
||||||
|
cd build
|
||||||
|
cmake .. -DENABLE_CJSON_UTILS=On -DENABLE_CJSON_TEST=Off -DCMAKE_INSTALL_PREFIX=/usr
|
||||||
|
make
|
||||||
|
make DESTDIR=$pkgdir install
|
||||||
|
```
|
||||||
|
|
||||||
|
On Windows CMake is usually used to create a Visual Studio solution file by running it inside the Developer Command Prompt for Visual Studio, for exact steps follow the official documentation from CMake and Microsoft and use the online search engine of your choice. The descriptions of the the options above still generally apply, although not all of them work on Windows.
|
||||||
|
|
||||||
|
#### Makefile
|
||||||
|
|
||||||
|
**NOTE:** This Method is deprecated. Use CMake if at all possible. Makefile support is limited to fixing bugs.
|
||||||
|
|
||||||
|
If you don't have CMake available, but still have GNU make. You can use the makefile to build cJSON:
|
||||||
|
|
||||||
|
Run this command in the directory with the source code and it will automatically compile static and shared libraries and a little test program (not the full test suite).
|
||||||
|
|
||||||
|
```
|
||||||
|
make all
|
||||||
|
```
|
||||||
|
|
||||||
|
If you want, you can install the compiled library to your system using `make install`. By default it will install the headers in `/usr/local/include/cjson` and the libraries in `/usr/local/lib`. But you can change this behavior by setting the `PREFIX` and `DESTDIR` variables: `make PREFIX=/usr DESTDIR=temp install`. And uninstall them with: `make PREFIX=/usr DESTDIR=temp uninstall`.
|
||||||
|
|
||||||
|
#### Meson
|
||||||
|
|
||||||
|
To make cjson work in a project using meson, the libcjson dependency has to be included:
|
||||||
|
|
||||||
|
```meson
|
||||||
|
project('c-json-example', 'c')
|
||||||
|
|
||||||
|
cjson = dependency('libcjson')
|
||||||
|
|
||||||
|
example = executable(
|
||||||
|
'example',
|
||||||
|
'example.c',
|
||||||
|
dependencies: [cjson],
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
#### Vcpkg
|
||||||
|
|
||||||
|
You can download and install cJSON using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager:
|
||||||
|
```
|
||||||
|
git clone https://github.com/Microsoft/vcpkg.git
|
||||||
|
cd vcpkg
|
||||||
|
./bootstrap-vcpkg.sh
|
||||||
|
./vcpkg integrate install
|
||||||
|
vcpkg install cjson
|
||||||
|
```
|
||||||
|
|
||||||
|
The cJSON port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
|
||||||
|
|
||||||
|
### Including cJSON
|
||||||
|
|
||||||
|
If you installed it via CMake or the Makefile, you can include cJSON like this:
|
||||||
|
|
||||||
|
```c
|
||||||
|
#include <cjson/cJSON.h>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Data Structure
|
||||||
|
|
||||||
|
cJSON represents JSON data using the `cJSON` struct data type:
|
||||||
|
|
||||||
|
```c
|
||||||
|
/* The cJSON structure: */
|
||||||
|
typedef struct cJSON
|
||||||
|
{
|
||||||
|
struct cJSON *next;
|
||||||
|
struct cJSON *prev;
|
||||||
|
struct cJSON *child;
|
||||||
|
int type;
|
||||||
|
char *valuestring;
|
||||||
|
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
|
||||||
|
int valueint;
|
||||||
|
double valuedouble;
|
||||||
|
char *string;
|
||||||
|
} cJSON;
|
||||||
|
```
|
||||||
|
|
||||||
|
An item of this type represents a JSON value. The type is stored in `type` as a bit-flag (**this means that you cannot find out the type by just comparing the value of `type`**).
|
||||||
|
|
||||||
|
To check the type of an item, use the corresponding `cJSON_Is...` function. It does a `NULL` check followed by a type check and returns a boolean value if the item is of this type.
|
||||||
|
|
||||||
|
The type can be one of the following:
|
||||||
|
|
||||||
|
* `cJSON_Invalid` (check with `cJSON_IsInvalid`): Represents an invalid item that doesn't contain any value. You automatically have this type if you set the item to all zero bytes.
|
||||||
|
* `cJSON_False` (check with `cJSON_IsFalse`): Represents a `false` boolean value. You can also check for boolean values in general with `cJSON_IsBool`.
|
||||||
|
* `cJSON_True` (check with `cJSON_IsTrue`): Represents a `true` boolean value. You can also check for boolean values in general with `cJSON_IsBool`.
|
||||||
|
* `cJSON_NULL` (check with `cJSON_IsNull`): Represents a `null` value.
|
||||||
|
* `cJSON_Number` (check with `cJSON_IsNumber`): Represents a number value. The value is stored as a double in `valuedouble` and also in `valueint`. If the number is outside of the range of an integer, `INT_MAX` or `INT_MIN` are used for `valueint`.
|
||||||
|
* `cJSON_String` (check with `cJSON_IsString`): Represents a string value. It is stored in the form of a zero terminated string in `valuestring`.
|
||||||
|
* `cJSON_Array` (check with `cJSON_IsArray`): Represent an array value. This is implemented by pointing `child` to a linked list of `cJSON` items that represent the values in the array. The elements are linked together using `next` and `prev`, where the first element has `prev.next == NULL` and the last element `next == NULL`.
|
||||||
|
* `cJSON_Object` (check with `cJSON_IsObject`): Represents an object value. Objects are stored same way as an array, the only difference is that the items in the object store their keys in `string`.
|
||||||
|
* `cJSON_Raw` (check with `cJSON_IsRaw`): Represents any kind of JSON that is stored as a zero terminated array of characters in `valuestring`. This can be used, for example, to avoid printing the same static JSON over and over again to save performance. cJSON will never create this type when parsing. Also note that cJSON doesn't check if it is valid JSON.
|
||||||
|
|
||||||
|
Additionally there are the following two flags:
|
||||||
|
|
||||||
|
* `cJSON_IsReference`: Specifies that the item that `child` points to and/or `valuestring` is not owned by this item, it is only a reference. So `cJSON_Delete` and other functions will only deallocate this item, not its `child`/`valuestring`.
|
||||||
|
* `cJSON_StringIsConst`: This means that `string` points to a constant string. This means that `cJSON_Delete` and other functions will not try to deallocate `string`.
|
||||||
|
|
||||||
|
### Working with the data structure
|
||||||
|
|
||||||
|
For every value type there is a `cJSON_Create...` function that can be used to create an item of that type.
|
||||||
|
All of these will allocate a `cJSON` struct that can later be deleted with `cJSON_Delete`.
|
||||||
|
Note that you have to delete them at some point, otherwise you will get a memory leak.
|
||||||
|
**Important**: If you have added an item to an array or an object already, you **mustn't** delete it with `cJSON_Delete`. Adding it to an array or object transfers its ownership so that when that array or object is deleted,
|
||||||
|
it gets deleted as well. You also could use `cJSON_SetValuestring` to change a `cJSON_String`'s `valuestring`, and you needn't to free the previous `valuestring` manually.
|
||||||
|
|
||||||
|
#### Basic types
|
||||||
|
|
||||||
|
* **null** is created with `cJSON_CreateNull`
|
||||||
|
* **booleans** are created with `cJSON_CreateTrue`, `cJSON_CreateFalse` or `cJSON_CreateBool`
|
||||||
|
* **numbers** are created with `cJSON_CreateNumber`. This will set both `valuedouble` and `valueint`. If the number is outside of the range of an integer, `INT_MAX` or `INT_MIN` are used for `valueint`
|
||||||
|
* **strings** are created with `cJSON_CreateString` (copies the string) or with `cJSON_CreateStringReference` (directly points to the string. This means that `valuestring` won't be deleted by `cJSON_Delete` and you are responsible for its lifetime, useful for constants)
|
||||||
|
|
||||||
|
#### Arrays
|
||||||
|
|
||||||
|
You can create an empty array with `cJSON_CreateArray`. `cJSON_CreateArrayReference` can be used to create an array that doesn't "own" its content, so its content doesn't get deleted by `cJSON_Delete`.
|
||||||
|
|
||||||
|
To add items to an array, use `cJSON_AddItemToArray` to append items to the end.
|
||||||
|
Using `cJSON_AddItemReferenceToArray` an element can be added as a reference to another item, array or string. This means that `cJSON_Delete` will not delete that items `child` or `valuestring` properties, so no double frees are occurring if they are already used elsewhere.
|
||||||
|
To insert items in the middle, use `cJSON_InsertItemInArray`. It will insert an item at the given 0 based index and shift all the existing items to the right.
|
||||||
|
|
||||||
|
If you want to take an item out of an array at a given index and continue using it, use `cJSON_DetachItemFromArray`, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak.
|
||||||
|
|
||||||
|
Deleting items is done with `cJSON_DeleteItemFromArray`. It works like `cJSON_DetachItemFromArray`, but deletes the detached item via `cJSON_Delete`.
|
||||||
|
|
||||||
|
You can also replace an item in an array in place. Either with `cJSON_ReplaceItemInArray` using an index or with `cJSON_ReplaceItemViaPointer` given a pointer to an element. `cJSON_ReplaceItemViaPointer` will return `0` if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place.
|
||||||
|
|
||||||
|
To get the size of an array, use `cJSON_GetArraySize`. Use `cJSON_GetArrayItem` to get an element at a given index.
|
||||||
|
|
||||||
|
Because an array is stored as a linked list, iterating it via index is inefficient (`O(n²)`), so you can iterate over an array using the `cJSON_ArrayForEach` macro in `O(n)` time complexity.
|
||||||
|
|
||||||
|
#### Objects
|
||||||
|
|
||||||
|
You can create an empty object with `cJSON_CreateObject`. `cJSON_CreateObjectReference` can be used to create an object that doesn't "own" its content, so its content doesn't get deleted by `cJSON_Delete`.
|
||||||
|
|
||||||
|
To add items to an object, use `cJSON_AddItemToObject`. Use `cJSON_AddItemToObjectCS` to add an item to an object with a name that is a constant or reference (key of the item, `string` in the `cJSON` struct), so that it doesn't get freed by `cJSON_Delete`.
|
||||||
|
Using `cJSON_AddItemReferenceToArray` an element can be added as a reference to another object, array or string. This means that `cJSON_Delete` will not delete that items `child` or `valuestring` properties, so no double frees are occurring if they are already used elsewhere.
|
||||||
|
|
||||||
|
If you want to take an item out of an object, use `cJSON_DetachItemFromObjectCaseSensitive`, it will return the detached item, so be sure to assign it to a pointer, otherwise you will have a memory leak.
|
||||||
|
|
||||||
|
Deleting items is done with `cJSON_DeleteItemFromObjectCaseSensitive`. It works like `cJSON_DetachItemFromObjectCaseSensitive` followed by `cJSON_Delete`.
|
||||||
|
|
||||||
|
You can also replace an item in an object in place. Either with `cJSON_ReplaceItemInObjectCaseSensitive` using a key or with `cJSON_ReplaceItemViaPointer` given a pointer to an element. `cJSON_ReplaceItemViaPointer` will return `0` if it fails. What this does internally is to detach the old item, delete it and insert the new item in its place.
|
||||||
|
|
||||||
|
To get the size of an object, you can use `cJSON_GetArraySize`, this works because internally objects are stored as arrays.
|
||||||
|
|
||||||
|
If you want to access an item in an object, use `cJSON_GetObjectItemCaseSensitive`.
|
||||||
|
|
||||||
|
To iterate over an object, you can use the `cJSON_ArrayForEach` macro the same way as for arrays.
|
||||||
|
|
||||||
|
cJSON also provides convenient helper functions for quickly creating a new item and adding it to an object, like `cJSON_AddNullToObject`. They return a pointer to the new item or `NULL` if they failed.
|
||||||
|
|
||||||
|
### Parsing JSON
|
||||||
|
|
||||||
|
Given some JSON in a zero terminated string, you can parse it with `cJSON_Parse`.
|
||||||
|
|
||||||
|
```c
|
||||||
|
cJSON *json = cJSON_Parse(string);
|
||||||
|
```
|
||||||
|
|
||||||
|
Given some JSON in a string (whether zero terminated or not), you can parse it with `cJSON_ParseWithLength`.
|
||||||
|
|
||||||
|
```c
|
||||||
|
cJSON *json = cJSON_ParseWithLength(string, buffer_length);
|
||||||
|
```
|
||||||
|
|
||||||
|
It will parse the JSON and allocate a tree of `cJSON` items that represents it. Once it returns, you are fully responsible for deallocating it after use with `cJSON_Delete`.
|
||||||
|
|
||||||
|
The allocator used by `cJSON_Parse` is `malloc` and `free` by default but can be changed (globally) with `cJSON_InitHooks`.
|
||||||
|
|
||||||
|
If an error occurs a pointer to the position of the error in the input string can be accessed using `cJSON_GetErrorPtr`. Note though that this can produce race conditions in multithreading scenarios, in that case it is better to use `cJSON_ParseWithOpts` with `return_parse_end`.
|
||||||
|
By default, characters in the input string that follow the parsed JSON will not be considered as an error.
|
||||||
|
|
||||||
|
If you want more options, use `cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated)`.
|
||||||
|
`return_parse_end` returns a pointer to the end of the JSON in the input string or the position that an error occurs at (thereby replacing `cJSON_GetErrorPtr` in a thread safe way). `require_null_terminated`, if set to `1` will make it an error if the input string contains data after the JSON.
|
||||||
|
|
||||||
|
If you want more options giving buffer length, use `cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated)`.
|
||||||
|
|
||||||
|
### Printing JSON
|
||||||
|
|
||||||
|
Given a tree of `cJSON` items, you can print them as a string using `cJSON_Print`.
|
||||||
|
|
||||||
|
```c
|
||||||
|
char *string = cJSON_Print(json);
|
||||||
|
```
|
||||||
|
|
||||||
|
It will allocate a string and print a JSON representation of the tree into it. Once it returns, you are fully responsible for deallocating it after use with your allocator. (usually `free`, depends on what has been set with `cJSON_InitHooks`).
|
||||||
|
|
||||||
|
`cJSON_Print` will print with whitespace for formatting. If you want to print without formatting, use `cJSON_PrintUnformatted`.
|
||||||
|
|
||||||
|
If you have a rough idea of how big your resulting string will be, you can use `cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)`. `fmt` is a boolean to turn formatting with whitespace on and off. `prebuffer` specifies the first buffer size to use for printing. `cJSON_Print` currently uses 256 bytes for its first buffer size. Once printing runs out of space, a new buffer is allocated and the old gets copied over before printing is continued.
|
||||||
|
|
||||||
|
These dynamic buffer allocations can be completely avoided by using `cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format)`. It takes a buffer to a pointer to print to and its length. If the length is reached, printing will fail and it returns `0`. In case of success, `1` is returned. Note that you should provide 5 bytes more than is actually needed, because cJSON is not 100% accurate in estimating if the provided memory is enough.
|
||||||
|
|
||||||
|
### Example
|
||||||
|
|
||||||
|
In this example we want to build and parse the following JSON:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "Awesome 4K",
|
||||||
|
"resolutions": [
|
||||||
|
{
|
||||||
|
"width": 1280,
|
||||||
|
"height": 720
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 1920,
|
||||||
|
"height": 1080
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"width": 3840,
|
||||||
|
"height": 2160
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Printing
|
||||||
|
|
||||||
|
Let's build the above JSON and print it to a string:
|
||||||
|
|
||||||
|
```c
|
||||||
|
//create a monitor with a list of supported resolutions
|
||||||
|
//NOTE: Returns a heap allocated string, you are required to free it after use.
|
||||||
|
char *create_monitor(void)
|
||||||
|
{
|
||||||
|
const unsigned int resolution_numbers[3][2] = {
|
||||||
|
{1280, 720},
|
||||||
|
{1920, 1080},
|
||||||
|
{3840, 2160}
|
||||||
|
};
|
||||||
|
char *string = NULL;
|
||||||
|
cJSON *name = NULL;
|
||||||
|
cJSON *resolutions = NULL;
|
||||||
|
cJSON *resolution = NULL;
|
||||||
|
cJSON *width = NULL;
|
||||||
|
cJSON *height = NULL;
|
||||||
|
size_t index = 0;
|
||||||
|
|
||||||
|
cJSON *monitor = cJSON_CreateObject();
|
||||||
|
if (monitor == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
name = cJSON_CreateString("Awesome 4K");
|
||||||
|
if (name == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
/* after creation was successful, immediately add it to the monitor,
|
||||||
|
* thereby transferring ownership of the pointer to it */
|
||||||
|
cJSON_AddItemToObject(monitor, "name", name);
|
||||||
|
|
||||||
|
resolutions = cJSON_CreateArray();
|
||||||
|
if (resolutions == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(monitor, "resolutions", resolutions);
|
||||||
|
|
||||||
|
for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
|
||||||
|
{
|
||||||
|
resolution = cJSON_CreateObject();
|
||||||
|
if (resolution == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToArray(resolutions, resolution);
|
||||||
|
|
||||||
|
width = cJSON_CreateNumber(resolution_numbers[index][0]);
|
||||||
|
if (width == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(resolution, "width", width);
|
||||||
|
|
||||||
|
height = cJSON_CreateNumber(resolution_numbers[index][1]);
|
||||||
|
if (height == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(resolution, "height", height);
|
||||||
|
}
|
||||||
|
|
||||||
|
string = cJSON_Print(monitor);
|
||||||
|
if (string == NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to print monitor.\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
end:
|
||||||
|
cJSON_Delete(monitor);
|
||||||
|
return string;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Alternatively we can use the `cJSON_Add...ToObject` helper functions to make our lives a little easier:
|
||||||
|
|
||||||
|
```c
|
||||||
|
//NOTE: Returns a heap allocated string, you are required to free it after use.
|
||||||
|
char *create_monitor_with_helpers(void)
|
||||||
|
{
|
||||||
|
const unsigned int resolution_numbers[3][2] = {
|
||||||
|
{1280, 720},
|
||||||
|
{1920, 1080},
|
||||||
|
{3840, 2160}
|
||||||
|
};
|
||||||
|
char *string = NULL;
|
||||||
|
cJSON *resolutions = NULL;
|
||||||
|
size_t index = 0;
|
||||||
|
|
||||||
|
cJSON *monitor = cJSON_CreateObject();
|
||||||
|
|
||||||
|
if (cJSON_AddStringToObject(monitor, "name", "Awesome 4K") == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolutions = cJSON_AddArrayToObject(monitor, "resolutions");
|
||||||
|
if (resolutions == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
|
||||||
|
{
|
||||||
|
cJSON *resolution = cJSON_CreateObject();
|
||||||
|
|
||||||
|
if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL)
|
||||||
|
{
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON_AddItemToArray(resolutions, resolution);
|
||||||
|
}
|
||||||
|
|
||||||
|
string = cJSON_Print(monitor);
|
||||||
|
if (string == NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Failed to print monitor.\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
end:
|
||||||
|
cJSON_Delete(monitor);
|
||||||
|
return string;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Parsing
|
||||||
|
|
||||||
|
In this example we will parse a JSON in the above format and check if the monitor supports a Full HD resolution while printing some diagnostic output:
|
||||||
|
|
||||||
|
```c
|
||||||
|
/* return 1 if the monitor supports full hd, 0 otherwise */
|
||||||
|
int supports_full_hd(const char * const monitor)
|
||||||
|
{
|
||||||
|
const cJSON *resolution = NULL;
|
||||||
|
const cJSON *resolutions = NULL;
|
||||||
|
const cJSON *name = NULL;
|
||||||
|
int status = 0;
|
||||||
|
cJSON *monitor_json = cJSON_Parse(monitor);
|
||||||
|
if (monitor_json == NULL)
|
||||||
|
{
|
||||||
|
const char *error_ptr = cJSON_GetErrorPtr();
|
||||||
|
if (error_ptr != NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "Error before: %s\n", error_ptr);
|
||||||
|
}
|
||||||
|
status = 0;
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
name = cJSON_GetObjectItemCaseSensitive(monitor_json, "name");
|
||||||
|
if (cJSON_IsString(name) && (name->valuestring != NULL))
|
||||||
|
{
|
||||||
|
printf("Checking monitor \"%s\"\n", name->valuestring);
|
||||||
|
}
|
||||||
|
|
||||||
|
resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions");
|
||||||
|
cJSON_ArrayForEach(resolution, resolutions)
|
||||||
|
{
|
||||||
|
cJSON *width = cJSON_GetObjectItemCaseSensitive(resolution, "width");
|
||||||
|
cJSON *height = cJSON_GetObjectItemCaseSensitive(resolution, "height");
|
||||||
|
|
||||||
|
if (!cJSON_IsNumber(width) || !cJSON_IsNumber(height))
|
||||||
|
{
|
||||||
|
status = 0;
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((width->valuedouble == 1920) && (height->valuedouble == 1080))
|
||||||
|
{
|
||||||
|
status = 1;
|
||||||
|
goto end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
end:
|
||||||
|
cJSON_Delete(monitor_json);
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that there are no NULL checks except for the result of `cJSON_Parse` because `cJSON_GetObjectItemCaseSensitive` checks for `NULL` inputs already, so a `NULL` value is just propagated and `cJSON_IsNumber` and `cJSON_IsString` return `0` if the input is `NULL`.
|
||||||
|
|
||||||
|
### Caveats
|
||||||
|
|
||||||
|
#### Zero Character
|
||||||
|
|
||||||
|
cJSON doesn't support strings that contain the zero character `'\0'` or `\u0000`. This is impossible with the current API because strings are zero terminated.
|
||||||
|
|
||||||
|
#### Character Encoding
|
||||||
|
|
||||||
|
cJSON only supports UTF-8 encoded input. In most cases it doesn't reject invalid UTF-8 as input though, it just propagates it through as is. As long as the input doesn't contain invalid UTF-8, the output will always be valid UTF-8.
|
||||||
|
|
||||||
|
#### C Standard
|
||||||
|
|
||||||
|
cJSON is written in ANSI C (or C89, C90). If your compiler or C library doesn't follow this standard, correct behavior is not guaranteed.
|
||||||
|
|
||||||
|
NOTE: ANSI C is not C++ therefore it shouldn't be compiled with a C++ compiler. You can compile it with a C compiler and link it with your C++ code however. Although compiling with a C++ compiler might work, correct behavior is not guaranteed.
|
||||||
|
|
||||||
|
#### Floating Point Numbers
|
||||||
|
|
||||||
|
cJSON does not officially support any `double` implementations other than IEEE754 double precision floating point numbers. It might still work with other implementations but bugs with these will be considered invalid.
|
||||||
|
|
||||||
|
The maximum length of a floating point literal that cJSON supports is currently 63 characters.
|
||||||
|
|
||||||
|
#### Deep Nesting Of Arrays And Objects
|
||||||
|
|
||||||
|
cJSON doesn't support arrays and objects that are nested too deeply because this would result in a stack overflow. To prevent this cJSON limits the depth to `CJSON_NESTING_LIMIT` which is 1000 by default but can be changed at compile time.
|
||||||
|
|
||||||
|
#### Thread Safety
|
||||||
|
|
||||||
|
In general cJSON is **not thread safe**.
|
||||||
|
|
||||||
|
However it is thread safe under the following conditions:
|
||||||
|
|
||||||
|
* `cJSON_GetErrorPtr` is never used (the `return_parse_end` parameter of `cJSON_ParseWithOpts` can be used instead)
|
||||||
|
* `cJSON_InitHooks` is only ever called before using cJSON in any threads.
|
||||||
|
* `setlocale` is never called before all calls to cJSON functions have returned.
|
||||||
|
|
||||||
|
#### Case Sensitivity
|
||||||
|
|
||||||
|
When cJSON was originally created, it didn't follow the JSON standard and didn't make a distinction between uppercase and lowercase letters. If you want the correct, standard compliant, behavior, you need to use the `CaseSensitive` functions where available.
|
||||||
|
|
||||||
|
#### Duplicate Object Members
|
||||||
|
|
||||||
|
cJSON supports parsing and printing JSON that contains objects that have multiple members with the same name. `cJSON_GetObjectItemCaseSensitive` however will always only return the first one.
|
||||||
|
|
||||||
|
# Enjoy cJSON!
|
||||||
|
|
||||||
|
- Dave Gamble (original author)
|
||||||
|
- Max Bruckner and Alan Wang (current maintainer)
|
||||||
|
- and the other [cJSON contributors](CONTRIBUTORS.md)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Security Policy
|
||||||
|
|
||||||
|
## Supported Versions
|
||||||
|
|
||||||
|
Security is of the highest importance and all security vulnerabilities or suspected security vulnerabilities should be reported to cjson team privately, to minimize attacks against current users of cjson before they are fixed. Vulnerabilities will be investigated and patched on the next patch (or minor) release as soon as possible. This information could be kept entirely internal to the project.
|
||||||
|
|
||||||
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
If you know of a publicly disclosed security vulnerability for cjson, please IMMEDIATELY contact wp_scut@163.com and peterlee@apache.org to inform the cjson Team.
|
||||||
|
|
||||||
|
IMPORTANT: Do not file public issues on GitHub for security vulnerabilities.
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
os: Visual Studio 2015
|
||||||
|
|
||||||
|
# ENABLE_CUSTOM_COMPILER_FLAGS - on by default
|
||||||
|
# ENABLE_SANITIZERS - off by default
|
||||||
|
# ENABLE_PUBLIC_SYMBOLS - on by default
|
||||||
|
# BUILD_SHARED_LIBS - on by default
|
||||||
|
# ENABLE_TARGET_EXPORT - on by default
|
||||||
|
# ENABLE_CJSON_UTILS - off by default
|
||||||
|
# ENABLE_CJSON_TEST -on by default
|
||||||
|
# ENABLE_VALGRIND - off by default
|
||||||
|
# ENABLE_FUZZING - off by default
|
||||||
|
|
||||||
|
environment:
|
||||||
|
matrix:
|
||||||
|
- GENERATOR: "Visual Studio 14 2015"
|
||||||
|
BUILD_SHARED_LIBS: ON
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 14 2015"
|
||||||
|
BUILD_SHARED_LIBS: OFF
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 12 2013"
|
||||||
|
BUILD_SHARED_LIBS: ON
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 12 2013"
|
||||||
|
BUILD_SHARED_LIBS: OFF
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 11 2012"
|
||||||
|
BUILD_SHARED_LIBS: ON
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 11 2012"
|
||||||
|
BUILD_SHARED_LIBS: OFF
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 10 2010"
|
||||||
|
BUILD_SHARED_LIBS: ON
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 10 2010"
|
||||||
|
BUILD_SHARED_LIBS: OFF
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 9 2008"
|
||||||
|
BUILD_SHARED_LIBS: ON
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
- GENERATOR: "Visual Studio 9 2008"
|
||||||
|
BUILD_SHARED_LIBS: OFF
|
||||||
|
ENABLE_CJSON_TEST: OFF
|
||||||
|
ENABLE_CJSON_UTILS: ON
|
||||||
|
|
||||||
|
|
||||||
|
platform:
|
||||||
|
- x86
|
||||||
|
- x64
|
||||||
|
matrix:
|
||||||
|
exclude:
|
||||||
|
- platform: x64
|
||||||
|
GENERATOR: "Visual Studio 9 2008"
|
||||||
|
|
||||||
|
configuration:
|
||||||
|
- Release
|
||||||
|
|
||||||
|
|
||||||
|
build_script:
|
||||||
|
- ps: if($env:PLATFORM -eq "x64") { $env:CMAKE_GEN_SUFFIX=" Win64" }
|
||||||
|
- cmake "-G%GENERATOR%%CMAKE_GEN_SUFFIX%" -DBUILD_SHARED_LIBS=%BUILD_SHARED_LIBS% -DENABLE_CJSON_TEST=%ENABLE_CJSON_TEST% -H. -Bbuild
|
||||||
|
- cmake --build build --config "%CONFIGURATION%"
|
||||||
|
|
||||||
|
|
||||||
|
on_failure:
|
||||||
|
- ps: if(Test-Path builds/CMakeFiles/CMakeOutput.log) { cat builds/CMakeFiles/CMakeOutput.log }
|
||||||
|
- ps: if(Test-Path builds/CMakeFiles/CMakeError.log) { cat builds/CMakeFiles/CMakeError.log }
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,306 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||||
|
|
||||||
|
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 cJSON__h
|
||||||
|
#define cJSON__h
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C"
|
||||||
|
{
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
|
||||||
|
#define __WINDOWS__
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __WINDOWS__
|
||||||
|
|
||||||
|
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
|
||||||
|
|
||||||
|
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
|
||||||
|
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
|
||||||
|
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
|
||||||
|
|
||||||
|
For *nix builds that support visibility attribute, you can define similar behavior by
|
||||||
|
|
||||||
|
setting default visibility to hidden by adding
|
||||||
|
-fvisibility=hidden (for gcc)
|
||||||
|
or
|
||||||
|
-xldscope=hidden (for sun cc)
|
||||||
|
to CFLAGS
|
||||||
|
|
||||||
|
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define CJSON_CDECL __cdecl
|
||||||
|
#define CJSON_STDCALL __stdcall
|
||||||
|
|
||||||
|
/* export symbols by default, this is necessary for copy pasting the C and header file */
|
||||||
|
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
|
||||||
|
#define CJSON_EXPORT_SYMBOLS
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(CJSON_HIDE_SYMBOLS)
|
||||||
|
#define CJSON_PUBLIC(type) type CJSON_STDCALL
|
||||||
|
#elif defined(CJSON_EXPORT_SYMBOLS)
|
||||||
|
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
|
||||||
|
#elif defined(CJSON_IMPORT_SYMBOLS)
|
||||||
|
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
|
||||||
|
#endif
|
||||||
|
#else /* !__WINDOWS__ */
|
||||||
|
#define CJSON_CDECL
|
||||||
|
#define CJSON_STDCALL
|
||||||
|
|
||||||
|
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
|
||||||
|
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
|
||||||
|
#else
|
||||||
|
#define CJSON_PUBLIC(type) type
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* project version */
|
||||||
|
#define CJSON_VERSION_MAJOR 1
|
||||||
|
#define CJSON_VERSION_MINOR 7
|
||||||
|
#define CJSON_VERSION_PATCH 19
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
/* cJSON Types: */
|
||||||
|
#define cJSON_Invalid (0)
|
||||||
|
#define cJSON_False (1 << 0)
|
||||||
|
#define cJSON_True (1 << 1)
|
||||||
|
#define cJSON_NULL (1 << 2)
|
||||||
|
#define cJSON_Number (1 << 3)
|
||||||
|
#define cJSON_String (1 << 4)
|
||||||
|
#define cJSON_Array (1 << 5)
|
||||||
|
#define cJSON_Object (1 << 6)
|
||||||
|
#define cJSON_Raw (1 << 7) /* raw json */
|
||||||
|
|
||||||
|
#define cJSON_IsReference 256
|
||||||
|
#define cJSON_StringIsConst 512
|
||||||
|
|
||||||
|
/* The cJSON structure: */
|
||||||
|
typedef struct cJSON
|
||||||
|
{
|
||||||
|
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
|
||||||
|
struct cJSON *next;
|
||||||
|
struct cJSON *prev;
|
||||||
|
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
|
||||||
|
struct cJSON *child;
|
||||||
|
|
||||||
|
/* The type of the item, as above. */
|
||||||
|
int type;
|
||||||
|
|
||||||
|
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
|
||||||
|
char *valuestring;
|
||||||
|
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
|
||||||
|
int valueint;
|
||||||
|
/* The item's number, if type==cJSON_Number */
|
||||||
|
double valuedouble;
|
||||||
|
|
||||||
|
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
|
||||||
|
char *string;
|
||||||
|
} cJSON;
|
||||||
|
|
||||||
|
typedef struct cJSON_Hooks
|
||||||
|
{
|
||||||
|
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
|
||||||
|
void *(CJSON_CDECL *malloc_fn)(size_t sz);
|
||||||
|
void (CJSON_CDECL *free_fn)(void *ptr);
|
||||||
|
} cJSON_Hooks;
|
||||||
|
|
||||||
|
typedef int cJSON_bool;
|
||||||
|
|
||||||
|
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
|
||||||
|
* This is to prevent stack overflows. */
|
||||||
|
#ifndef CJSON_NESTING_LIMIT
|
||||||
|
#define CJSON_NESTING_LIMIT 1000
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Limits the length of circular references can be before cJSON rejects to parse them.
|
||||||
|
* This is to prevent stack overflows. */
|
||||||
|
#ifndef CJSON_CIRCULAR_LIMIT
|
||||||
|
#define CJSON_CIRCULAR_LIMIT 10000
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* returns the version of cJSON as a string */
|
||||||
|
CJSON_PUBLIC(const char*) cJSON_Version(void);
|
||||||
|
|
||||||
|
/* Supply malloc, realloc and free functions to cJSON */
|
||||||
|
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
|
||||||
|
|
||||||
|
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
|
||||||
|
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
|
||||||
|
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
|
||||||
|
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
|
||||||
|
|
||||||
|
/* Render a cJSON entity to text for transfer/storage. */
|
||||||
|
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
|
||||||
|
/* Render a cJSON entity to text for transfer/storage without any formatting. */
|
||||||
|
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
|
||||||
|
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
|
||||||
|
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
|
||||||
|
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
|
||||||
|
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
|
||||||
|
/* Delete a cJSON entity and all subentities. */
|
||||||
|
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
|
||||||
|
|
||||||
|
/* Returns the number of items in an array (or object). */
|
||||||
|
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
|
||||||
|
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
|
||||||
|
/* Get item "string" from object. Case insensitive. */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
|
||||||
|
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
|
||||||
|
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
|
||||||
|
|
||||||
|
/* Check item type and return its value */
|
||||||
|
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item);
|
||||||
|
|
||||||
|
/* These functions check the type of an item */
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
|
||||||
|
|
||||||
|
/* These calls create a cJSON item of the appropriate type. */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
|
||||||
|
/* raw json */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
|
||||||
|
|
||||||
|
/* Create a string where valuestring references a string so
|
||||||
|
* it will not be freed by cJSON_Delete */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
|
||||||
|
/* Create an object/array that only references it's elements so
|
||||||
|
* they will not be freed by cJSON_Delete */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
|
||||||
|
|
||||||
|
/* These utilities create an Array of count items.
|
||||||
|
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
|
||||||
|
|
||||||
|
/* Append item to the specified array/object. */
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
|
||||||
|
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
|
||||||
|
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
|
||||||
|
* writing to `item->string` */
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
|
||||||
|
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
|
||||||
|
|
||||||
|
/* Remove/Detach items from Arrays/Objects. */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
|
||||||
|
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
|
||||||
|
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
|
||||||
|
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
|
||||||
|
|
||||||
|
/* Update array items. */
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
|
||||||
|
|
||||||
|
/* Duplicate a cJSON item */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
|
||||||
|
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
|
||||||
|
* need to be released. With recurse!=0, it will duplicate any children connected to the item.
|
||||||
|
* The item->next and ->prev pointers are always zero on return from Duplicate. */
|
||||||
|
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
|
||||||
|
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
|
||||||
|
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
|
||||||
|
|
||||||
|
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
|
||||||
|
* The input pointer json cannot point to a read-only address area, such as a string constant,
|
||||||
|
* but should point to a readable and writable address area. */
|
||||||
|
CJSON_PUBLIC(void) cJSON_Minify(char *json);
|
||||||
|
|
||||||
|
/* Helper functions for creating and adding items to an object at the same time.
|
||||||
|
* They return the added item or NULL on failure. */
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
|
||||||
|
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
|
||||||
|
|
||||||
|
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
|
||||||
|
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
|
||||||
|
/* helper for the cJSON_SetNumberValue macro */
|
||||||
|
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
|
||||||
|
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
|
||||||
|
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
|
||||||
|
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
|
||||||
|
|
||||||
|
/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/
|
||||||
|
#define cJSON_SetBoolValue(object, boolValue) ( \
|
||||||
|
(object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \
|
||||||
|
(object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \
|
||||||
|
cJSON_Invalid\
|
||||||
|
)
|
||||||
|
|
||||||
|
/* Macro for iterating over an array or object */
|
||||||
|
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
|
||||||
|
|
||||||
|
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
|
||||||
|
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
|
||||||
|
CJSON_PUBLIC(void) cJSON_free(void *object);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,88 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||||
|
|
||||||
|
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 cJSON_Utils__h
|
||||||
|
#define cJSON_Utils__h
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C"
|
||||||
|
{
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
|
||||||
|
/* Implement RFC6901 (https://tools.ietf.org/html/rfc6901) JSON Pointer spec. */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON * const object, const char *pointer);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointerCaseSensitive(cJSON * const object, const char *pointer);
|
||||||
|
|
||||||
|
/* Implement RFC6902 (https://tools.ietf.org/html/rfc6902) JSON Patch spec. */
|
||||||
|
/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON * const from, cJSON * const to);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatchesCaseSensitive(cJSON * const from, cJSON * const to);
|
||||||
|
/* Utility for generating patch array entries. */
|
||||||
|
CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON * const array, const char * const operation, const char * const path, const cJSON * const value);
|
||||||
|
/* Returns 0 for success. */
|
||||||
|
CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON * const object, const cJSON * const patches);
|
||||||
|
CJSON_PUBLIC(int) cJSONUtils_ApplyPatchesCaseSensitive(cJSON * const object, const cJSON * const patches);
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Note that ApplyPatches is NOT atomic on failure. To implement an atomic ApplyPatches, use:
|
||||||
|
//int cJSONUtils_AtomicApplyPatches(cJSON **object, cJSON *patches)
|
||||||
|
//{
|
||||||
|
// cJSON *modme = cJSON_Duplicate(*object, 1);
|
||||||
|
// int error = cJSONUtils_ApplyPatches(modme, patches);
|
||||||
|
// if (!error)
|
||||||
|
// {
|
||||||
|
// cJSON_Delete(*object);
|
||||||
|
// *object = modme;
|
||||||
|
// }
|
||||||
|
// else
|
||||||
|
// {
|
||||||
|
// cJSON_Delete(modme);
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return error;
|
||||||
|
//}
|
||||||
|
// Code not added to library since this strategy is a LOT slower.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Implement RFC7386 (https://tools.ietf.org/html/rfc7396) JSON Merge Patch spec. */
|
||||||
|
/* target will be modified by patch. return value is new ptr for target. */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, const cJSON * const patch);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatchCaseSensitive(cJSON *target, const cJSON * const patch);
|
||||||
|
/* generates a patch to move from -> to */
|
||||||
|
/* NOTE: This modifies objects in 'from' and 'to' by sorting the elements by their key */
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON * const from, cJSON * const to);
|
||||||
|
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatchCaseSensitive(cJSON * const from, cJSON * const to);
|
||||||
|
|
||||||
|
/* Given a root object and a target object, construct a pointer from one to the other. */
|
||||||
|
CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(const cJSON * const object, const cJSON * const target);
|
||||||
|
|
||||||
|
/* Sorts the members of the object into alphabetical order. */
|
||||||
|
CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON * const object);
|
||||||
|
CJSON_PUBLIC(void) cJSONUtils_SortObjectCaseSensitive(cJSON * const object);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
afl-build
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
option(ENABLE_FUZZING "Create executables and targets for fuzzing cJSON with afl." Off)
|
||||||
|
if (ENABLE_FUZZING)
|
||||||
|
find_program(AFL_FUZZ afl-fuzz)
|
||||||
|
if ("${AFL_FUZZ}" MATCHES "AFL_FUZZ-NOTFOUND")
|
||||||
|
message(FATAL_ERROR "Couldn't find afl-fuzz.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
add_executable(afl-main afl.c)
|
||||||
|
target_link_libraries(afl-main "${CJSON_LIB}")
|
||||||
|
|
||||||
|
if (NOT ENABLE_SANITIZERS)
|
||||||
|
message(FATAL_ERROR "Enable sanitizers with -DENABLE_SANITIZERS=On to do fuzzing.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
option(ENABLE_FUZZING_PRINT "Fuzz printing functions together with parser." On)
|
||||||
|
set(fuzz_print_parameter "no")
|
||||||
|
if (ENABLE_FUZZING_PRINT)
|
||||||
|
set(fuzz_print_parameter "yes")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error")
|
||||||
|
|
||||||
|
add_custom_target(afl
|
||||||
|
COMMAND "${AFL_FUZZ}" -i "${CMAKE_CURRENT_SOURCE_DIR}/inputs" -o "${CMAKE_CURRENT_BINARY_DIR}/findings" -x "${CMAKE_CURRENT_SOURCE_DIR}/json.dict" -- "${CMAKE_CURRENT_BINARY_DIR}/afl-main" "@@" "${fuzz_print_parameter}"
|
||||||
|
DEPENDS afl-main)
|
||||||
|
|
||||||
|
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(ENABLE_CJSON_TEST)
|
||||||
|
ADD_EXECUTABLE(fuzz_main fuzz_main.c cjson_read_fuzzer.c)
|
||||||
|
TARGET_LINK_LIBRARIES(fuzz_main cjson)
|
||||||
|
endif()
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -x
|
||||||
|
echo core | sudo tee /proc/sys/kernel/core_pattern
|
||||||
|
echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
/*
|
||||||
|
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||||
|
|
||||||
|
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 <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "../cJSON.h"
|
||||||
|
|
||||||
|
static char *read_file(const char *filename)
|
||||||
|
{
|
||||||
|
FILE *file = NULL;
|
||||||
|
long length = 0;
|
||||||
|
char *content = NULL;
|
||||||
|
size_t read_chars = 0;
|
||||||
|
|
||||||
|
/* open in read binary mode */
|
||||||
|
file = fopen(filename, "rb");
|
||||||
|
if (file == NULL)
|
||||||
|
{
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* get the length */
|
||||||
|
if (fseek(file, 0, SEEK_END) != 0)
|
||||||
|
{
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
length = ftell(file);
|
||||||
|
if (length < 0)
|
||||||
|
{
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
if (fseek(file, 0, SEEK_SET) != 0)
|
||||||
|
{
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* allocate content buffer */
|
||||||
|
content = (char*)malloc((size_t)length + sizeof(""));
|
||||||
|
if (content == NULL)
|
||||||
|
{
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* read the file into memory */
|
||||||
|
read_chars = fread(content, sizeof(char), (size_t)length, file);
|
||||||
|
if ((long)read_chars != length)
|
||||||
|
{
|
||||||
|
free(content);
|
||||||
|
content = NULL;
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
content[read_chars] = '\0';
|
||||||
|
|
||||||
|
|
||||||
|
cleanup:
|
||||||
|
if (file != NULL)
|
||||||
|
{
|
||||||
|
fclose(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char** argv)
|
||||||
|
{
|
||||||
|
const char *filename = NULL;
|
||||||
|
cJSON *item = NULL;
|
||||||
|
char *json = NULL;
|
||||||
|
int status = EXIT_FAILURE;
|
||||||
|
char *printed_json = NULL;
|
||||||
|
|
||||||
|
if ((argc < 2) || (argc > 3))
|
||||||
|
{
|
||||||
|
printf("Usage:\n");
|
||||||
|
printf("%s input_file [enable_printing]\n", argv[0]);
|
||||||
|
printf("\t input_file: file containing the test data\n");
|
||||||
|
printf("\t enable_printing: print after parsing, 'yes' or 'no', defaults to 'no'\n");
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
|
||||||
|
filename = argv[1];
|
||||||
|
|
||||||
|
#if __AFL_HAVE_MANUAL_CONTROL
|
||||||
|
while (__AFL_LOOP(1000))
|
||||||
|
{
|
||||||
|
#endif
|
||||||
|
status = EXIT_SUCCESS;
|
||||||
|
|
||||||
|
json = read_file(filename);
|
||||||
|
if ((json == NULL) || (json[0] == '\0') || (json[1] == '\0'))
|
||||||
|
{
|
||||||
|
status = EXIT_FAILURE;
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
item = cJSON_Parse(json + 2);
|
||||||
|
if (item == NULL)
|
||||||
|
{
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((argc == 3) && (strncmp(argv[2], "yes", 3) == 0))
|
||||||
|
{
|
||||||
|
int do_format = 0;
|
||||||
|
if (json[1] == 'f')
|
||||||
|
{
|
||||||
|
do_format = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (json[0] == 'b')
|
||||||
|
{
|
||||||
|
/* buffered printing */
|
||||||
|
printed_json = cJSON_PrintBuffered(item, 1, do_format);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* unbuffered printing */
|
||||||
|
if (do_format)
|
||||||
|
{
|
||||||
|
printed_json = cJSON_Print(item);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printed_json = cJSON_PrintUnformatted(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (printed_json == NULL)
|
||||||
|
{
|
||||||
|
status = EXIT_FAILURE;
|
||||||
|
goto cleanup;
|
||||||
|
}
|
||||||
|
printf("%s\n", printed_json);
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup:
|
||||||
|
if (item != NULL)
|
||||||
|
{
|
||||||
|
cJSON_Delete(item);
|
||||||
|
item = NULL;
|
||||||
|
}
|
||||||
|
if (json != NULL)
|
||||||
|
{
|
||||||
|
free(json);
|
||||||
|
json = NULL;
|
||||||
|
}
|
||||||
|
if (printed_json != NULL)
|
||||||
|
{
|
||||||
|
free(printed_json);
|
||||||
|
printed_json = NULL;
|
||||||
|
}
|
||||||
|
#if __AFL_HAVE_MANUAL_CONTROL
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
return status;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
mkdir -p afl-build || exit 1
|
||||||
|
cd afl-build || exit 1
|
||||||
|
#cleanup
|
||||||
|
rm -r -- *
|
||||||
|
|
||||||
|
CC=afl-clang-fast cmake ../.. -DENABLE_FUZZING=On -DENABLE_SANITIZERS=On -DBUILD_SHARED_LIBS=Off
|
||||||
|
make afl
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "../cJSON.h"
|
||||||
|
|
||||||
|
int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); /* required by C89 */
|
||||||
|
|
||||||
|
int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
|
||||||
|
{
|
||||||
|
cJSON *json;
|
||||||
|
size_t offset = 4;
|
||||||
|
unsigned char *copied;
|
||||||
|
char *printed_json = NULL;
|
||||||
|
int minify, require_termination, formatted, buffered;
|
||||||
|
|
||||||
|
|
||||||
|
if(size <= offset) return 0;
|
||||||
|
if(data[size-1] != '\0') return 0;
|
||||||
|
if(data[0] != '1' && data[0] != '0') return 0;
|
||||||
|
if(data[1] != '1' && data[1] != '0') return 0;
|
||||||
|
if(data[2] != '1' && data[2] != '0') return 0;
|
||||||
|
if(data[3] != '1' && data[3] != '0') return 0;
|
||||||
|
|
||||||
|
minify = data[0] == '1' ? 1 : 0;
|
||||||
|
require_termination = data[1] == '1' ? 1 : 0;
|
||||||
|
formatted = data[2] == '1' ? 1 : 0;
|
||||||
|
buffered = data[3] == '1' ? 1 : 0;
|
||||||
|
|
||||||
|
json = cJSON_ParseWithOpts((const char*)data + offset, NULL, require_termination);
|
||||||
|
|
||||||
|
if(json == NULL) return 0;
|
||||||
|
|
||||||
|
if(buffered)
|
||||||
|
{
|
||||||
|
printed_json = cJSON_PrintBuffered(json, 1, formatted);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* unbuffered printing */
|
||||||
|
if(formatted)
|
||||||
|
{
|
||||||
|
printed_json = cJSON_Print(json);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
printed_json = cJSON_PrintUnformatted(json);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if(printed_json != NULL) free(printed_json);
|
||||||
|
|
||||||
|
if(minify)
|
||||||
|
{
|
||||||
|
copied = (unsigned char*)malloc(size);
|
||||||
|
if(copied == NULL) return 0;
|
||||||
|
|
||||||
|
memcpy(copied, data, size);
|
||||||
|
|
||||||
|
cJSON_Minify((char*)copied + offset);
|
||||||
|
|
||||||
|
free(copied);
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON_Delete(json);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); /* required by C89 */
|
||||||
|
|
||||||
|
/* fuzz target entry point, works without libFuzzer */
|
||||||
|
|
||||||
|
int main(int argc, char **argv)
|
||||||
|
{
|
||||||
|
FILE *f;
|
||||||
|
char *buf = NULL;
|
||||||
|
long siz_buf;
|
||||||
|
|
||||||
|
if(argc < 2)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "no input file\n");
|
||||||
|
goto err;
|
||||||
|
}
|
||||||
|
|
||||||
|
f = fopen(argv[1], "rb");
|
||||||
|
if(f == NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "error opening input file %s\n", argv[1]);
|
||||||
|
goto err;
|
||||||
|
}
|
||||||
|
|
||||||
|
fseek(f, 0, SEEK_END);
|
||||||
|
|
||||||
|
siz_buf = ftell(f);
|
||||||
|
rewind(f);
|
||||||
|
|
||||||
|
if(siz_buf < 1) goto err;
|
||||||
|
|
||||||
|
buf = (char*)malloc((size_t)siz_buf);
|
||||||
|
if(buf == NULL)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "malloc() failed\n");
|
||||||
|
goto err;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(fread(buf, (size_t)siz_buf, 1, f) != 1)
|
||||||
|
{
|
||||||
|
fprintf(stderr, "fread() failed\n");
|
||||||
|
goto err;
|
||||||
|
}
|
||||||
|
|
||||||
|
(void)LLVMFuzzerTestOneInput((uint8_t*)buf, (size_t)siz_buf);
|
||||||
|
|
||||||
|
err:
|
||||||
|
free(buf);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
bf{
|
||||||
|
"glossary": {
|
||||||
|
"title": "example glossary",
|
||||||
|
"GlossDiv": {
|
||||||
|
"title": "S",
|
||||||
|
"GlossList": {
|
||||||
|
"GlossEntry": {
|
||||||
|
"ID": "SGML",
|
||||||
|
"SortAs": "SGML",
|
||||||
|
"GlossTerm": "Standard Generalized Markup Language",
|
||||||
|
"Acronym": "SGML",
|
||||||
|
"Abbrev": "ISO 8879:1986",
|
||||||
|
"GlossDef": {
|
||||||
|
"para": "A meta-markup language, used to create markup languages such as DocBook.",
|
||||||
|
"GlossSeeAlso": ["GML", "XML"]
|
||||||
|
},
|
||||||
|
"GlossSee": "markup"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
bf["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
bf{
|
||||||
|
"name": "Jack (\"Bee\") Nimble",
|
||||||
|
"format": {"type": "rect",
|
||||||
|
"width": 1920,
|
||||||
|
"height": 1080,
|
||||||
|
"interlace": false,"frame rate": 24
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
bf{"menu": {
|
||||||
|
"id": "file",
|
||||||
|
"value": "File",
|
||||||
|
"popup": {
|
||||||
|
"menuitem": [
|
||||||
|
{"value": "New", "onclick": "CreateNewDoc()"},
|
||||||
|
{"value": "Open", "onclick": "OpenDoc()"},
|
||||||
|
{"value": "Close", "onclick": "CloseDoc()"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
bf{"widget": {
|
||||||
|
"debug": "on",
|
||||||
|
"window": {
|
||||||
|
"title": "Sample Konfabulator Widget",
|
||||||
|
"name": "main_window",
|
||||||
|
"width": 500,
|
||||||
|
"height": 500
|
||||||
|
},
|
||||||
|
"image": {
|
||||||
|
"src": "Images/Sun.png",
|
||||||
|
"name": "sun1",
|
||||||
|
"hOffset": 250,
|
||||||
|
"vOffset": 250,
|
||||||
|
"alignment": "center"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"data": "Click Here",
|
||||||
|
"size": 36,
|
||||||
|
"style": "bold",
|
||||||
|
"name": "text1",
|
||||||
|
"hOffset": 250,
|
||||||
|
"vOffset": 100,
|
||||||
|
"alignment": "center",
|
||||||
|
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
|
||||||
|
}
|
||||||
|
}}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
bu{"widget": {
|
||||||
|
"debug": "on",
|
||||||
|
"window": {
|
||||||
|
"title": "Sample Konfabulator Widget",
|
||||||
|
"name": "main_window",
|
||||||
|
"width": 500,
|
||||||
|
"height": 500
|
||||||
|
},
|
||||||
|
"image": {
|
||||||
|
"src": "Images/Sun.png",
|
||||||
|
"name": "sun1",
|
||||||
|
"hOffset": 250,
|
||||||
|
"vOffset": 250,
|
||||||
|
"alignment": "center"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"data": "Click Here",
|
||||||
|
"size": 36,
|
||||||
|
"style": "bold",
|
||||||
|
"name": "text1",
|
||||||
|
"hOffset": 250,
|
||||||
|
"vOffset": 100,
|
||||||
|
"alignment": "center",
|
||||||
|
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
|
||||||
|
}
|
||||||
|
}}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
uf{"widget": {
|
||||||
|
"debug": "on",
|
||||||
|
"window": {
|
||||||
|
"title": "Sample Konfabulator Widget",
|
||||||
|
"name": "main_window",
|
||||||
|
"width": 500,
|
||||||
|
"height": 500
|
||||||
|
},
|
||||||
|
"image": {
|
||||||
|
"src": "Images/Sun.png",
|
||||||
|
"name": "sun1",
|
||||||
|
"hOffset": 250,
|
||||||
|
"vOffset": 250,
|
||||||
|
"alignment": "center"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"data": "Click Here",
|
||||||
|
"size": 36,
|
||||||
|
"style": "bold",
|
||||||
|
"name": "text1",
|
||||||
|
"hOffset": 250,
|
||||||
|
"vOffset": 100,
|
||||||
|
"alignment": "center",
|
||||||
|
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
|
||||||
|
}
|
||||||
|
}}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
uu{"widget": {
|
||||||
|
"debug": "on",
|
||||||
|
"window": {
|
||||||
|
"title": "Sample Konfabulator Widget",
|
||||||
|
"name": "main_window",
|
||||||
|
"width": 500,
|
||||||
|
"height": 500
|
||||||
|
},
|
||||||
|
"image": {
|
||||||
|
"src": "Images/Sun.png",
|
||||||
|
"name": "sun1",
|
||||||
|
"hOffset": 250,
|
||||||
|
"vOffset": 250,
|
||||||
|
"alignment": "center"
|
||||||
|
},
|
||||||
|
"text": {
|
||||||
|
"data": "Click Here",
|
||||||
|
"size": 36,
|
||||||
|
"style": "bold",
|
||||||
|
"name": "text1",
|
||||||
|
"hOffset": 250,
|
||||||
|
"vOffset": 100,
|
||||||
|
"alignment": "center",
|
||||||
|
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
|
||||||
|
}
|
||||||
|
}}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
bf{"web-app": {
|
||||||
|
"servlet": [
|
||||||
|
{
|
||||||
|
"servlet-name": "cofaxCDS",
|
||||||
|
"servlet-class": "org.cofax.cds.CDSServlet",
|
||||||
|
"init-param": {
|
||||||
|
"configGlossary:installationAt": "Philadelphia, PA",
|
||||||
|
"configGlossary:adminEmail": "ksm@pobox.com",
|
||||||
|
"configGlossary:poweredBy": "Cofax",
|
||||||
|
"configGlossary:poweredByIcon": "/images/cofax.gif",
|
||||||
|
"configGlossary:staticPath": "/content/static",
|
||||||
|
"templateProcessorClass": "org.cofax.WysiwygTemplate",
|
||||||
|
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
|
||||||
|
"templatePath": "templates",
|
||||||
|
"templateOverridePath": "",
|
||||||
|
"defaultListTemplate": "listTemplate.htm",
|
||||||
|
"defaultFileTemplate": "articleTemplate.htm",
|
||||||
|
"useJSP": false,
|
||||||
|
"jspListTemplate": "listTemplate.jsp",
|
||||||
|
"jspFileTemplate": "articleTemplate.jsp",
|
||||||
|
"cachePackageTagsTrack": 200,
|
||||||
|
"cachePackageTagsStore": 200,
|
||||||
|
"cachePackageTagsRefresh": 60,
|
||||||
|
"cacheTemplatesTrack": 100,
|
||||||
|
"cacheTemplatesStore": 50,
|
||||||
|
"cacheTemplatesRefresh": 15,
|
||||||
|
"cachePagesTrack": 200,
|
||||||
|
"cachePagesStore": 100,
|
||||||
|
"cachePagesRefresh": 10,
|
||||||
|
"cachePagesDirtyRead": 10,
|
||||||
|
"searchEngineListTemplate": "forSearchEnginesList.htm",
|
||||||
|
"searchEngineFileTemplate": "forSearchEngines.htm",
|
||||||
|
"searchEngineRobotsDb": "WEB-INF/robots.db",
|
||||||
|
"useDataStore": true,
|
||||||
|
"dataStoreClass": "org.cofax.SqlDataStore",
|
||||||
|
"redirectionClass": "org.cofax.SqlRedirection",
|
||||||
|
"dataStoreName": "cofax",
|
||||||
|
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
|
||||||
|
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
|
||||||
|
"dataStoreUser": "sa",
|
||||||
|
"dataStorePassword": "dataStoreTestQuery",
|
||||||
|
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
|
||||||
|
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
|
||||||
|
"dataStoreInitConns": 10,
|
||||||
|
"dataStoreMaxConns": 100,
|
||||||
|
"dataStoreConnUsageLimit": 100,
|
||||||
|
"dataStoreLogLevel": "debug",
|
||||||
|
"maxUrlLength": 500}},
|
||||||
|
{
|
||||||
|
"servlet-name": "cofaxEmail",
|
||||||
|
"servlet-class": "org.cofax.cds.EmailServlet",
|
||||||
|
"init-param": {
|
||||||
|
"mailHost": "mail1",
|
||||||
|
"mailHostOverride": "mail2"}},
|
||||||
|
{
|
||||||
|
"servlet-name": "cofaxAdmin",
|
||||||
|
"servlet-class": "org.cofax.cds.AdminServlet"},
|
||||||
|
|
||||||
|
{
|
||||||
|
"servlet-name": "fileServlet",
|
||||||
|
"servlet-class": "org.cofax.cds.FileServlet"},
|
||||||
|
{
|
||||||
|
"servlet-name": "cofaxTools",
|
||||||
|
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
|
||||||
|
"init-param": {
|
||||||
|
"templatePath": "toolstemplates/",
|
||||||
|
"log": 1,
|
||||||
|
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
|
||||||
|
"logMaxSize": "",
|
||||||
|
"dataLog": 1,
|
||||||
|
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
|
||||||
|
"dataLogMaxSize": "",
|
||||||
|
"removePageCache": "/content/admin/remove?cache=pages&id=",
|
||||||
|
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
|
||||||
|
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
|
||||||
|
"lookInContext": 1,
|
||||||
|
"adminGroupID": 4,
|
||||||
|
"betaServer": true}}],
|
||||||
|
"servlet-mapping": {
|
||||||
|
"cofaxCDS": "/",
|
||||||
|
"cofaxEmail": "/cofaxutil/aemail/*",
|
||||||
|
"cofaxAdmin": "/admin/*",
|
||||||
|
"fileServlet": "/static/*",
|
||||||
|
"cofaxTools": "/tools/*"},
|
||||||
|
|
||||||
|
"taglib": {
|
||||||
|
"taglib-uri": "cofax.tld",
|
||||||
|
"taglib-location": "/WEB-INF/tlds/cofax.tld"}}}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
bf{"menu": {
|
||||||
|
"header": "SVG Viewer",
|
||||||
|
"items": [
|
||||||
|
{"id": "Open"},
|
||||||
|
{"id": "OpenNew", "label": "Open New"},
|
||||||
|
null,
|
||||||
|
{"id": "ZoomIn", "label": "Zoom In"},
|
||||||
|
{"id": "ZoomOut", "label": "Zoom Out"},
|
||||||
|
{"id": "OriginalView", "label": "Original View"},
|
||||||
|
null,
|
||||||
|
{"id": "Quality"},
|
||||||
|
{"id": "Pause"},
|
||||||
|
{"id": "Mute"},
|
||||||
|
null,
|
||||||
|
{"id": "Find", "label": "Find..."},
|
||||||
|
{"id": "FindAgain", "label": "Find Again"},
|
||||||
|
{"id": "Copy"},
|
||||||
|
{"id": "CopyAgain", "label": "Copy Again"},
|
||||||
|
{"id": "CopySVG", "label": "Copy SVG"},
|
||||||
|
{"id": "ViewSVG", "label": "View SVG"},
|
||||||
|
{"id": "ViewSource", "label": "View Source"},
|
||||||
|
{"id": "SaveAs", "label": "Save As"},
|
||||||
|
null,
|
||||||
|
{"id": "Help"},
|
||||||
|
{"id": "About", "label": "About Adobe CVG Viewer..."}
|
||||||
|
]
|
||||||
|
}}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
bf<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<style type="text/css">
|
||||||
|
html, body, iframe { margin: 0; padding: 0; height: 100%; }
|
||||||
|
iframe { display: block; width: 100%; border: none; }
|
||||||
|
</style>
|
||||||
|
<title>Application Error</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<iframe src="//s3.amazonaws.com/heroku_pages/error.html">
|
||||||
|
<p>Application Error</p>
|
||||||
|
</iframe>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
bf[
|
||||||
|
{
|
||||||
|
"precision": "zip",
|
||||||
|
"Latitude": 37.7668,
|
||||||
|
"Longitude": -122.3959,
|
||||||
|
"Address": "",
|
||||||
|
"City": "SAN FRANCISCO",
|
||||||
|
"State": "CA",
|
||||||
|
"Zip": "94107",
|
||||||
|
"Country": "US"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"precision": "zip",
|
||||||
|
"Latitude": 37.371991,
|
||||||
|
"Longitude": -122.026020,
|
||||||
|
"Address": "",
|
||||||
|
"City": "SUNNYVALE",
|
||||||
|
"State": "CA",
|
||||||
|
"Zip": "94085",
|
||||||
|
"Country": "US"
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
bf{
|
||||||
|
"Image": {
|
||||||
|
"Width": 800,
|
||||||
|
"Height": 600,
|
||||||
|
"Title": "View from 15th Floor",
|
||||||
|
"Thumbnail": {
|
||||||
|
"Url": "http:/*www.example.com/image/481989943",
|
||||||
|
"Height": 125,
|
||||||
|
"Width": "100"
|
||||||
|
},
|
||||||
|
"IDs": [116, 943, 234, 38793]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
bf[
|
||||||
|
[0, -1, 0],
|
||||||
|
[1, 0, 0],
|
||||||
|
[0, 0, 1]
|
||||||
|
]
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
#
|
||||||
|
# AFL dictionary for JSON
|
||||||
|
# -----------------------------
|
||||||
|
#
|
||||||
|
|
||||||
|
object_start="{"
|
||||||
|
object_end="}"
|
||||||
|
object_empty="{}"
|
||||||
|
object_one_element="{\"one\":1}"
|
||||||
|
object_two_elements="{\"1\":1,\"2\":2}"
|
||||||
|
object_separator=":"
|
||||||
|
|
||||||
|
array_start="["
|
||||||
|
array_end="]"
|
||||||
|
array_empty="[]"
|
||||||
|
array_one_element="[1]"
|
||||||
|
array_two_elements="[1,2]"
|
||||||
|
|
||||||
|
separator=","
|
||||||
|
|
||||||
|
escape_sequence_b="\\b"
|
||||||
|
escape_sequence_f="\\f"
|
||||||
|
escape_sequence_n="\\n"
|
||||||
|
escape_sequence_r="\\r"
|
||||||
|
escape_sequence_t="\\t"
|
||||||
|
escape_sequence_quote="\\\""
|
||||||
|
escape_sequence_backslash="\\\\"
|
||||||
|
escape_sequence_slash="\\/"
|
||||||
|
escape_sequence_utf16_base="\\u"
|
||||||
|
escape_sequence_utf16="\\u12ab"
|
||||||
|
|
||||||
|
number_integer="1"
|
||||||
|
number_double="1.0"
|
||||||
|
number_negative_integer="-1"
|
||||||
|
number_negative_double="-1.0"
|
||||||
|
number_engineering1="1e1"
|
||||||
|
number_engineering2="1e-1"
|
||||||
|
number_positive_integer="+1"
|
||||||
|
number_positive_double="+1.0"
|
||||||
|
number_e="e"
|
||||||
|
number_plus="+"
|
||||||
|
number_minus="-"
|
||||||
|
number_separator="."
|
||||||
|
|
||||||
|
null="null"
|
||||||
|
true="true"
|
||||||
|
false="false"
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#!/bin/bash -eu
|
||||||
|
|
||||||
|
# This script is meant to be run by
|
||||||
|
# https://github.com/google/oss-fuzz/blob/master/projects/cjson/Dockerfile
|
||||||
|
|
||||||
|
mkdir build
|
||||||
|
cd build
|
||||||
|
cmake -DBUILD_SHARED_LIBS=OFF -DENABLE_CJSON_TEST=OFF ..
|
||||||
|
make -j$(nproc)
|
||||||
|
|
||||||
|
$CXX $CXXFLAGS $SRC/cjson/fuzzing/cjson_read_fuzzer.c -I. \
|
||||||
|
-o $OUT/cjson_read_fuzzer \
|
||||||
|
$LIB_FUZZING_ENGINE $SRC/cjson/build/libcjson.a
|
||||||
|
|
||||||
|
find $SRC/cjson/fuzzing/inputs -name "*" | \
|
||||||
|
xargs zip $OUT/cjson_read_fuzzer_seed_corpus.zip
|
||||||
|
|
||||||
|
cp $SRC/cjson/fuzzing/json.dict $OUT/cjson_read_fuzzer.dict
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Whether the utils lib was build.
|
||||||
|
set(CJSON_UTILS_FOUND @ENABLE_CJSON_UTILS@)
|
||||||
|
|
||||||
|
# The include directories used by cJSON
|
||||||
|
set(CJSON_INCLUDE_DIRS "@CMAKE_INSTALL_FULL_INCLUDEDIR@")
|
||||||
|
set(CJSON_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@")
|
||||||
|
|
||||||
|
get_filename_component(_dir "${CMAKE_CURRENT_LIST_FILE}" PATH)
|
||||||
|
|
||||||
|
# The cJSON library
|
||||||
|
set(CJSON_LIBRARY "@CJSON_LIB@")
|
||||||
|
if(@ENABLE_TARGET_EXPORT@)
|
||||||
|
# Include the target
|
||||||
|
include("${_dir}/cjson.cmake")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(CJSON_UTILS_FOUND)
|
||||||
|
# The cJSON utils library
|
||||||
|
set(CJSON_UTILS_LIBRARY @CJSON_UTILS_LIB@)
|
||||||
|
# All cJSON libraries
|
||||||
|
set(CJSON_LIBRARIES "@CJSON_UTILS_LIB@" "@CJSON_LIB@")
|
||||||
|
if(@ENABLE_TARGET_EXPORT@)
|
||||||
|
# Include the target
|
||||||
|
include("${_dir}/cjson_utils.cmake")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
# All cJSON libraries
|
||||||
|
set(CJSON_LIBRARIES "@CJSON_LIB@")
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
set(PACKAGE_VERSION "@PROJECT_VERSION@")
|
||||||
|
|
||||||
|
# Check whether the requested PACKAGE_FIND_VERSION is compatible
|
||||||
|
if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}")
|
||||||
|
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
||||||
|
else()
|
||||||
|
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
||||||
|
if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}")
|
||||||
|
set(PACKAGE_VERSION_EXACT TRUE)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||||
|
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||||
|
|
||||||
|
Name: libcjson
|
||||||
|
Version: @PROJECT_VERSION@
|
||||||
|
Description: Ultralightweight JSON parser in ANSI C
|
||||||
|
URL: https://github.com/DaveGamble/cJSON
|
||||||
|
Libs: -L${libdir} -lcjson
|
||||||
|
Libs.private: -lm
|
||||||
|
Cflags: -I${includedir} -I${includedir}/cjson
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||||
|
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||||
|
|
||||||
|
Name: libcjson_utils
|
||||||
|
Version: @PROJECT_VERSION@
|
||||||
|
Description: An implementation of JSON Pointer, Patch and Merge Patch based on cJSON.
|
||||||
|
URL: https://github.com/DaveGamble/cJSON
|
||||||
|
Libs: -L${libdir} -lcjson_utils
|
||||||
|
Cflags: -I${includedir} -I${includedir}/cjson
|
||||||
|
Requires: libcjson
|
||||||
Loaded 100 of 419 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user