Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1524 lines
45 KiB

6 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
6 years ago
6 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
api: rework plain and JSON implementations (#2405) - match paths through a custom AsyncWebHandler instead of using generic not-found fallback handler - allow MQTT-like patterns when registering paths (`simple/path`, `path/+/something`, `path/#`) Replaces `relay/0`, `relay/1` etc. with `relay/+`. Magnitudes are plain paths, but using `/+` in case there's more than 1 magnitude of the same type. - restore `std::function` as callback container (no more single-byte arg nonsense). Still, limit to 1 type per handler type - adds JSON handlers which will receive JsonObject root as both input and output. Same logic as plain - GET returns resource data, PUT updates it. - breaking change to `apiAuthenticate(request)`, it no longer will do `request->send(403)` and expect this to be handled externally. - allow `Api-Key` header containing the key, works for both GET & PUT plain requests. The only way to set apikey for JSON. - add `ApiRequest::param` to retrieve both GET and PUT params (aka args), remove ApiBuffer - remove `API_BUFFER_SIZE`. Allow custom form-data key=value pairs for requests, allow to send basic `String`. - add `API_JSON_BUFFER_SIZE` for the JSON buffer (both input and output) - `/apis` replaced with `/api/list`, no longer uses custom handler and is an `apiRegister` callback - `/api/rpc` custom handler replaced with an `apiRegister` callback WIP further down: - no more `webLog` for API requests, unless `webAccessLog` / `WEB_ACCESS_LOG` is set to `1`. This also needs to happen to the other handlers. - migrate to ArduinoJson v6, since it become apparent it is actually a good upgrade :) - actually make use of JSON endpoints more, right now it's just existing GET for sensors and relays - fork ESPAsyncWebServer to cleanup path parsing and temporary objects attached to the request (also, fix things a lot of things based on PRs there...)
4 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. LIGHT MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "light.h"
  6. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  7. #include "api.h"
  8. #include "broker.h"
  9. #include "mqtt.h"
  10. #include "rpc.h"
  11. #include "rtcmem.h"
  12. #include "tuya.h"
  13. #include "ws.h"
  14. #include "light_config.h"
  15. #include <Ticker.h>
  16. #include <Schedule.h>
  17. #include <ArduinoJson.h>
  18. #include <vector>
  19. extern "C" {
  20. #include "libs/fs_math.h"
  21. }
  22. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  23. // default is 8, we only need up to 5
  24. #define PWM_CHANNEL_NUM_MAX Light::ChannelsMax
  25. extern "C" {
  26. #include "libs/pwm.h"
  27. }
  28. #endif
  29. // -----------------------------------------------------------------------------
  30. struct channel_t {
  31. channel_t();
  32. channel_t(unsigned char pin, bool inverse);
  33. unsigned char pin; // real GPIO pin
  34. bool inverse; // whether we should invert the value before using it
  35. bool state; // is the channel ON
  36. unsigned char inputValue; // raw value, without the brightness
  37. unsigned char value; // normalized value, including brightness
  38. unsigned char target; // target value
  39. double current; // transition value
  40. };
  41. Ticker _light_comms_ticker;
  42. Ticker _light_save_ticker;
  43. Ticker _light_transition_ticker;
  44. std::vector<channel_t> _light_channels;
  45. bool _light_has_color = false;
  46. bool _light_use_white = false;
  47. bool _light_use_cct = false;
  48. bool _light_use_gamma = false;
  49. bool _light_provider_update = false;
  50. bool _light_use_transitions = false;
  51. unsigned int _light_transition_time = LIGHT_TRANSITION_TIME;
  52. bool _light_dirty = false;
  53. bool _light_state = false;
  54. unsigned char _light_brightness = Light::BRIGHTNESS_MAX;
  55. // Default to the Philips Hue value that HA also use.
  56. // https://developers.meethue.com/documentation/core-concepts
  57. long _light_cold_mireds = LIGHT_COLDWHITE_MIRED;
  58. long _light_warm_mireds = LIGHT_WARMWHITE_MIRED;
  59. long _light_cold_kelvin = (1000000L / _light_cold_mireds);
  60. long _light_warm_kelvin = (1000000L / _light_warm_mireds);
  61. long _light_mireds = lround((_light_cold_mireds + _light_warm_mireds) / 2L);
  62. using light_brightness_func_t = void();
  63. light_brightness_func_t* _light_brightness_func = nullptr;
  64. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  65. #include <my92xx.h>
  66. my92xx * _my92xx;
  67. unsigned char _light_channel_map[] {
  68. MY92XX_MAPPING
  69. };
  70. #endif
  71. // UI hint about channel distribution
  72. const char _light_channel_desc[5][5] PROGMEM = {
  73. {'W', 0, 0, 0, 0},
  74. {'W', 'C', 0, 0, 0},
  75. {'R', 'G', 'B', 0, 0},
  76. {'R', 'G', 'B', 'W', 0},
  77. {'R', 'G', 'B', 'W', 'C'}
  78. };
  79. static_assert((LIGHT_CHANNELS * LIGHT_CHANNELS) <= (sizeof(_light_channel_desc)), "Out-of-bounds array access");
  80. // Gamma Correction lookup table (8 bit)
  81. const unsigned char _light_gamma_table[] PROGMEM = {
  82. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  83. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
  84. 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6,
  85. 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11,
  86. 12, 12, 13, 13, 14, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19,
  87. 19, 20, 20, 21, 22, 22, 23, 23, 24, 25, 25, 26, 26, 27, 28, 28,
  88. 29, 30, 30, 31, 32, 33, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40,
  89. 41, 42, 43, 43, 44, 45, 46, 47, 48, 49, 50, 50, 51, 52, 53, 54,
  90. 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71,
  91. 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89,
  92. 91, 92, 93, 94, 96, 97, 98, 100, 101, 102, 104, 105, 106, 108, 109, 110,
  93. 112, 113, 115, 116, 118, 119, 121, 122, 123, 125, 126, 128, 130, 131, 133, 134,
  94. 136, 137, 139, 140, 142, 144, 145, 147, 149, 150, 152, 154, 155, 157, 159, 160,
  95. 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 187, 189,
  96. 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221,
  97. 223, 225, 227, 229, 231, 233, 235, 238, 240, 242, 244, 246, 248, 251, 253, 255
  98. };
  99. static_assert(Light::VALUE_MAX <= sizeof(_light_gamma_table), "Out-of-bounds array access");
  100. // -----------------------------------------------------------------------------
  101. // UTILS
  102. // -----------------------------------------------------------------------------
  103. channel_t::channel_t() :
  104. pin(GPIO_NONE),
  105. inverse(false),
  106. state(true),
  107. inputValue(0),
  108. value(0),
  109. target(0),
  110. current(0.0)
  111. {}
  112. channel_t::channel_t(unsigned char pin, bool inverse) :
  113. pin(pin),
  114. inverse(inverse),
  115. state(true),
  116. inputValue(0),
  117. value(0),
  118. target(0),
  119. current(0.0)
  120. {
  121. pinMode(pin, OUTPUT);
  122. }
  123. void _setValue(const unsigned char id, const unsigned int value) {
  124. if (_light_channels[id].value != value) {
  125. _light_channels[id].value = value;
  126. _light_dirty = true;
  127. }
  128. }
  129. void _setInputValue(const unsigned char id, const unsigned int value) {
  130. _light_channels[id].inputValue = value;
  131. }
  132. void _setRGBInputValue(unsigned char red, unsigned char green, unsigned char blue) {
  133. _setInputValue(0, constrain(red, Light::VALUE_MIN, Light::VALUE_MAX));
  134. _setInputValue(1, constrain(green, Light::VALUE_MIN, Light::VALUE_MAX));
  135. _setInputValue(2, constrain(blue, Light::VALUE_MIN, Light::VALUE_MAX));
  136. }
  137. void _setCCTInputValue(unsigned char warm, unsigned char cold) {
  138. _setInputValue(0, constrain(warm, Light::VALUE_MIN, Light::VALUE_MAX));
  139. _setInputValue(1, constrain(cold, Light::VALUE_MIN, Light::VALUE_MAX));
  140. }
  141. void _lightApplyBrightness(size_t channels = lightChannels()) {
  142. double brightness = static_cast<double>(_light_brightness) / static_cast<double>(Light::BRIGHTNESS_MAX);
  143. channels = std::min(channels, lightChannels());
  144. for (unsigned char i=0; i < lightChannels(); i++) {
  145. if (i >= channels) brightness = 1;
  146. _setValue(i, _light_channels[i].inputValue * brightness);
  147. }
  148. }
  149. void _lightApplyBrightnessColor() {
  150. double brightness = static_cast<double>(_light_brightness) / static_cast<double>(Light::BRIGHTNESS_MAX);
  151. // Substract the common part from RGB channels and add it to white channel. So [250,150,50] -> [200,100,0,50]
  152. unsigned char white = std::min(_light_channels[0].inputValue, std::min(_light_channels[1].inputValue, _light_channels[2].inputValue));
  153. for (unsigned int i=0; i < 3; i++) {
  154. _setValue(i, _light_channels[i].inputValue - white);
  155. }
  156. // Split the White Value across 2 White LED Strips.
  157. if (_light_use_cct) {
  158. // This change the range from 153-500 to 0-347 so we get a value between 0 and 1 in the end.
  159. double miredFactor = ((double) _light_mireds - (double) _light_cold_mireds)/((double) _light_warm_mireds - (double) _light_cold_mireds);
  160. // set cold white
  161. _light_channels[3].inputValue = 0;
  162. _setValue(3, lround(((double) 1.0 - miredFactor) * white));
  163. // set warm white
  164. _light_channels[4].inputValue = 0;
  165. _setValue(4, lround(miredFactor * white));
  166. } else {
  167. _light_channels[3].inputValue = 0;
  168. _setValue(3, white);
  169. }
  170. // Scale up to equal input values. So [250,150,50] -> [200,100,0,50] -> [250, 125, 0, 63]
  171. unsigned char max_in = std::max(_light_channels[0].inputValue, std::max(_light_channels[1].inputValue, _light_channels[2].inputValue));
  172. unsigned char max_out = std::max(std::max(_light_channels[0].value, _light_channels[1].value), std::max(_light_channels[2].value, _light_channels[3].value));
  173. unsigned char channelSize = _light_use_cct ? 5 : 4;
  174. if (_light_use_cct) {
  175. max_out = std::max(max_out, _light_channels[4].value);
  176. }
  177. double factor = (max_out > 0) ? (double) (max_in / max_out) : 0;
  178. for (unsigned char i=0; i < channelSize; i++) {
  179. _setValue(i, lround((double) _light_channels[i].value * factor * brightness));
  180. }
  181. // Scale white channel to match brightness
  182. for (unsigned char i=3; i < channelSize; i++) {
  183. _setValue(i, constrain(static_cast<unsigned int>(_light_channels[i].value * LIGHT_WHITE_FACTOR), Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX));
  184. }
  185. // For the rest of channels, don't apply brightness, it is already in the inputValue
  186. // i should be 4 when RGBW and 5 when RGBWW
  187. for (unsigned char i=channelSize; i < _light_channels.size(); i++) {
  188. _setValue(i, _light_channels[i].inputValue);
  189. }
  190. }
  191. String lightDesc(unsigned char id) {
  192. if (id >= _light_channels.size()) return FPSTR(pstr_unknown);
  193. const char tag = pgm_read_byte(&_light_channel_desc[_light_channels.size() - 1][id]);
  194. switch (tag) {
  195. case 'W': return F("WARM WHITE");
  196. case 'C': return F("COLD WHITE");
  197. case 'R': return F("RED");
  198. case 'G': return F("GREEN");
  199. case 'B': return F("BLUE");
  200. default: break;
  201. }
  202. return FPSTR(pstr_unknown);
  203. }
  204. // -----------------------------------------------------------------------------
  205. // Input Values
  206. // -----------------------------------------------------------------------------
  207. void _fromLong(unsigned long value, bool brightness) {
  208. if (brightness) {
  209. _setRGBInputValue((value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF);
  210. lightBrightness((value & 0xFF) * Light::BRIGHTNESS_MAX / 255);
  211. } else {
  212. _setRGBInputValue((value >> 16) & 0xFF, (value >> 8) & 0xFF, (value) & 0xFF);
  213. }
  214. }
  215. void _fromRGB(const char * rgb) {
  216. // 9 char #........ , 11 char ...,...,...
  217. if (!_light_has_color) return;
  218. if (!rgb || (strlen(rgb) == 0)) return;
  219. // HEX value is always prefixed, like CSS
  220. // values are interpreted like RGB + optional brightness
  221. if (rgb[0] == '#') {
  222. _fromLong(strtoul(rgb + 1, nullptr, 16), strlen(rgb + 1) > 7);
  223. // With comma separated string, assume decimal values
  224. } else {
  225. const auto channels = _light_channels.size();
  226. unsigned char count = 0;
  227. char buf[16] = {0};
  228. strncpy(buf, rgb, sizeof(buf) - 1);
  229. char *tok = strtok(buf, ",");
  230. while (tok != NULL) {
  231. _setInputValue(count, atoi(tok));
  232. if (++count == channels) break;
  233. tok = strtok(NULL, ",");
  234. }
  235. // If less than 3 values received, set the rest to 0
  236. if (count < 2) _setInputValue(1, 0);
  237. if (count < 3) _setInputValue(2, 0);
  238. return;
  239. }
  240. }
  241. // HSV string is expected to be "H,S,V", where:
  242. // 0 <= H <= 360
  243. // 0 <= S <= 100
  244. // 0 <= V <= 100
  245. void _fromHSV(const char * hsv) {
  246. if (!_light_has_color) return;
  247. if (strlen(hsv) == 0) return;
  248. char buf[16] = {0};
  249. strncpy(buf, hsv, sizeof(buf) - 1);
  250. unsigned char count = 0;
  251. unsigned int value[3] = {0};
  252. char * tok = strtok(buf, ",");
  253. while (tok != NULL) {
  254. value[count] = atoi(tok);
  255. if (++count == 3) break;
  256. tok = strtok(NULL, ",");
  257. }
  258. if (count != 3) return;
  259. // HSV to RGB transformation -----------------------------------------------
  260. //INPUT: [0,100,57]
  261. //IS: [145,0,0]
  262. //SHOULD: [255,0,0]
  263. const double h = (value[0] == 360) ? 0 : (double) value[0] / 60.0;
  264. const double f = (h - floor(h));
  265. const double s = (double) value[1] / 100.0;
  266. _light_brightness = lround((double) value[2] * (static_cast<double>(Light::BRIGHTNESS_MAX) / 100.0)); // (default 255/100)
  267. const unsigned char p = lround(Light::VALUE_MAX * (1.0 - s));
  268. const unsigned char q = lround(Light::VALUE_MAX * (1.0 - s * f));
  269. const unsigned char t = lround(Light::VALUE_MAX * (1.0 - s * (1.0 - f)));
  270. switch (int(h)) {
  271. case 0:
  272. _setRGBInputValue(Light::VALUE_MAX, t, p);
  273. break;
  274. case 1:
  275. _setRGBInputValue(q, Light::VALUE_MAX, p);
  276. break;
  277. case 2:
  278. _setRGBInputValue(p, Light::VALUE_MAX, t);
  279. break;
  280. case 3:
  281. _setRGBInputValue(p, q, Light::VALUE_MAX);
  282. break;
  283. case 4:
  284. _setRGBInputValue(t, p, Light::VALUE_MAX);
  285. break;
  286. case 5:
  287. _setRGBInputValue(Light::VALUE_MAX, p, q);
  288. break;
  289. default:
  290. _setRGBInputValue(Light::VALUE_MIN, Light::VALUE_MIN, Light::VALUE_MIN);
  291. break;
  292. }
  293. }
  294. // Thanks to Sacha Telgenhof for sharing this code in his AiLight library
  295. // https://github.com/stelgenhof/AiLight
  296. // Color temperature is measured in mireds (kelvin = 1e6/mired)
  297. long _toKelvin(const long mireds) {
  298. return constrain(static_cast<long>(1000000L / mireds), _light_warm_kelvin, _light_cold_kelvin);
  299. }
  300. long _toMireds(const long kelvin) {
  301. return constrain(static_cast<long>(lround(1000000L / kelvin)), _light_cold_mireds, _light_warm_mireds);
  302. }
  303. void _lightMireds(const long kelvin) {
  304. _light_mireds = _toMireds(kelvin);
  305. }
  306. void _lightMiredsCCT(const long kelvin) {
  307. _lightMireds(kelvin);
  308. // This change the range from 153-500 to 0-347 so we get a value between 0 and 1 in the end.
  309. const double factor = ((double) _light_mireds - (double) _light_cold_mireds)/((double) _light_warm_mireds - (double) _light_cold_mireds);
  310. _setCCTInputValue(
  311. lround(factor * Light::VALUE_MAX),
  312. lround(((double) 1.0 - factor) * Light::VALUE_MAX)
  313. );
  314. }
  315. void _fromKelvin(long kelvin) {
  316. if (!_light_has_color) {
  317. if (!_light_use_cct) return;
  318. _lightMiredsCCT(kelvin);
  319. return;
  320. }
  321. _lightMireds(kelvin);
  322. if (_light_use_cct) {
  323. _setRGBInputValue(Light::VALUE_MAX, Light::VALUE_MAX, Light::VALUE_MAX);
  324. return;
  325. }
  326. // Calculate colors
  327. kelvin /= 100;
  328. const unsigned int red = (kelvin <= 66)
  329. ? Light::VALUE_MAX
  330. : 329.698727446 * fs_pow((double) (kelvin - 60), -0.1332047592);
  331. const unsigned int green = (kelvin <= 66)
  332. ? 99.4708025861 * fs_log(kelvin) - 161.1195681661
  333. : 288.1221695283 * fs_pow((double) kelvin, -0.0755148492);
  334. const unsigned int blue = (kelvin >= 66)
  335. ? Light::VALUE_MAX
  336. : ((kelvin <= 19)
  337. ? 0
  338. : 138.5177312231 * fs_log(kelvin - 10) - 305.0447927307);
  339. _setRGBInputValue(red, green, blue);
  340. }
  341. void _fromMireds(const long mireds) {
  342. _fromKelvin(_toKelvin(mireds));
  343. }
  344. // -----------------------------------------------------------------------------
  345. // Output Values
  346. // -----------------------------------------------------------------------------
  347. void _toRGB(char * rgb, size_t len, bool target = false) {
  348. unsigned long value = 0;
  349. value += target ? _light_channels[0].target : _light_channels[0].inputValue;
  350. value <<= 8;
  351. value += target ? _light_channels[1].target : _light_channels[1].inputValue;
  352. value <<= 8;
  353. value += target ? _light_channels[2].target : _light_channels[2].inputValue;
  354. snprintf_P(rgb, len, PSTR("#%06X"), value);
  355. }
  356. String _toRGB(bool target) {
  357. char buffer[64] { 0 };
  358. _toRGB(buffer, sizeof(buffer), target);
  359. return buffer;
  360. }
  361. void _toHSV(char * hsv, size_t len) {
  362. double h {0.}, s {0.}, v {0.};
  363. double r {0.}, g {0.}, b {0.};
  364. double min {0.}, max {0.};
  365. r = static_cast<double>(_light_channels[0].target) / Light::VALUE_MAX;
  366. g = static_cast<double>(_light_channels[1].target) / Light::VALUE_MAX;
  367. b = static_cast<double>(_light_channels[2].target) / Light::VALUE_MAX;
  368. min = std::min(r, std::min(g, b));
  369. max = std::max(r, std::max(g, b));
  370. v = 100.0 * max;
  371. if (v == 0) {
  372. h = s = 0;
  373. } else {
  374. s = 100.0 * (max - min) / max;
  375. if (s == 0) {
  376. h = 0;
  377. } else {
  378. if (max == r) {
  379. if (g >= b) {
  380. h = 0.0 + 60.0 * (g - b) / (max - min);
  381. } else {
  382. h = 360.0 + 60.0 * (g - b) / (max - min);
  383. }
  384. } else if (max == g) {
  385. h = 120.0 + 60.0 * (b - r) / (max - min);
  386. } else {
  387. h = 240.0 + 60.0 * (r - g) / (max - min);
  388. }
  389. }
  390. }
  391. // Convert to string. Using lround, since we can't (yet) printf floats
  392. snprintf(hsv, len, "%d,%d,%d",
  393. static_cast<int>(lround(h)),
  394. static_cast<int>(lround(s)),
  395. static_cast<int>(lround(v))
  396. );
  397. }
  398. String _toHSV() {
  399. char buffer[64] { 0 };
  400. _toHSV(buffer, sizeof(buffer));
  401. return buffer;
  402. }
  403. void _toLong(char * color, size_t len, bool target) {
  404. if (!_light_has_color) return;
  405. snprintf_P(color, len, PSTR("%u,%u,%u"),
  406. (target ? _light_channels[0].target : _light_channels[0].inputValue),
  407. (target ? _light_channels[1].target : _light_channels[1].inputValue),
  408. (target ? _light_channels[2].target : _light_channels[2].inputValue)
  409. );
  410. }
  411. void _toLong(char * color, size_t len) {
  412. _toLong(color, len, false);
  413. }
  414. String _toLong(bool target = false) {
  415. char buffer[64] { 0 };
  416. _toLong(buffer, sizeof(buffer), target);
  417. return buffer;
  418. }
  419. String _toCSV(bool target) {
  420. const auto channels = lightChannels();
  421. String result;
  422. result.reserve(4 * channels);
  423. for (auto& channel : _light_channels) {
  424. if (result.length()) result += ',';
  425. result += String(target ? channel.target : channel.inputValue);
  426. }
  427. return result;
  428. }
  429. // See cores/esp8266/WMath.cpp::map
  430. // Redefining as local method here to avoid breaking in unexpected ways in inputs like (0, 0, 0, 0, 1)
  431. template <typename T, typename Tin, typename Tout> T _lightMap(T x, Tin in_min, Tin in_max, Tout out_min, Tout out_max) {
  432. auto divisor = (in_max - in_min);
  433. if (divisor == 0){
  434. return -1; //AVR returns -1, SAM returns 0
  435. }
  436. return (x - in_min) * (out_max - out_min) / divisor + out_min;
  437. }
  438. int _lightAdjustValue(const int& value, const String& operation) {
  439. if (!operation.length()) return value;
  440. // if prefixed with a sign, treat expression as numerical operation
  441. // otherwise, use as the new value
  442. int updated = operation.toInt();
  443. if (operation[0] == '+' || operation[0] == '-') {
  444. updated = value + updated;
  445. }
  446. return updated;
  447. }
  448. void _lightAdjustBrightness(const char* payload) {
  449. lightBrightness(_lightAdjustValue(lightBrightness(), payload));
  450. }
  451. void _lightAdjustBrightness(const String& payload) {
  452. _lightAdjustBrightness(payload.c_str());
  453. }
  454. void _lightAdjustChannel(unsigned char id, const char* payload) {
  455. lightChannel(id, _lightAdjustValue(lightChannel(id), payload));
  456. }
  457. void _lightAdjustChannel(unsigned char id, const String& payload) {
  458. _lightAdjustChannel(id, payload.c_str());
  459. }
  460. void _lightAdjustKelvin(const char* payload) {
  461. _fromKelvin(_lightAdjustValue(_toKelvin(_light_mireds), payload));
  462. }
  463. void _lightAdjustKelvin(const String& payload) {
  464. _lightAdjustKelvin(payload.c_str());
  465. }
  466. void _lightAdjustMireds(const char* payload) {
  467. _fromMireds(_lightAdjustValue(_light_mireds, payload));
  468. }
  469. void _lightAdjustMireds(const String& payload) {
  470. _lightAdjustMireds(payload.c_str());
  471. }
  472. // -----------------------------------------------------------------------------
  473. // PROVIDER
  474. // -----------------------------------------------------------------------------
  475. unsigned int _toPWM(unsigned int value, bool gamma, bool inverse) {
  476. value = constrain(value, Light::VALUE_MIN, Light::VALUE_MAX);
  477. if (gamma) value = pgm_read_byte(_light_gamma_table + value);
  478. if (Light::VALUE_MAX != Light::PWM_LIMIT) value = _lightMap(value, Light::VALUE_MIN, Light::VALUE_MAX, Light::PWM_MIN, Light::PWM_LIMIT);
  479. if (inverse) value = LIGHT_LIMIT_PWM - value;
  480. return value;
  481. }
  482. // Returns a PWM value for the given channel ID
  483. unsigned int _toPWM(unsigned char id) {
  484. bool useGamma = _light_use_gamma && _light_has_color && (id < 3);
  485. return _toPWM(_light_channels[id].current, useGamma, _light_channels[id].inverse);
  486. }
  487. void _lightTransition(unsigned long step) {
  488. // Transitions based on current step. If step == 0, then it is the last transition
  489. for (auto& channel : _light_channels) {
  490. if (!step) {
  491. channel.current = channel.target;
  492. } else {
  493. channel.current += (double) (channel.target - channel.current) / (step + 1);
  494. }
  495. }
  496. }
  497. void _lightProviderScheduleUpdate(unsigned long steps);
  498. void _lightProviderUpdate(unsigned long steps) {
  499. if (_light_provider_update) return;
  500. _light_provider_update = true;
  501. _lightTransition(--steps);
  502. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  503. for (unsigned char i=0; i<_light_channels.size(); i++) {
  504. _my92xx->setChannel(_light_channel_map[i], _toPWM(i));
  505. }
  506. _my92xx->setState(true);
  507. _my92xx->update();
  508. #endif
  509. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  510. for (unsigned int i=0; i < _light_channels.size(); i++) {
  511. pwm_set_duty(_toPWM(i), i);
  512. }
  513. pwm_start();
  514. #endif
  515. // This is not the final value, update again
  516. if (steps) _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  517. _light_provider_update = false;
  518. }
  519. void _lightProviderScheduleUpdate(unsigned long steps) {
  520. schedule_function(std::bind(_lightProviderUpdate, steps));
  521. }
  522. // -----------------------------------------------------------------------------
  523. // PERSISTANCE
  524. // -----------------------------------------------------------------------------
  525. union light_rtcmem_t {
  526. struct {
  527. uint8_t channels[Light::ChannelsMax];
  528. uint8_t brightness;
  529. uint16_t mired;
  530. } __attribute__((packed)) packed;
  531. uint64_t value;
  532. };
  533. void _lightSaveRtcmem() {
  534. if (lightChannels() > Light::ChannelsMax) return;
  535. light_rtcmem_t light;
  536. for (unsigned int i=0; i < lightChannels(); i++) {
  537. light.packed.channels[i] = _light_channels[i].inputValue;
  538. }
  539. light.packed.brightness = _light_brightness;
  540. light.packed.mired = _light_mireds;
  541. Rtcmem->light = light.value;
  542. }
  543. void _lightRestoreRtcmem() {
  544. if (lightChannels() > Light::ChannelsMax) return;
  545. light_rtcmem_t light;
  546. light.value = Rtcmem->light;
  547. for (unsigned int i=0; i < lightChannels(); i++) {
  548. _light_channels[i].inputValue = light.packed.channels[i];
  549. }
  550. _light_brightness = light.packed.brightness;
  551. _light_mireds = light.packed.mired;
  552. }
  553. void _lightSaveSettings() {
  554. for (unsigned char i=0; i < _light_channels.size(); ++i) {
  555. setSetting({"ch", i}, _light_channels[i].inputValue);
  556. }
  557. setSetting("brightness", _light_brightness);
  558. setSetting("mireds", _light_mireds);
  559. saveSettings();
  560. }
  561. void _lightRestoreSettings() {
  562. for (unsigned char i=0; i < _light_channels.size(); ++i) {
  563. _light_channels[i].inputValue = getSetting({"ch", i}, (i == 0) ? Light::VALUE_MAX : 0);
  564. }
  565. _light_brightness = getSetting("brightness", Light::BRIGHTNESS_MAX);
  566. _light_mireds = getSetting("mireds", _light_mireds);
  567. }
  568. // -----------------------------------------------------------------------------
  569. // MQTT
  570. // -----------------------------------------------------------------------------
  571. #if MQTT_SUPPORT
  572. void _lightMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  573. String mqtt_group_color = getSetting("mqttGroupColor");
  574. if (type == MQTT_CONNECT_EVENT) {
  575. mqttSubscribe(MQTT_TOPIC_BRIGHTNESS);
  576. if (_light_has_color) {
  577. mqttSubscribe(MQTT_TOPIC_COLOR_RGB);
  578. mqttSubscribe(MQTT_TOPIC_COLOR_HSV);
  579. mqttSubscribe(MQTT_TOPIC_TRANSITION);
  580. }
  581. if (_light_has_color || _light_use_cct) {
  582. mqttSubscribe(MQTT_TOPIC_MIRED);
  583. mqttSubscribe(MQTT_TOPIC_KELVIN);
  584. }
  585. // Group color
  586. if (mqtt_group_color.length() > 0) mqttSubscribeRaw(mqtt_group_color.c_str());
  587. // Channels
  588. char buffer[strlen(MQTT_TOPIC_CHANNEL) + 3];
  589. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_CHANNEL);
  590. mqttSubscribe(buffer);
  591. }
  592. if (type == MQTT_MESSAGE_EVENT) {
  593. // Group color
  594. if ((mqtt_group_color.length() > 0) && (mqtt_group_color.equals(topic))) {
  595. lightColor(payload, true);
  596. lightUpdate(true, mqttForward(), false);
  597. return;
  598. }
  599. // Match topic
  600. String t = mqttMagnitude((char *) topic);
  601. // Color temperature in mireds
  602. if (t.equals(MQTT_TOPIC_MIRED)) {
  603. _lightAdjustMireds(payload);
  604. lightUpdate(true, mqttForward());
  605. return;
  606. }
  607. // Color temperature in kelvins
  608. if (t.equals(MQTT_TOPIC_KELVIN)) {
  609. _lightAdjustKelvin(payload);
  610. lightUpdate(true, mqttForward());
  611. return;
  612. }
  613. // Color
  614. if (t.equals(MQTT_TOPIC_COLOR_RGB)) {
  615. lightColor(payload, true);
  616. lightUpdate(true, mqttForward());
  617. return;
  618. }
  619. if (t.equals(MQTT_TOPIC_COLOR_HSV)) {
  620. lightColor(payload, false);
  621. lightUpdate(true, mqttForward());
  622. return;
  623. }
  624. // Brightness
  625. if (t.equals(MQTT_TOPIC_BRIGHTNESS)) {
  626. _lightAdjustBrightness(payload);
  627. lightUpdate(true, mqttForward());
  628. return;
  629. }
  630. // Transitions
  631. if (t.equals(MQTT_TOPIC_TRANSITION)) {
  632. lightTransitionTime(atol(payload));
  633. return;
  634. }
  635. // Channel
  636. if (t.startsWith(MQTT_TOPIC_CHANNEL)) {
  637. unsigned int channelID = t.substring(strlen(MQTT_TOPIC_CHANNEL)+1).toInt();
  638. if (channelID >= _light_channels.size()) {
  639. DEBUG_MSG_P(PSTR("[LIGHT] Wrong channelID (%d)\n"), channelID);
  640. return;
  641. }
  642. _lightAdjustChannel(channelID, payload);
  643. lightUpdate(true, mqttForward());
  644. return;
  645. }
  646. }
  647. }
  648. void lightMQTT() {
  649. char buffer[20];
  650. if (_light_has_color) {
  651. // Color
  652. if (getSetting("useCSS", 1 == LIGHT_USE_CSS)) {
  653. _toRGB(buffer, sizeof(buffer), true);
  654. } else {
  655. _toLong(buffer, sizeof(buffer), true);
  656. }
  657. mqttSend(MQTT_TOPIC_COLOR_RGB, buffer);
  658. _toHSV(buffer, sizeof(buffer));
  659. mqttSend(MQTT_TOPIC_COLOR_HSV, buffer);
  660. }
  661. if (_light_has_color || _light_use_cct) {
  662. // Mireds
  663. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_mireds);
  664. mqttSend(MQTT_TOPIC_MIRED, buffer);
  665. }
  666. // Channels
  667. for (unsigned int i=0; i < _light_channels.size(); i++) {
  668. itoa(_light_channels[i].target, buffer, 10);
  669. mqttSend(MQTT_TOPIC_CHANNEL, i, buffer);
  670. }
  671. // Brightness
  672. snprintf_P(buffer, sizeof(buffer), PSTR("%d"), _light_brightness);
  673. mqttSend(MQTT_TOPIC_BRIGHTNESS, buffer);
  674. }
  675. void lightMQTTGroup() {
  676. const String mqtt_group_color = getSetting("mqttGroupColor");
  677. if (mqtt_group_color.length()) {
  678. mqttSendRaw(mqtt_group_color.c_str(), _toCSV(false).c_str());
  679. }
  680. }
  681. #endif
  682. // -----------------------------------------------------------------------------
  683. // Broker
  684. // -----------------------------------------------------------------------------
  685. #if BROKER_SUPPORT
  686. void lightBroker() {
  687. for (unsigned int id = 0; id < _light_channels.size(); ++id) {
  688. StatusBroker::Publish(MQTT_TOPIC_CHANNEL, id, _light_channels[id].value);
  689. }
  690. }
  691. #endif
  692. // -----------------------------------------------------------------------------
  693. // API
  694. // -----------------------------------------------------------------------------
  695. #if API_SUPPORT
  696. bool _lightTryParseChannel(const char* p, unsigned char& id) {
  697. char* endp { nullptr };
  698. const unsigned long result { strtoul(p, &endp, 10) };
  699. if ((endp == p) || (*endp != '\0') || (result >= lightChannels())) {
  700. DEBUG_MSG_P(PSTR("[LIGHT] Invalid channelID (%s)\n"), p);
  701. return false;
  702. }
  703. id = result;
  704. return true;
  705. }
  706. template <typename T>
  707. bool _lightApiTryHandle(ApiRequest& request, T&& callback) {
  708. auto id_param = request.wildcard(0);
  709. unsigned char id;
  710. if (!_lightTryParseChannel(id_param.c_str(), id)) {
  711. return false;
  712. }
  713. return callback(id);
  714. }
  715. void _lightApiSetup() {
  716. if (_light_has_color) {
  717. apiRegister(F(MQTT_TOPIC_COLOR_RGB),
  718. [](ApiRequest& request) {
  719. auto result = getSetting("useCSS", 1 == LIGHT_USE_CSS)
  720. ? _toRGB(true) : _toLong(true);
  721. request.send(result);
  722. return true;
  723. },
  724. [](ApiRequest& request) {
  725. lightColor(request.param(F("value")), true);
  726. lightUpdate(true, true);
  727. return true;
  728. }
  729. );
  730. apiRegister(F(MQTT_TOPIC_COLOR_HSV),
  731. [](ApiRequest& request) {
  732. request.send(_toHSV());
  733. return true;
  734. },
  735. [](ApiRequest& request) {
  736. lightColor(request.param(F("value")), false);
  737. lightUpdate(true, true);
  738. return true;
  739. }
  740. );
  741. apiRegister(F(MQTT_TOPIC_MIRED),
  742. [](ApiRequest& request) {
  743. request.send(String(_light_mireds));
  744. return true;
  745. },
  746. [](ApiRequest& request) {
  747. _lightAdjustMireds(request.param(F("value")));
  748. lightUpdate(true, true);
  749. return true;
  750. }
  751. );
  752. apiRegister(F(MQTT_TOPIC_KELVIN),
  753. [](ApiRequest& request) {
  754. request.send(String(_toKelvin(_light_mireds)));
  755. return true;
  756. },
  757. [](ApiRequest& request) {
  758. _lightAdjustKelvin(request.param(F("value")));
  759. lightUpdate(true, true);
  760. return true;
  761. }
  762. );
  763. }
  764. apiRegister(F(MQTT_TOPIC_TRANSITION),
  765. [](ApiRequest& request) {
  766. request.send(String(lightTransitionTime()));
  767. return true;
  768. },
  769. [](ApiRequest& request) {
  770. lightTransitionTime(request.param(F("value")).toInt());
  771. return true;
  772. }
  773. );
  774. apiRegister(F(MQTT_TOPIC_BRIGHTNESS),
  775. [](ApiRequest& request) {
  776. request.send(String(static_cast<int>(_light_brightness)));
  777. return true;
  778. },
  779. [](ApiRequest& request) {
  780. _lightAdjustBrightness(request.param(F("value")));
  781. lightUpdate(true, true);
  782. return true;
  783. }
  784. );
  785. apiRegister(F(MQTT_TOPIC_CHANNEL "/+"),
  786. [](ApiRequest& request) {
  787. return _lightApiTryHandle(request, [&](unsigned char id) {
  788. request.send(String(static_cast<int>(_light_channels[id].target)));
  789. return true;
  790. });
  791. },
  792. [](ApiRequest& request) {
  793. return _lightApiTryHandle(request, [&](unsigned char id) {
  794. _lightAdjustChannel(id, request.param(F("value")));
  795. lightUpdate(true, true);
  796. return true;
  797. });
  798. }
  799. );
  800. }
  801. #endif // API_SUPPORT
  802. #if WEB_SUPPORT
  803. bool _lightWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  804. if (strncmp(key, "light", 5) == 0) return true;
  805. if (strncmp(key, "use", 3) == 0) return true;
  806. return false;
  807. }
  808. void _lightWebSocketStatus(JsonObject& root) {
  809. if (_light_has_color) {
  810. if (getSetting("useRGB", 1 == LIGHT_USE_RGB)) {
  811. root["rgb"] = lightColor(true);
  812. } else {
  813. root["hsv"] = lightColor(false);
  814. }
  815. }
  816. if (_light_use_cct) {
  817. JsonObject& mireds = root.createNestedObject("mireds");
  818. mireds["value"] = _light_mireds;
  819. mireds["cold"] = _light_cold_mireds;
  820. mireds["warm"] = _light_warm_mireds;
  821. root["useCCT"] = _light_use_cct;
  822. }
  823. JsonArray& channels = root.createNestedArray("channels");
  824. for (unsigned char id=0; id < _light_channels.size(); id++) {
  825. channels.add(lightChannel(id));
  826. }
  827. root["brightness"] = lightBrightness();
  828. }
  829. void _lightWebSocketOnVisible(JsonObject& root) {
  830. root["colorVisible"] = 1;
  831. }
  832. void _lightWebSocketOnConnected(JsonObject& root) {
  833. root["mqttGroupColor"] = getSetting("mqttGroupColor");
  834. root["useColor"] = _light_has_color;
  835. root["useWhite"] = _light_use_white;
  836. root["useGamma"] = _light_use_gamma;
  837. root["useTransitions"] = _light_use_transitions;
  838. root["useCSS"] = getSetting("useCSS", 1 == LIGHT_USE_CSS);
  839. root["useRGB"] = getSetting("useRGB", 1 == LIGHT_USE_RGB);
  840. root["lightTime"] = _light_transition_time;
  841. _lightWebSocketStatus(root);
  842. }
  843. void _lightWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  844. if (_light_has_color) {
  845. if (strcmp(action, "color") == 0) {
  846. if (data.containsKey("rgb")) {
  847. lightColor(data["rgb"].as<const char*>(), true);
  848. lightUpdate(true, true);
  849. }
  850. if (data.containsKey("hsv")) {
  851. lightColor(data["hsv"].as<const char*>(), false);
  852. lightUpdate(true, true);
  853. }
  854. }
  855. }
  856. if (_light_use_cct) {
  857. if (strcmp(action, "mireds") == 0) {
  858. _fromMireds(data["mireds"]);
  859. lightUpdate(true, true);
  860. }
  861. }
  862. if (strcmp(action, "channel") == 0) {
  863. if (data.containsKey("id") && data.containsKey("value")) {
  864. lightChannel(data["id"].as<unsigned char>(), data["value"].as<int>());
  865. lightUpdate(true, true);
  866. }
  867. }
  868. if (strcmp(action, "brightness") == 0) {
  869. if (data.containsKey("value")) {
  870. lightBrightness(data["value"].as<int>());
  871. lightUpdate(true, true);
  872. }
  873. }
  874. }
  875. #endif
  876. #if TERMINAL_SUPPORT
  877. void _lightChannelDebug(unsigned char id) {
  878. DEBUG_MSG_P(PSTR("Channel #%u (%s): %d\n"), id, lightDesc(id).c_str(), lightChannel(id));
  879. }
  880. void _lightInitCommands() {
  881. terminalRegisterCommand(F("BRIGHTNESS"), [](const terminal::CommandContext& ctx) {
  882. if (ctx.argc > 1) {
  883. _lightAdjustBrightness(ctx.argv[1].c_str());
  884. lightUpdate(true, true);
  885. }
  886. DEBUG_MSG_P(PSTR("Brightness: %u\n"), lightBrightness());
  887. terminalOK();
  888. });
  889. terminalRegisterCommand(F("CHANNEL"), [](const terminal::CommandContext& ctx) {
  890. if (!lightChannels()) return;
  891. auto id = -1;
  892. if (ctx.argc > 1) {
  893. id = ctx.argv[1].toInt();
  894. }
  895. if (id < 0 || id >= static_cast<decltype(id)>(lightChannels())) {
  896. for (unsigned char index = 0; index < lightChannels(); ++index) {
  897. _lightChannelDebug(index);
  898. }
  899. return;
  900. }
  901. if (ctx.argc > 2) {
  902. _lightAdjustChannel(id, ctx.argv[2].c_str());
  903. lightUpdate(true, true);
  904. }
  905. _lightChannelDebug(id);
  906. terminalOK();
  907. });
  908. terminalRegisterCommand(F("COLOR"), [](const terminal::CommandContext& ctx) {
  909. if (ctx.argc > 1) {
  910. lightColor(ctx.argv[1].c_str());
  911. lightUpdate(true, true);
  912. }
  913. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  914. terminalOK();
  915. });
  916. terminalRegisterCommand(F("KELVIN"), [](const terminal::CommandContext& ctx) {
  917. if (ctx.argc > 1) {
  918. _lightAdjustKelvin(ctx.argv[1].c_str());
  919. lightUpdate(true, true);
  920. }
  921. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  922. terminalOK();
  923. });
  924. terminalRegisterCommand(F("MIRED"), [](const terminal::CommandContext& ctx) {
  925. if (ctx.argc > 1) {
  926. _lightAdjustMireds(ctx.argv[1]);
  927. lightUpdate(true, true);
  928. }
  929. DEBUG_MSG_P(PSTR("Color: %s\n"), lightColor().c_str());
  930. terminalOK();
  931. });
  932. }
  933. #endif // TERMINAL_SUPPORT
  934. size_t lightChannels() {
  935. return _light_channels.size();
  936. }
  937. bool lightHasColor() {
  938. return _light_has_color;
  939. }
  940. bool lightUseCCT() {
  941. return _light_use_cct;
  942. }
  943. void _lightComms(unsigned char mask) {
  944. // Report color and brightness to MQTT broker
  945. #if MQTT_SUPPORT
  946. if (mask & Light::COMMS_NORMAL) lightMQTT();
  947. if (mask & Light::COMMS_GROUP) lightMQTTGroup();
  948. #endif
  949. // Report color to WS clients (using current brightness setting)
  950. #if WEB_SUPPORT
  951. wsPost(_lightWebSocketStatus);
  952. #endif
  953. // Report channels to local broker
  954. #if BROKER_SUPPORT
  955. lightBroker();
  956. #endif
  957. }
  958. void lightUpdate(bool save, bool forward, bool group_forward) {
  959. // Calculate values based on inputs and brightness
  960. _light_brightness_func();
  961. // Only update if a channel has changed
  962. if (!_light_dirty) return;
  963. _light_dirty = false;
  964. // Update channels
  965. for (unsigned int i=0; i < _light_channels.size(); i++) {
  966. _light_channels[i].target = _light_state && _light_channels[i].state ? _light_channels[i].value : 0;
  967. //DEBUG_MSG_P("[LIGHT] Channel #%u target value: %u\n", i, _light_channels[i].target);
  968. }
  969. // Channel transition will be handled by the provider function
  970. // User can configure total transition time, step time is a fixed value
  971. const unsigned long steps = _light_use_transitions ? _light_transition_time / LIGHT_TRANSITION_STEP : 1;
  972. _light_transition_ticker.once_ms(LIGHT_TRANSITION_STEP, _lightProviderScheduleUpdate, steps);
  973. // Delay every communication 100ms to avoid jamming
  974. const unsigned char mask =
  975. ((forward) ? Light::COMMS_NORMAL : Light::COMMS_NONE) |
  976. ((group_forward) ? Light::COMMS_GROUP : Light::COMMS_NONE);
  977. _light_comms_ticker.once_ms(LIGHT_COMMS_DELAY, _lightComms, mask);
  978. _lightSaveRtcmem();
  979. #if LIGHT_SAVE_ENABLED
  980. // Delay saving to EEPROM 5 seconds to avoid wearing it out unnecessarily
  981. if (save) _light_save_ticker.once(LIGHT_SAVE_DELAY, _lightSaveSettings);
  982. #endif
  983. };
  984. void lightUpdate(bool save, bool forward) {
  985. lightUpdate(save, forward, true);
  986. }
  987. #if LIGHT_SAVE_ENABLED == 0
  988. void lightSave() {
  989. _lightSaveSettings();
  990. }
  991. #endif
  992. void lightState(unsigned char id, bool state) {
  993. if (id >= _light_channels.size()) return;
  994. if (_light_channels[id].state != state) {
  995. _light_channels[id].state = state;
  996. _light_dirty = true;
  997. }
  998. }
  999. bool lightState(unsigned char id) {
  1000. if (id >= _light_channels.size()) return false;
  1001. return _light_channels[id].state;
  1002. }
  1003. void lightState(bool state) {
  1004. if (_light_state != state) {
  1005. _light_state = state;
  1006. _light_dirty = true;
  1007. }
  1008. }
  1009. bool lightState() {
  1010. return _light_state;
  1011. }
  1012. void lightColor(const char * color, bool rgb) {
  1013. DEBUG_MSG_P(PSTR("[LIGHT] %s: %s\n"), rgb ? "RGB" : "HSV", color);
  1014. if (rgb) {
  1015. _fromRGB(color);
  1016. } else {
  1017. _fromHSV(color);
  1018. }
  1019. }
  1020. void lightColor(const String& color, bool rgb) {
  1021. lightColor(color.c_str(), rgb);
  1022. }
  1023. void lightColor(const char* color) {
  1024. lightColor(color, true);
  1025. }
  1026. void lightColor(const String& color) {
  1027. lightColor(color.c_str());
  1028. }
  1029. void lightColor(unsigned long color) {
  1030. _fromLong(color, false);
  1031. }
  1032. String lightColor(bool rgb) {
  1033. char str[12];
  1034. if (rgb) {
  1035. _toRGB(str, sizeof(str));
  1036. } else {
  1037. _toHSV(str, sizeof(str));
  1038. }
  1039. return String(str);
  1040. }
  1041. String lightColor() {
  1042. return lightColor(true);
  1043. }
  1044. long lightChannel(unsigned char id) {
  1045. if (id >= _light_channels.size()) return 0;
  1046. return _light_channels[id].inputValue;
  1047. }
  1048. void lightChannel(unsigned char id, long value) {
  1049. if (id >= _light_channels.size()) return;
  1050. _setInputValue(id, constrain(value, Light::VALUE_MIN, Light::VALUE_MAX));
  1051. }
  1052. void lightChannelStep(unsigned char id, long steps, long multiplier) {
  1053. lightChannel(id, static_cast<int>(lightChannel(id)) + (steps * multiplier));
  1054. }
  1055. long lightBrightness() {
  1056. return _light_brightness;
  1057. }
  1058. void lightBrightness(long brightness) {
  1059. _light_brightness = constrain(brightness, Light::BRIGHTNESS_MIN, Light::BRIGHTNESS_MAX);
  1060. }
  1061. void lightBrightnessStep(long steps, long multiplier) {
  1062. lightBrightness(static_cast<int>(_light_brightness) + (steps * multiplier));
  1063. }
  1064. unsigned int lightTransitionTime() {
  1065. if (_light_use_transitions) {
  1066. return _light_transition_time;
  1067. } else {
  1068. return 0;
  1069. }
  1070. }
  1071. void lightTransitionTime(unsigned long ms) {
  1072. if (0 == ms) {
  1073. _light_use_transitions = false;
  1074. } else {
  1075. _light_use_transitions = true;
  1076. _light_transition_time = ms;
  1077. }
  1078. setSetting("useTransitions", _light_use_transitions);
  1079. setSetting("lightTime", _light_transition_time);
  1080. saveSettings();
  1081. }
  1082. // -----------------------------------------------------------------------------
  1083. // SETUP
  1084. // -----------------------------------------------------------------------------
  1085. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  1086. const unsigned long _light_iomux[16] PROGMEM = {
  1087. PERIPHS_IO_MUX_GPIO0_U, PERIPHS_IO_MUX_U0TXD_U, PERIPHS_IO_MUX_GPIO2_U, PERIPHS_IO_MUX_U0RXD_U,
  1088. PERIPHS_IO_MUX_GPIO4_U, PERIPHS_IO_MUX_GPIO5_U, PERIPHS_IO_MUX_SD_CLK_U, PERIPHS_IO_MUX_SD_DATA0_U,
  1089. PERIPHS_IO_MUX_SD_DATA1_U, PERIPHS_IO_MUX_SD_DATA2_U, PERIPHS_IO_MUX_SD_DATA3_U, PERIPHS_IO_MUX_SD_CMD_U,
  1090. PERIPHS_IO_MUX_MTDI_U, PERIPHS_IO_MUX_MTCK_U, PERIPHS_IO_MUX_MTMS_U, PERIPHS_IO_MUX_MTDO_U
  1091. };
  1092. const unsigned long _light_iofunc[16] PROGMEM = {
  1093. FUNC_GPIO0, FUNC_GPIO1, FUNC_GPIO2, FUNC_GPIO3,
  1094. FUNC_GPIO4, FUNC_GPIO5, FUNC_GPIO6, FUNC_GPIO7,
  1095. FUNC_GPIO8, FUNC_GPIO9, FUNC_GPIO10, FUNC_GPIO11,
  1096. FUNC_GPIO12, FUNC_GPIO13, FUNC_GPIO14, FUNC_GPIO15
  1097. };
  1098. #endif
  1099. void _lightConfigure() {
  1100. _light_has_color = getSetting("useColor", 1 == LIGHT_USE_COLOR);
  1101. if (_light_has_color && (_light_channels.size() < 3)) {
  1102. _light_has_color = false;
  1103. setSetting("useColor", _light_has_color);
  1104. }
  1105. _light_use_white = getSetting("useWhite", 1 == LIGHT_USE_WHITE);
  1106. if (_light_use_white && (_light_channels.size() < 4) && (_light_channels.size() != 2)) {
  1107. _light_use_white = false;
  1108. setSetting("useWhite", _light_use_white);
  1109. }
  1110. if (_light_has_color) {
  1111. if (_light_use_white) {
  1112. _light_brightness_func = _lightApplyBrightnessColor;
  1113. } else {
  1114. _light_brightness_func = []() { _lightApplyBrightness(3); };
  1115. }
  1116. } else {
  1117. _light_brightness_func = []() { _lightApplyBrightness(); };
  1118. }
  1119. _light_use_cct = getSetting("useCCT", 1 == LIGHT_USE_CCT);
  1120. if (_light_use_cct && (((_light_channels.size() < 5) && (_light_channels.size() != 2)) || !_light_use_white)) {
  1121. _light_use_cct = false;
  1122. setSetting("useCCT", _light_use_cct);
  1123. }
  1124. _light_cold_mireds = getSetting("lightColdMired", LIGHT_COLDWHITE_MIRED);
  1125. _light_warm_mireds = getSetting("lightWarmMired", LIGHT_WARMWHITE_MIRED);
  1126. _light_cold_kelvin = (1000000L / _light_cold_mireds);
  1127. _light_warm_kelvin = (1000000L / _light_warm_mireds);
  1128. _light_use_gamma = getSetting("useGamma", 1 == LIGHT_USE_GAMMA);
  1129. _light_use_transitions = getSetting("useTransitions", 1 == LIGHT_USE_TRANSITIONS);
  1130. _light_transition_time = getSetting("lightTime", LIGHT_TRANSITION_TIME);
  1131. }
  1132. // Dummy channel setup for light providers without real GPIO
  1133. void lightSetupChannels(unsigned char size) {
  1134. size = constrain(size, 0, Light::ChannelsMax);
  1135. if (size == _light_channels.size()) return;
  1136. _light_channels.resize(size);
  1137. }
  1138. void lightSetup() {
  1139. const auto enable_pin = getSetting("ltEnableGPIO", _lightEnablePin());
  1140. if (enable_pin != GPIO_NONE) {
  1141. pinMode(enable_pin, OUTPUT);
  1142. digitalWrite(enable_pin, HIGH);
  1143. }
  1144. _light_channels.reserve(Light::ChannelsMax);
  1145. #if LIGHT_PROVIDER == LIGHT_PROVIDER_MY92XX
  1146. _my92xx = new my92xx(MY92XX_MODEL, MY92XX_CHIPS, MY92XX_DI_PIN, MY92XX_DCKI_PIN, MY92XX_COMMAND);
  1147. lightSetupChannels(LIGHT_CHANNELS);
  1148. #endif
  1149. #if LIGHT_PROVIDER == LIGHT_PROVIDER_DIMMER
  1150. // Initial duty value (will be passed to pwm_set_duty(...), OFF in this case)
  1151. uint32_t pwm_duty_init[Light::ChannelsMax] = {0};
  1152. // 3-tuples of MUX_REGISTER, MUX_VALUE and GPIO number
  1153. uint32_t io_info[Light::ChannelsMax][3];
  1154. for (unsigned char index = 0; index < Light::ChannelsMax; ++index) {
  1155. // Load up until first GPIO_NONE. Allow settings to override, but not remove values
  1156. const auto pin = getSetting({"ltDimmerGPIO", index}, _lightChannelPin(index));
  1157. if (!gpioValid(pin)) {
  1158. break;
  1159. }
  1160. _light_channels.emplace_back(pin, getSetting({"ltDimmerInv", index}, _lightInverse(index)));
  1161. io_info[index][0] = pgm_read_dword(&_light_iomux[pin]);
  1162. io_info[index][1] = pgm_read_dword(&_light_iofunc[pin]);
  1163. io_info[index][2] = pin;
  1164. pinMode(pin, OUTPUT);
  1165. }
  1166. // with 0 channels this should not do anything at all and provider will never call pwm_set_duty(...)
  1167. pwm_init(Light::PWM_MAX, pwm_duty_init, _light_channels.size(), io_info);
  1168. pwm_start();
  1169. #endif
  1170. #if LIGHT_PROVIDER == LIGHT_PROVIDER_TUYA
  1171. Tuya::tuyaSetupLight();
  1172. #endif
  1173. DEBUG_MSG_P(PSTR("[LIGHT] LIGHT_PROVIDER = %d\n"), LIGHT_PROVIDER);
  1174. DEBUG_MSG_P(PSTR("[LIGHT] Number of channels: %d\n"), _light_channels.size());
  1175. _lightConfigure();
  1176. if (rtcmemStatus()) {
  1177. _lightRestoreRtcmem();
  1178. } else {
  1179. _lightRestoreSettings();
  1180. }
  1181. lightUpdate(false, false);
  1182. #if WEB_SUPPORT
  1183. wsRegister()
  1184. .onVisible(_lightWebSocketOnVisible)
  1185. .onConnected(_lightWebSocketOnConnected)
  1186. .onAction(_lightWebSocketOnAction)
  1187. .onKeyCheck(_lightWebSocketOnKeyCheck);
  1188. #endif
  1189. #if API_SUPPORT
  1190. _lightApiSetup();
  1191. #endif
  1192. #if MQTT_SUPPORT
  1193. mqttRegister(_lightMQTTCallback);
  1194. #endif
  1195. #if TERMINAL_SUPPORT
  1196. _lightInitCommands();
  1197. #endif
  1198. // Main callbacks
  1199. espurnaRegisterReload([]() {
  1200. #if LIGHT_SAVE_ENABLED == 0
  1201. lightSave();
  1202. #endif
  1203. _lightConfigure();
  1204. });
  1205. }
  1206. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE