7 Commits
Author SHA1 Message Date
jimmyandClaude Haiku 5.5 4cd3bc7973 feat: DDP frame sync over UDP broadcast, DDP acks, DDP enable setting
- Driver acks each completed DDP frame; the test waits for the acks before broadcasting the sync.
- Sync listener on UDP 4049: a frame is held until the next sync, then shown.
- DDP pixels are shown at full brightness, ignoring the device brightness settings.
- "DDP and sync receive on" setting (NVS, network API, web UI); off ignores DDP and sync packets.
- ddp_test.py: finds devices on the subnet, drives them in lockstep at a fixed rate, runs animations.
- /api/ddp reports sync counters for diagnosis.
- Includes in-progress WebSocket, multi-driver web UI and Wi-Fi work from the same tree.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 14:10:55 +13:00
jimmyandClaude Haiku 5.5 47f4eba0d6 test: DDP test finds every device on the subnet and runs animations
- With no arguments, probe the local /24 for devices answering /api/ddp and test each one
  (--subnet picks another subnet; named hosts still override discovery).
- Test all devices at the same time, one thread each.
- Add chase, rainbow and breathe animations; check the last frame of each is shown.
- Compare readback against the output scale (global x master x max brightness) the
  firmware applies, read from /api/status and /api/hardware.
- Check the out-of-range packet and the timeout fallback against the last frame shown.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 12:57:14 +13:00
jimmyandClaude Haiku 5.5 d32f3d69cf feat: control several drivers from one web UI
- Device dropdown: All devices, this device by name, then drivers found by
  mDNS (tagged app=led-strip) and any added by hand.
- POST /api/relay: a driver calls another driver's API for the page, so the
  browser only talks to its own board. Limited to /api/*, /ota and /reboot.
- All devices sends brightness and preset plays to every device.
- Settings: sync this device's presets, order and startup to the others.
- CORS for LAN and localhost origins, and an OPTIONS handler for /ota.
- Header labels are removed; the controls keep aria-labels.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 02:48:48 +13:00
jimmyandClaude Haiku 5.5 4b623bb156 chore: remove MicroPython driver code (src, lib, tests, dev.py)
The cpp branch is the ESP-IDF firmware; the MicroPython drivers are removed.
Uncommitted MicroPython work was saved outside the repo before removal.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 02:07:44 +13:00
jimmyandClaude Haiku 5.5 9a04d28ecf feat: web UI with AP, Wi-Fi client, mDNS, presets, OTA and DDP
- Wi-Fi access point led-XXXXXX plus a client network, configurable
  mDNS name and static client address
- Preset tiles with an editor, drag to reorder, default presets,
  global brightness, Run and Edit modes, collapsible menu on phones
- 35 patterns ported from led-driver, up to 512 LEDs, colour order,
  max brightness and data pin settings
- Over-the-air updates (POST /ota) with rollback, and a CLI in tools/ota.py
- DDP receiver on UDP 4048 with tools/ddp_test.py
- LED refresh every 10 ms; lwIP sockets raised to 16 so mDNS, HTTP
  and DDP can run together

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 01:54:32 +13:00
jimmyandClaude Haiku 5.5 89f996096c Add LED web UI with AP, Wi-Fi client, mDNS and patterns
Brings the led_strip example into the cpp app, targeting the ESP32-C3:
- Access point led-XXXXXX (open) plus a Wi-Fi client configured from the
  web Settings tab, with credentials stored in NVS and reconnect backoff
- mDNS as led.local with an HTTP service on port 80
- HTTP server with an embedded web UI and a JSON API for patterns and Wi-Fi
- Pattern runner for solid, rainbow, chase, breathe, blink, pulse,
  transition and circle on a 119-LED WS2812 strip (GPIO 10)

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 00:02:49 +13:00
jimmyandClaude Haiku 5.5 df43820acd Add basic ESP-IDF app skeleton
Adds a minimal ESP-IDF project for ESP32-S3 at the repo root: top-level
CMakeLists, a main component with a C++ app_main that logs a heartbeat,
sdkconfig.defaults selecting esp32s3, and build notes in the README.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 23:23:08 +13:00
420 changed files with 56656 additions and 11577 deletions

No files matched your search

+8
View File
@@ -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)
+80
View File
@@ -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)
+32
View File
@@ -50,3 +50,35 @@ led-driver/
## 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.
## 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 |
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
```
+31
View File
@@ -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
-75
View File
@@ -1,75 +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:
# Single self-contained suite (tests/all.py); requires ``src`` on device first.
subprocess.call(
[*mpremote_base(), "connect", port, "run", "tests/all.py"]
)
else:
print("Error: Port required for 'test' command")
+7
View File
@@ -97,6 +97,13 @@ Presets define LED patterns with their configuration. Each preset has a name and
- **`n3`**: Tail movement rate (LEDs per second)
- **`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 control which preset is active on which device. The format uses a list to support step synchronization.
-2
View File
@@ -1,2 +0,0 @@
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
send_file # noqa: F401
-8
View File
@@ -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
-225
View File
@@ -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
-70
View File
@@ -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
-231
View File
@@ -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)
-14
View File
@@ -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
-21
View File
@@ -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)
-188
View File
@@ -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)
+6
View File
@@ -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"
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
INCLUDE_DIRS "."
EMBED_TXTFILES "../web/index.html" "../web/app.js" "../web/style.css")
+144
View File
@@ -0,0 +1,144 @@
/*
* 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];
if (dtype != 0x00 && dtype != 0x01) {
continue; // only 8-bit RGB
}
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
View File
@@ -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);
+149
View File
@@ -0,0 +1,149 @@
/*
* 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, negated when reversed
int led_at(const fx_t &f, int i); // logical index -> physical (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_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_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);
+899
View File
@@ -0,0 +1,899 @@
/*
* 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 = abs(sgn(f, nz(f.pr->n[3], 1)));
if (step < 1) step = 1;
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 + sgn(f, 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);
// Always move forward: a negative n3/n4 would otherwise make the dot bounce back.
// sgn() still applies the preset's reverse flag.
int n3 = sgn(f, abs(f.pr->n[3]));
int n4 = sgn(f, abs(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;
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;
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;
}
// ---- 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 --------------------------------------------------------------------------------
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;
return false;
}
rgb c1 = c[s.ci % nc];
rgb c2 = c[(s.ci + 1) % nc];
float factor = (float)elapsed / duration;
rgb m = { (int)(c1.r + (c2.r - c1.r) * factor), (int)(c1.g + (c2.g - c1.g) * factor),
(int)(c1.b + (c2.b - c1.b) * factor) };
fill(f, ab(m, 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;
}
+894
View File
@@ -0,0 +1,894 @@
/*
* 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);
int spacing = nz(f.pr->n[1], 1);
int outward = nz(f.pr->n[2], 1);
int ret = nz(f.pr->n[3], 1);
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;
}
+295
View File
@@ -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;
}
+185
View File
@@ -0,0 +1,185 @@
/*
* 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 "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 &f, int v)
{
return f.pr->reverse ? -v : v;
}
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;
}
// The beat is 500 ms here (there is no beat source on this board)
uint32_t dur(const fx_t &f, int v)
{
if (v < 0) {
v = 0;
}
return f.pr->beat_time ? (uint32_t)(v * 500 / 4) : (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;
}
+5
View File
@@ -0,0 +1,5 @@
dependencies:
espressif/mdns:
version: "^1.4.0"
espressif/cjson:
version: "^1.7.19"
+39
View File
@@ -0,0 +1,39 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include "esp_log.h"
#include "nvs_flash.h"
#include "ddp.h"
#include "net.h"
#include "ota.h"
#include "patterns.h"
#include "presets.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());
ESP_ERROR_CHECK(web_start());
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);
}
+324
View File
@@ -0,0 +1,324 @@
/*
* 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_timer.h"
#include "esp_wifi.h"
#include "mdns.h"
#include "net.h"
static const char *TAG = "net";
#define AP_CHANNEL 1
#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 (with its led-XXXXXX name, open) or off. The client keeps running either way.
static void apply_ap(bool on)
{
if (on) {
char ssid[16];
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 = AP_CHANNEL;
ap.ap.max_connection = AP_MAX_CLIENTS;
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", ssid);
} 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)
static void ap_timer_cb(void *arg)
{
(void)arg;
if (s_ap_want != s_ap_on) {
apply_ap(s_ap_want);
}
}
static esp_err_t apply_client_ip(const net_cfg_t *c);
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");
}
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;
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);
}
esp_wifi_connect();
}
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)
{
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());
// 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_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;
}
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;
}
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;
}
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);
}
// 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;
}
+32
View File
@@ -0,0 +1,32 @@
/*
* 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 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
View File
@@ -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
View File
@@ -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
+537
View File
@@ -0,0 +1,537 @@
/*
* 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 },
{ "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 },
};
#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. While they keep arriving they replace the pattern.
#define DDP_TIMEOUT_MS 2000
static uint8_t s_ddp[FX_LEDS_MAX * 3];
static uint32_t s_ddp_last_ms; // 0: never
static bool s_ddp_was;
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;
for (int i = 1; i <= 6; i++) {
if (p->n[i] < 0) p->n[i] = 0;
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);
}
// Show the shadow frame, crossfading from the previous frame while a fade runs
static void output(uint32_t now, bool full_brightness)
{
// device brightness x master scale, under the max brightness ceiling. DDP frames are shown at
// full brightness: the sender sets the colours.
int s_scale = full_brightness ? 255 : 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);
}
// The whole frame (pattern and output) runs under s_lock, so the buffers can't be replaced mid-frame
static void patterns_task(void *arg)
{
(void)arg;
s_fx.pr = &s_run;
while (true) {
xSemaphoreTake(s_lock, portMAX_DELAY);
bool reset = s_reset_pending;
s_reset_pending = false;
s_run = s_cur;
uint32_t now = now_ms();
bool ddp_on = s_ddp_last_ms != 0 && now - s_ddp_last_ms < DDP_TIMEOUT_MS;
if (!ddp_on && s_ddp_was) {
reset = true; // the pattern starts again when the pixels stop
}
s_ddp_was = ddp_on;
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);
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 = s_sync_last_ms != 0 && 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 = s_ddp_last_ms != 0 && 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);
}
+84
View File
@@ -0,0 +1,84 @@
/*
* 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 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);
+391
View File
@@ -0,0 +1,391 @@
/*
* 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)
{
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" };
for (int i = 0; i < 4; 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;
}
// Write the whole list to NVS as one JSON blob
static esp_err_t save_list(void)
{
cJSON *arr = cJSON_CreateArray();
for (size_t i = 0; i < s_count; i++) {
cJSON_AddItemToArray(arr, preset_to_json(&s_list[i]));
}
char *s = cJSON_PrintUnformatted(arr);
cJSON_Delete(arr);
if (!s) {
return ESP_ERR_NO_MEM;
}
nvs_handle_t h;
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
if (err == ESP_OK) {
err = nvs_set_blob(h, "list", s, strlen(s));
if (err == ESP_OK) err = nvs_set_str(h, "startup", s_startup);
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
}
cJSON_free(s);
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("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;
}
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;
}
size_t len = 0;
bool have_list = nvs_get_blob(h, "list", NULL, &len) == ESP_OK;
if (have_list && len > 0) {
char *buf = (char *)malloc(len + 1);
if (buf && 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);
}
free(buf);
}
len = sizeof(s_startup);
if (nvs_get_str(h, "startup", s_startup, &len) != ESP_OK) {
s_startup[0] = '\0';
}
nvs_close(h);
if (!have_list) {
presets_add_defaults(); // nothing saved yet: start with the defaults
}
ESP_LOGI(TAG, "%u presets loaded", (unsigned)s_count);
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;
}
esp_err_t presets_save(const preset_t *preset)
{
int idx = find(preset->name);
if (idx < 0) {
if (s_count >= PRESETS_MAX) {
return ESP_ERR_NO_MEM;
}
idx = (int)s_count++;
}
s_list[idx] = *preset;
return save_list();
}
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));
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--;
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);
}
}
+57
View File
@@ -0,0 +1,57 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <cstddef>
#include "cJSON.h"
#include "esp_err.h"
#include "patterns.h"
#define PRESETS_MAX 32
/** @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 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);
+162
View File
@@ -0,0 +1,162 @@
/*
* 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;
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;
char ddp[8];
get_str(h, "ddp", ddp, sizeof(ddp), "on");
c->ddp_enabled = strcmp(ddp, "off") != 0;
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, "ddp", c->ddp_enabled ? "on" : "off");
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
return err;
}
+51
View File
@@ -0,0 +1,51 @@
/*
* 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
bool ddp_enabled; // DDP pixels and frame sync are received; default on
};
/** @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);
+1325
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -0,0 +1,24 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "esp_err.h"
#include "esp_http_server.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @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);
#ifdef __cplusplus
}
#endif
+258
View File
@@ -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(&copy_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;
}
}
+82
View File
@@ -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_ = {};
};
+173
View File
@@ -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);
}
}
+22
View File
@@ -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
@@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.5)
set(MANIFEST "${CMAKE_CURRENT_BINARY_DIR}/install_manifest.txt")
if(NOT EXISTS ${MANIFEST})
message(FATAL_ERROR "Cannot find install mainfest: ${MANIFEST}")
endif()
file(STRINGS ${MANIFEST} files)
foreach(file ${files})
if(EXISTS ${file} OR IS_SYMLINK ${file})
message(STATUS "Removing: ${file}")
execute_process(COMMAND rm -f ${file}
RESULT_VARIABLE result
OUTPUT_QUIET
ERROR_VARIABLE stderr
ERROR_STRIP_TRAILING_WHITESPACE
)
if(NOT ${result} EQUAL 0)
message(FATAL_ERROR "${stderr}")
endif()
else()
message(STATUS "Does-not-exist: ${file}")
endif()
endforeach(file)
@@ -0,0 +1,268 @@
/*
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"
/* Used by some code below as an example datatype. */
struct record
{
const char *precision;
double lat;
double lon;
const char *address;
const char *city;
const char *state;
const char *zip;
const char *country;
};
/* Create a bunch of objects as demonstration. */
static int print_preallocated(cJSON *root)
{
/* declarations */
char *out = NULL;
char *buf = NULL;
char *buf_fail = NULL;
size_t len = 0;
size_t len_fail = 0;
/* formatted print */
out = cJSON_Print(root);
/* create buffer to succeed */
/* the extra 5 bytes are because of inaccuracies when reserving memory */
len = strlen(out) + 5;
buf = (char*)malloc(len);
if (buf == NULL)
{
printf("Failed to allocate memory.\n");
exit(1);
}
/* create buffer to fail */
len_fail = strlen(out);
buf_fail = (char*)malloc(len_fail);
if (buf_fail == NULL)
{
printf("Failed to allocate memory.\n");
exit(1);
}
/* Print to buffer */
if (!cJSON_PrintPreallocated(root, buf, (int)len, 1)) {
printf("cJSON_PrintPreallocated failed!\n");
if (strcmp(out, buf) != 0) {
printf("cJSON_PrintPreallocated not the same as cJSON_Print!\n");
printf("cJSON_Print result:\n%s\n", out);
printf("cJSON_PrintPreallocated result:\n%s\n", buf);
}
free(out);
free(buf_fail);
free(buf);
return -1;
}
/* success */
printf("%s\n", buf);
/* force it to fail */
if (cJSON_PrintPreallocated(root, buf_fail, (int)len_fail, 1)) {
printf("cJSON_PrintPreallocated failed to show error with insufficient memory!\n");
printf("cJSON_Print result:\n%s\n", out);
printf("cJSON_PrintPreallocated result:\n%s\n", buf_fail);
free(out);
free(buf_fail);
free(buf);
return -1;
}
free(out);
free(buf_fail);
free(buf);
return 0;
}
/* Create a bunch of objects as demonstration. */
static void create_objects(void)
{
/* declare a few. */
cJSON *root = NULL;
cJSON *fmt = NULL;
cJSON *img = NULL;
cJSON *thm = NULL;
cJSON *fld = NULL;
int i = 0;
/* Our "days of the week" array: */
const char *strings[7] =
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
/* Our matrix: */
int numbers[3][3] =
{
{0, -1, 0},
{1, 0, 0},
{0 ,0, 1}
};
/* Our "gallery" item: */
int ids[4] = { 116, 943, 234, 38793 };
/* Our array of "records": */
struct record fields[2] =
{
{
"zip",
37.7668,
-1.223959e+2,
"",
"SAN FRANCISCO",
"CA",
"94107",
"US"
},
{
"zip",
37.371991,
-1.22026e+2,
"",
"SUNNYVALE",
"CA",
"94085",
"US"
}
};
volatile double zero = 0.0;
/* Here we construct some JSON standards, from the JSON site. */
/* Our "Video" datatype: */
root = cJSON_CreateObject();
cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));
cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject());
cJSON_AddStringToObject(fmt, "type", "rect");
cJSON_AddNumberToObject(fmt, "width", 1920);
cJSON_AddNumberToObject(fmt, "height", 1080);
cJSON_AddFalseToObject (fmt, "interlace");
cJSON_AddNumberToObject(fmt, "frame rate", 24);
/* Print to text */
if (print_preallocated(root) != 0) {
cJSON_Delete(root);
exit(EXIT_FAILURE);
}
cJSON_Delete(root);
/* Our "days of the week" array: */
root = cJSON_CreateStringArray(strings, 7);
if (print_preallocated(root) != 0) {
cJSON_Delete(root);
exit(EXIT_FAILURE);
}
cJSON_Delete(root);
/* Our matrix: */
root = cJSON_CreateArray();
for (i = 0; i < 3; i++)
{
cJSON_AddItemToArray(root, cJSON_CreateIntArray(numbers[i], 3));
}
/* cJSON_ReplaceItemInArray(root, 1, cJSON_CreateString("Replacement")); */
if (print_preallocated(root) != 0) {
cJSON_Delete(root);
exit(EXIT_FAILURE);
}
cJSON_Delete(root);
/* Our "gallery" item: */
root = cJSON_CreateObject();
cJSON_AddItemToObject(root, "Image", img = cJSON_CreateObject());
cJSON_AddNumberToObject(img, "Width", 800);
cJSON_AddNumberToObject(img, "Height", 600);
cJSON_AddStringToObject(img, "Title", "View from 15th Floor");
cJSON_AddItemToObject(img, "Thumbnail", thm = cJSON_CreateObject());
cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
cJSON_AddNumberToObject(thm, "Height", 125);
cJSON_AddStringToObject(thm, "Width", "100");
cJSON_AddItemToObject(img, "IDs", cJSON_CreateIntArray(ids, 4));
if (print_preallocated(root) != 0) {
cJSON_Delete(root);
exit(EXIT_FAILURE);
}
cJSON_Delete(root);
/* Our array of "records": */
root = cJSON_CreateArray();
for (i = 0; i < 2; i++)
{
cJSON_AddItemToArray(root, fld = cJSON_CreateObject());
cJSON_AddStringToObject(fld, "precision", fields[i].precision);
cJSON_AddNumberToObject(fld, "Latitude", fields[i].lat);
cJSON_AddNumberToObject(fld, "Longitude", fields[i].lon);
cJSON_AddStringToObject(fld, "Address", fields[i].address);
cJSON_AddStringToObject(fld, "City", fields[i].city);
cJSON_AddStringToObject(fld, "State", fields[i].state);
cJSON_AddStringToObject(fld, "Zip", fields[i].zip);
cJSON_AddStringToObject(fld, "Country", fields[i].country);
}
/* cJSON_ReplaceItemInObject(cJSON_GetArrayItem(root, 1), "City", cJSON_CreateIntArray(ids, 4)); */
if (print_preallocated(root) != 0) {
cJSON_Delete(root);
exit(EXIT_FAILURE);
}
cJSON_Delete(root);
root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, "number", 1.0 / zero);
if (print_preallocated(root) != 0) {
cJSON_Delete(root);
exit(EXIT_FAILURE);
}
cJSON_Delete(root);
}
int CJSON_CDECL main(void)
{
/* print the version */
printf("Version: %s\n", cJSON_Version());
/* Now some samplecode for building objects concisely: */
create_objects();
return 0;
}
@@ -0,0 +1,119 @@
if(ENABLE_CJSON_TEST)
add_library(unity STATIC unity/src/unity.c)
# Disable -Werror for Unity
if (FLAG_SUPPORTED_Werror)
if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-error")
else()
target_compile_options(unity PRIVATE "-Wno-error")
endif()
endif()
# Disable -fvisibility=hidden for Unity
if (FLAG_SUPPORTED_fvisibilityhidden)
if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fvisibility=default")
else()
target_compile_options(unity PRIVATE "-fvisibility=default")
endif()
endif()
# Disable -fsanitize=float-divide-by-zero for Unity (GCC bug on x86 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80097)
if (FLAG_SUPPORTED_fsanitizefloatdividebyzero AND (CMAKE_C_COMPILER_ID STREQUAL "GNU"))
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(unity PRIVATE "-fno-sanitize=float-divide-by-zero")
endif()
endif()
# Disable -Wswitch-enum for Unity
if (FLAG_SUPPORTED_Wswitchenum)
if ("${CMAKE_VERSION}" VERSION_LESS "2.8.12")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-switch-enum")
else()
target_compile_options(unity PRIVATE "-Wno-switch-enum")
endif()
endif()
#copy test files
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/inputs")
file(GLOB test_files "inputs/*")
file(COPY ${test_files} DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/inputs/")
set(unity_tests
parse_examples
parse_number
parse_hex4
parse_string
parse_array
parse_object
parse_value
print_string
print_number
print_array
print_object
print_value
misc_tests
parse_with_opts
compare_tests
cjson_add
readme_examples
minify_tests
)
option(ENABLE_VALGRIND OFF "Enable the valgrind memory checker for the tests.")
if (ENABLE_VALGRIND)
find_program(MEMORYCHECK_COMMAND valgrind)
if ("${MEMORYCHECK_COMMAND}" MATCHES "MEMORYCHECK_COMMAND-NOTFOUND")
message(WARNING "Valgrind couldn't be found.")
unset(MEMORYCHECK_COMMAND)
else()
set(MEMORYCHECK_COMMAND_OPTIONS --trace-children=yes --leak-check=full --error-exitcode=1 --suppressions=${CMAKE_CURRENT_SOURCE_DIR}/../valgrind.supp)
endif()
endif()
foreach(unity_test ${unity_tests})
add_executable("${unity_test}" "${unity_test}.c")
if("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC")
target_sources(${unity_test} PRIVATE unity_setup.c)
endif()
target_link_libraries("${unity_test}" "${CJSON_LIB}" unity)
if(MEMORYCHECK_COMMAND)
add_test(NAME "${unity_test}"
COMMAND "${MEMORYCHECK_COMMAND}" ${MEMORYCHECK_COMMAND_OPTIONS} "${CMAKE_CURRENT_BINARY_DIR}/${unity_test}")
else()
add_test(NAME "${unity_test}"
COMMAND "./${unity_test}")
endif()
endforeach()
add_dependencies(check ${unity_tests})
if (ENABLE_CJSON_UTILS)
#copy test files
file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/json-patch-tests")
file(GLOB test_files "json-patch-tests/*")
file(COPY ${test_files} DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/json-patch-tests/")
set (cjson_utils_tests
json_patch_tests
old_utils_tests
misc_utils_tests)
foreach (cjson_utils_test ${cjson_utils_tests})
add_executable("${cjson_utils_test}" "${cjson_utils_test}.c")
target_link_libraries("${cjson_utils_test}" "${CJSON_LIB}" "${CJSON_UTILS_LIB}" unity)
if("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC")
target_sources(${cjson_utils_test} PRIVATE unity_setup.c)
endif()
if(MEMORYCHECK_COMMAND)
add_test(NAME "${cjson_utils_test}"
COMMAND "${MEMORYCHECK_COMMAND}" ${MEMORYCHECK_COMMAND_OPTIONS} "${CMAKE_CURRENT_BINARY_DIR}/${cjson_utils_test}")
else()
add_test(NAME "${cjson_utils_test}"
COMMAND "./${cjson_utils_test}")
endif()
endforeach()
add_dependencies(check ${cjson_utils_tests})
endif()
endif()
@@ -0,0 +1,471 @@
/*
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 "unity/examples/unity_config.h"
#include "unity/src/unity.h"
#include "common.h"
static void * CJSON_CDECL failing_malloc(size_t size)
{
(void)size;
return NULL;
}
/* work around MSVC error C2322: '...' address of dllimport '...' is not static */
static void CJSON_CDECL normal_free(void *pointer)
{
free(pointer);
}
static cJSON_Hooks failing_hooks = {
failing_malloc,
normal_free
};
static void cjson_add_null_should_add_null(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *null = NULL;
cJSON_AddNullToObject(root, "null");
TEST_ASSERT_NOT_NULL(null = cJSON_GetObjectItemCaseSensitive(root, "null"));
TEST_ASSERT_EQUAL_INT(null->type, cJSON_NULL);
cJSON_Delete(root);
}
static void cjson_add_null_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddNullToObject(NULL, "null"));
TEST_ASSERT_NULL(cJSON_AddNullToObject(root, NULL));
cJSON_Delete(root);
}
static void cjson_add_null_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddNullToObject(root, "null"));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
static void cjson_add_true_should_add_true(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *true_item = NULL;
cJSON_AddTrueToObject(root, "true");
TEST_ASSERT_NOT_NULL(true_item = cJSON_GetObjectItemCaseSensitive(root, "true"));
TEST_ASSERT_EQUAL_INT(true_item->type, cJSON_True);
cJSON_Delete(root);
}
static void cjson_add_true_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddTrueToObject(NULL, "true"));
TEST_ASSERT_NULL(cJSON_AddTrueToObject(root, NULL));
cJSON_Delete(root);
}
static void cjson_add_true_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddTrueToObject(root, "true"));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
static void cjson_create_int_array_should_fail_on_allocation_failure(void)
{
int numbers[] = {1, 2, 3};
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_CreateIntArray(numbers, 3));
cJSON_InitHooks(NULL);
}
static void cjson_create_float_array_should_fail_on_allocation_failure(void)
{
float numbers[] = {1.0f, 2.0f, 3.0f};
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_CreateFloatArray(numbers, 3));
cJSON_InitHooks(NULL);
}
static void cjson_create_double_array_should_fail_on_allocation_failure(void)
{
double numbers[] = {1.0, 2.0, 3.0};
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_CreateDoubleArray(numbers, 3));
cJSON_InitHooks(NULL);
}
static void cjson_create_string_array_should_fail_on_allocation_failure(void)
{
const char* strings[] = {"1", "2", "3"};
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_CreateStringArray(strings, 3));
cJSON_InitHooks(NULL);
}
static void cjson_add_false_should_add_false(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *false_item = NULL;
cJSON_AddFalseToObject(root, "false");
TEST_ASSERT_NOT_NULL(false_item = cJSON_GetObjectItemCaseSensitive(root, "false"));
TEST_ASSERT_EQUAL_INT(false_item->type, cJSON_False);
cJSON_Delete(root);
}
static void cjson_add_false_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddFalseToObject(NULL, "false"));
TEST_ASSERT_NULL(cJSON_AddFalseToObject(root, NULL));
cJSON_Delete(root);
}
static void cjson_add_false_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddFalseToObject(root, "false"));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
static void cjson_add_bool_should_add_bool(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *true_item = NULL;
cJSON *false_item = NULL;
/* true */
cJSON_AddBoolToObject(root, "true", true);
TEST_ASSERT_NOT_NULL(true_item = cJSON_GetObjectItemCaseSensitive(root, "true"));
TEST_ASSERT_EQUAL_INT(true_item->type, cJSON_True);
/* false */
cJSON_AddBoolToObject(root, "false", false);
TEST_ASSERT_NOT_NULL(false_item = cJSON_GetObjectItemCaseSensitive(root, "false"));
TEST_ASSERT_EQUAL_INT(false_item->type, cJSON_False);
cJSON_Delete(root);
}
static void cjson_add_bool_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddBoolToObject(NULL, "false", false));
TEST_ASSERT_NULL(cJSON_AddBoolToObject(root, NULL, false));
cJSON_Delete(root);
}
static void cjson_add_bool_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddBoolToObject(root, "false", false));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
static void cjson_add_number_should_add_number(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *number = NULL;
cJSON_AddNumberToObject(root, "number", 42);
TEST_ASSERT_NOT_NULL(number = cJSON_GetObjectItemCaseSensitive(root, "number"));
TEST_ASSERT_EQUAL_INT(number->type, cJSON_Number);
TEST_ASSERT_EQUAL_DOUBLE(number->valuedouble, 42);
TEST_ASSERT_EQUAL_INT(number->valueint, 42);
cJSON_Delete(root);
}
static void cjson_add_number_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddNumberToObject(NULL, "number", 42));
TEST_ASSERT_NULL(cJSON_AddNumberToObject(root, NULL, 42));
cJSON_Delete(root);
}
static void cjson_add_number_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddNumberToObject(root, "number", 42));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
static void cjson_add_string_should_add_string(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *string = NULL;
cJSON_AddStringToObject(root, "string", "Hello World!");
TEST_ASSERT_NOT_NULL(string = cJSON_GetObjectItemCaseSensitive(root, "string"));
TEST_ASSERT_EQUAL_INT(string->type, cJSON_String);
TEST_ASSERT_EQUAL_STRING(string->valuestring, "Hello World!");
cJSON_Delete(root);
}
static void cjson_add_string_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddStringToObject(NULL, "string", "string"));
TEST_ASSERT_NULL(cJSON_AddStringToObject(root, NULL, "string"));
cJSON_Delete(root);
}
static void cjson_add_string_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddStringToObject(root, "string", "string"));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
static void cjson_add_raw_should_add_raw(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *raw = NULL;
cJSON_AddRawToObject(root, "raw", "{}");
TEST_ASSERT_NOT_NULL(raw = cJSON_GetObjectItemCaseSensitive(root, "raw"));
TEST_ASSERT_EQUAL_INT(raw->type, cJSON_Raw);
TEST_ASSERT_EQUAL_STRING(raw->valuestring, "{}");
cJSON_Delete(root);
}
static void cjson_add_raw_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddRawToObject(NULL, "raw", "{}"));
TEST_ASSERT_NULL(cJSON_AddRawToObject(root, NULL, "{}"));
cJSON_Delete(root);
}
static void cjson_add_raw_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddRawToObject(root, "raw", "{}"));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
static void cJSON_add_object_should_add_object(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *object = NULL;
cJSON_AddObjectToObject(root, "object");
TEST_ASSERT_NOT_NULL(object = cJSON_GetObjectItemCaseSensitive(root, "object"));
TEST_ASSERT_EQUAL_INT(object->type, cJSON_Object);
cJSON_Delete(root);
}
static void cjson_add_object_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddObjectToObject(NULL, "object"));
TEST_ASSERT_NULL(cJSON_AddObjectToObject(root, NULL));
cJSON_Delete(root);
}
static void cjson_add_object_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddObjectToObject(root, "object"));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
static void cJSON_add_array_should_add_array(void)
{
cJSON *root = cJSON_CreateObject();
cJSON *array = NULL;
cJSON_AddArrayToObject(root, "array");
TEST_ASSERT_NOT_NULL(array = cJSON_GetObjectItemCaseSensitive(root, "array"));
TEST_ASSERT_EQUAL_INT(array->type, cJSON_Array);
cJSON_Delete(root);
}
static void cjson_add_array_should_fail_with_null_pointers(void)
{
cJSON *root = cJSON_CreateObject();
TEST_ASSERT_NULL(cJSON_AddArrayToObject(NULL, "array"));
TEST_ASSERT_NULL(cJSON_AddArrayToObject(root, NULL));
cJSON_Delete(root);
}
static void cjson_add_array_should_fail_on_allocation_failure(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_InitHooks(&failing_hooks);
TEST_ASSERT_NULL(cJSON_AddArrayToObject(root, "array"));
cJSON_InitHooks(NULL);
cJSON_Delete(root);
}
int CJSON_CDECL main(void)
{
UNITY_BEGIN();
RUN_TEST(cjson_add_null_should_add_null);
RUN_TEST(cjson_add_null_should_fail_with_null_pointers);
RUN_TEST(cjson_add_null_should_fail_on_allocation_failure);
RUN_TEST(cjson_add_true_should_add_true);
RUN_TEST(cjson_add_true_should_fail_with_null_pointers);
RUN_TEST(cjson_add_true_should_fail_on_allocation_failure);
RUN_TEST(cjson_create_int_array_should_fail_on_allocation_failure);
RUN_TEST(cjson_create_float_array_should_fail_on_allocation_failure);
RUN_TEST(cjson_create_double_array_should_fail_on_allocation_failure);
RUN_TEST(cjson_create_string_array_should_fail_on_allocation_failure);
RUN_TEST(cjson_add_false_should_add_false);
RUN_TEST(cjson_add_false_should_fail_with_null_pointers);
RUN_TEST(cjson_add_false_should_fail_on_allocation_failure);
RUN_TEST(cjson_add_bool_should_add_bool);
RUN_TEST(cjson_add_bool_should_fail_with_null_pointers);
RUN_TEST(cjson_add_bool_should_fail_on_allocation_failure);
RUN_TEST(cjson_add_number_should_add_number);
RUN_TEST(cjson_add_number_should_fail_with_null_pointers);
RUN_TEST(cjson_add_number_should_fail_on_allocation_failure);
RUN_TEST(cjson_add_string_should_add_string);
RUN_TEST(cjson_add_string_should_fail_with_null_pointers);
RUN_TEST(cjson_add_string_should_fail_on_allocation_failure);
RUN_TEST(cjson_add_raw_should_add_raw);
RUN_TEST(cjson_add_raw_should_fail_with_null_pointers);
RUN_TEST(cjson_add_raw_should_fail_on_allocation_failure);
RUN_TEST(cJSON_add_object_should_add_object);
RUN_TEST(cjson_add_object_should_fail_with_null_pointers);
RUN_TEST(cjson_add_object_should_fail_on_allocation_failure);
RUN_TEST(cJSON_add_array_should_add_array);
RUN_TEST(cjson_add_array_should_fail_with_null_pointers);
RUN_TEST(cjson_add_array_should_fail_on_allocation_failure);
return UNITY_END();
}
@@ -0,0 +1,122 @@
/*
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_TESTS_COMMON_H
#define CJSON_TESTS_COMMON_H
#include "../cJSON.c"
void reset(cJSON *item);
void reset(cJSON *item) {
if ((item != NULL) && (item->child != NULL))
{
cJSON_Delete(item->child);
}
if ((item->valuestring != NULL) && !(item->type & cJSON_IsReference))
{
global_hooks.deallocate(item->valuestring);
}
if ((item->string != NULL) && !(item->type & cJSON_StringIsConst))
{
global_hooks.deallocate(item->string);
}
memset(item, 0, sizeof(cJSON));
}
char* read_file(const char *filename);
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;
}
/* assertion helper macros */
#define assert_has_type(item, item_type) TEST_ASSERT_BITS_MESSAGE(0xFF, item_type, item->type, "Item doesn't have expected type.")
#define assert_has_no_reference(item) TEST_ASSERT_BITS_MESSAGE(cJSON_IsReference, 0, item->type, "Item should not have a string as reference.")
#define assert_has_no_const_string(item) TEST_ASSERT_BITS_MESSAGE(cJSON_StringIsConst, 0, item->type, "Item should not have a const string.")
#define assert_has_valuestring(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->valuestring, "Valuestring is NULL.")
#define assert_has_no_valuestring(item) TEST_ASSERT_NULL_MESSAGE(item->valuestring, "Valuestring is not NULL.")
#define assert_has_string(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->string, "String is NULL")
#define assert_has_no_string(item) TEST_ASSERT_NULL_MESSAGE(item->string, "String is not NULL.")
#define assert_not_in_list(item) \
TEST_ASSERT_NULL_MESSAGE(item->next, "Linked list next pointer is not NULL.");\
TEST_ASSERT_NULL_MESSAGE(item->prev, "Linked list previous pointer is not NULL.")
#define assert_has_child(item) TEST_ASSERT_NOT_NULL_MESSAGE(item->child, "Item doesn't have a child.")
#define assert_has_no_child(item) TEST_ASSERT_NULL_MESSAGE(item->child, "Item has a child.")
#define assert_is_invalid(item) \
assert_has_type(item, cJSON_Invalid);\
assert_not_in_list(item);\
assert_has_no_child(item);\
assert_has_no_string(item);\
assert_has_no_valuestring(item)
#endif
@@ -0,0 +1,208 @@
/*
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 "unity/examples/unity_config.h"
#include "unity/src/unity.h"
#include "common.h"
static cJSON_bool compare_from_string(const char * const a, const char * const b, const cJSON_bool case_sensitive)
{
cJSON *a_json = NULL;
cJSON *b_json = NULL;
cJSON_bool result = false;
a_json = cJSON_Parse(a);
TEST_ASSERT_NOT_NULL_MESSAGE(a_json, "Failed to parse a.");
b_json = cJSON_Parse(b);
TEST_ASSERT_NOT_NULL_MESSAGE(b_json, "Failed to parse b.");
result = cJSON_Compare(a_json, b_json, case_sensitive);
cJSON_Delete(a_json);
cJSON_Delete(b_json);
return result;
}
static void cjson_compare_should_compare_null_pointer_as_not_equal(void)
{
TEST_ASSERT_FALSE(cJSON_Compare(NULL, NULL, true));
TEST_ASSERT_FALSE(cJSON_Compare(NULL, NULL, false));
}
static void cjson_compare_should_compare_invalid_as_not_equal(void)
{
cJSON invalid[1];
memset(invalid, '\0', sizeof(invalid));
TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, false));
TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, true));
}
static void cjson_compare_should_compare_numbers(void)
{
TEST_ASSERT_TRUE(compare_from_string("1", "1", true));
TEST_ASSERT_TRUE(compare_from_string("1", "1", false));
TEST_ASSERT_TRUE(compare_from_string("0.0001", "0.0001", true));
TEST_ASSERT_TRUE(compare_from_string("0.0001", "0.0001", false));
TEST_ASSERT_TRUE(compare_from_string("1E100", "10E99", false));
TEST_ASSERT_FALSE(compare_from_string("0.5E-100", "0.5E-101", false));
TEST_ASSERT_FALSE(compare_from_string("1", "2", true));
TEST_ASSERT_FALSE(compare_from_string("1", "2", false));
}
static void cjson_compare_should_compare_booleans(void)
{
/* true */
TEST_ASSERT_TRUE(compare_from_string("true", "true", true));
TEST_ASSERT_TRUE(compare_from_string("true", "true", false));
/* false */
TEST_ASSERT_TRUE(compare_from_string("false", "false", true));
TEST_ASSERT_TRUE(compare_from_string("false", "false", false));
/* mixed */
TEST_ASSERT_FALSE(compare_from_string("true", "false", true));
TEST_ASSERT_FALSE(compare_from_string("true", "false", false));
TEST_ASSERT_FALSE(compare_from_string("false", "true", true));
TEST_ASSERT_FALSE(compare_from_string("false", "true", false));
}
static void cjson_compare_should_compare_null(void)
{
TEST_ASSERT_TRUE(compare_from_string("null", "null", true));
TEST_ASSERT_TRUE(compare_from_string("null", "null", false));
TEST_ASSERT_FALSE(compare_from_string("null", "true", true));
TEST_ASSERT_FALSE(compare_from_string("null", "true", false));
}
static void cjson_compare_should_not_accept_invalid_types(void)
{
cJSON invalid[1];
memset(invalid, '\0', sizeof(invalid));
invalid->type = cJSON_Number | cJSON_String;
TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, true));
TEST_ASSERT_FALSE(cJSON_Compare(invalid, invalid, false));
}
static void cjson_compare_should_compare_strings(void)
{
TEST_ASSERT_TRUE(compare_from_string("\"abcdefg\"", "\"abcdefg\"", true));
TEST_ASSERT_TRUE(compare_from_string("\"abcdefg\"", "\"abcdefg\"", false));
TEST_ASSERT_FALSE(compare_from_string("\"ABCDEFG\"", "\"abcdefg\"", true));
TEST_ASSERT_FALSE(compare_from_string("\"ABCDEFG\"", "\"abcdefg\"", false));
}
static void cjson_compare_should_compare_raw(void)
{
cJSON *raw1 = NULL;
cJSON *raw2 = NULL;
raw1 = cJSON_Parse("\"[true, false]\"");
TEST_ASSERT_NOT_NULL(raw1);
raw2 = cJSON_Parse("\"[true, false]\"");
TEST_ASSERT_NOT_NULL(raw2);
raw1->type = cJSON_Raw;
raw2->type = cJSON_Raw;
TEST_ASSERT_TRUE(cJSON_Compare(raw1, raw2, true));
TEST_ASSERT_TRUE(cJSON_Compare(raw1, raw2, false));
cJSON_Delete(raw1);
cJSON_Delete(raw2);
}
static void cjson_compare_should_compare_arrays(void)
{
TEST_ASSERT_TRUE(compare_from_string("[]", "[]", true));
TEST_ASSERT_TRUE(compare_from_string("[]", "[]", false));
TEST_ASSERT_TRUE(compare_from_string("[false,true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", true));
TEST_ASSERT_TRUE(compare_from_string("[false,true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", false));
TEST_ASSERT_TRUE(compare_from_string("[[[1], 2]]", "[[[1], 2]]", true));
TEST_ASSERT_TRUE(compare_from_string("[[[1], 2]]", "[[[1], 2]]", false));
TEST_ASSERT_FALSE(compare_from_string("[true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", true));
TEST_ASSERT_FALSE(compare_from_string("[true,null,42,\"string\",[],{}]", "[false, true, null, 42, \"string\", [], {}]", false));
/* Arrays that are a prefix of another array */
TEST_ASSERT_FALSE(compare_from_string("[1,2,3]", "[1,2]", true));
TEST_ASSERT_FALSE(compare_from_string("[1,2,3]", "[1,2]", false));
}
static void cjson_compare_should_compare_objects(void)
{
TEST_ASSERT_TRUE(compare_from_string("{}", "{}", true));
TEST_ASSERT_TRUE(compare_from_string("{}", "{}", false));
TEST_ASSERT_TRUE(compare_from_string(
"{\"false\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
"{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
true));
TEST_ASSERT_FALSE(compare_from_string(
"{\"False\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
"{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
true));
TEST_ASSERT_TRUE(compare_from_string(
"{\"False\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
"{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
false));
TEST_ASSERT_FALSE(compare_from_string(
"{\"Flse\": false, \"true\": true, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
"{\"true\": true, \"false\": false, \"null\": null, \"number\": 42, \"string\": \"string\", \"array\": [], \"object\": {}}",
false));
/* test objects that are a subset of each other */
TEST_ASSERT_FALSE(compare_from_string(
"{\"one\": 1, \"two\": 2}",
"{\"one\": 1, \"two\": 2, \"three\": 3}",
true))
TEST_ASSERT_FALSE(compare_from_string(
"{\"one\": 1, \"two\": 2}",
"{\"one\": 1, \"two\": 2, \"three\": 3}",
false))
}
int CJSON_CDECL main(void)
{
UNITY_BEGIN();
RUN_TEST(cjson_compare_should_compare_null_pointer_as_not_equal);
RUN_TEST(cjson_compare_should_compare_invalid_as_not_equal);
RUN_TEST(cjson_compare_should_compare_numbers);
RUN_TEST(cjson_compare_should_compare_booleans);
RUN_TEST(cjson_compare_should_compare_null);
RUN_TEST(cjson_compare_should_not_accept_invalid_types);
RUN_TEST(cjson_compare_should_compare_strings);
RUN_TEST(cjson_compare_should_compare_raw);
RUN_TEST(cjson_compare_should_compare_arrays);
RUN_TEST(cjson_compare_should_compare_objects);
return UNITY_END();
}
@@ -0,0 +1,22 @@
{
"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,22 @@
{
"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 @@
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
@@ -0,0 +1 @@
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
Loaded 100 of 420 files, more files were not shown because too many files have changed in this diff. Show more