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.

1586 lines
46 KiB

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
5 years ago
5 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
  1. /*
  2. RELAY MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "relay.h"
  6. #if RELAY_SUPPORT
  7. #include <Ticker.h>
  8. #include <ArduinoJson.h>
  9. #include <vector>
  10. #include <functional>
  11. #include <bitset>
  12. #include "api.h"
  13. #include "broker.h"
  14. #include "light.h"
  15. #include "mqtt.h"
  16. #include "rfbridge.h"
  17. #include "rpc.h"
  18. #include "rtcmem.h"
  19. #include "settings.h"
  20. #include "storage_eeprom.h"
  21. #include "tuya.h"
  22. #include "utils.h"
  23. #include "ws.h"
  24. #include "libs/BasePin.h"
  25. #include "gpio_pin.h"
  26. #include "mcp23s08_pin.h"
  27. #include "relay_config.h"
  28. class DummyPin final : public BasePin {
  29. public:
  30. DummyPin(unsigned char pin) :
  31. BasePin(pin)
  32. {}
  33. void pinMode(int8_t) override {
  34. }
  35. void digitalWrite(int8_t) override {
  36. }
  37. int digitalRead() override {
  38. return 0;
  39. }
  40. String description() const override {
  41. return F("DummyPin");
  42. }
  43. };
  44. struct relay_t {
  45. using pin_type = BasePin;
  46. // Share the same dummy pin between different relays, no need to duplicate
  47. static pin_type* DummyPinInstance;
  48. // Default to empty relay configuration, as we allow switches to exist without real GPIOs
  49. relay_t() = default;
  50. relay_t(pin_type* pin_, unsigned char type_, pin_type* reset_pin_) :
  51. pin(pin_),
  52. reset_pin(reset_pin_),
  53. type(type_)
  54. {}
  55. pin_type* pin { DummyPinInstance }; // GPIO pin for the relay
  56. pin_type* reset_pin { DummyPinInstance }; // GPIO to reset the relay if RELAY_TYPE_LATCHED
  57. unsigned char type { RELAY_TYPE_NORMAL }; // RELAY_TYPE_NORMAL, RELAY_TYPE_INVERSE, RELAY_TYPE_LATCHED or RELAY_TYPE_LATCHED_INVERSE
  58. unsigned long delay_on { 0ul }; // Delay to turn relay ON
  59. unsigned long delay_off { 0ul }; // Delay to turn relay OFF
  60. unsigned char pulse { RELAY_PULSE_NONE }; // RELAY_PULSE_NONE, RELAY_PULSE_OFF or RELAY_PULSE_ON
  61. unsigned long pulse_ms { 0ul }; // Pulse length in millis
  62. // Status variables
  63. bool current_status { false }; // Holds the current (physical) status of the relay
  64. bool target_status { false }; // Holds the target status
  65. unsigned char lock { RELAY_LOCK_DISABLED }; // Holds the value of target status, that cannot be changed afterwards. (0 for false, 1 for true, 2 to disable)
  66. unsigned long fw_start { 0ul }; // Flood window start time
  67. unsigned char fw_count { 0u }; // Number of changes within the current flood window
  68. unsigned long change_start { 0ul }; // Time when relay was scheduled to change
  69. unsigned long change_delay { 0ul }; // Delay until the next change
  70. bool report { false }; // Whether to report to own topic
  71. bool group_report { false }; // Whether to report to group topic
  72. // Helper objects
  73. Ticker pulseTicker; // Holds the pulse back timer
  74. };
  75. BasePin* relay_t::DummyPinInstance = new DummyPin(GPIO_NONE);
  76. std::vector<relay_t> _relays;
  77. bool _relayRecursive = false;
  78. size_t _relayDummy = 0;
  79. unsigned long _relay_flood_window = (1000 * RELAY_FLOOD_WINDOW);
  80. unsigned long _relay_flood_changes = RELAY_FLOOD_CHANGES;
  81. unsigned long _relay_delay_interlock;
  82. unsigned char _relay_sync_mode = RELAY_SYNC_ANY;
  83. bool _relay_sync_locked = false;
  84. Ticker _relay_save_timer;
  85. Ticker _relay_sync_timer;
  86. #if WEB_SUPPORT
  87. bool _relay_report_ws = false;
  88. #endif // WEB_SUPPORT
  89. #if MQTT_SUPPORT || API_SUPPORT
  90. String _relay_rpc_payload_on;
  91. String _relay_rpc_payload_off;
  92. String _relay_rpc_payload_toggle;
  93. #endif // MQTT_SUPPORT || API_SUPPORT
  94. // -----------------------------------------------------------------------------
  95. // UTILITY
  96. // -----------------------------------------------------------------------------
  97. bool _relayTryParseId(const char* p, unsigned char& relayID) {
  98. char* endp { nullptr };
  99. const unsigned long result { strtoul(p, &endp, 10) };
  100. if ((endp == p) || (*endp != '\0') || (result >= relayCount())) {
  101. DEBUG_MSG_P(PSTR("[RELAY] Invalid relayID (%s)\n"), p);
  102. return false;
  103. }
  104. relayID = result;
  105. return true;
  106. }
  107. bool _relayTryParseIdFromPath(const String& endpoint, unsigned char& relayID) {
  108. int next_slash { endpoint.lastIndexOf('/') };
  109. if (next_slash < 0) {
  110. return false;
  111. }
  112. const char* p { endpoint.c_str() + next_slash + 1 };
  113. if (*p == '\0') {
  114. DEBUG_MSG_P(PSTR("[RELAY] relayID was not specified\n"));
  115. return false;
  116. }
  117. return _relayTryParseId(p, relayID);
  118. }
  119. void _relayHandleStatus(unsigned char relayID, PayloadStatus status) {
  120. switch (status) {
  121. case PayloadStatus::Off:
  122. relayStatus(relayID, false);
  123. break;
  124. case PayloadStatus::On:
  125. relayStatus(relayID, true);
  126. break;
  127. case PayloadStatus::Toggle:
  128. relayToggle(relayID);
  129. break;
  130. case PayloadStatus::Unknown:
  131. break;
  132. }
  133. }
  134. bool _relayHandlePayload(unsigned char relayID, const char* payload) {
  135. auto status = relayParsePayload(payload);
  136. if (status != PayloadStatus::Unknown) {
  137. _relayHandleStatus(relayID, status);
  138. return true;
  139. }
  140. DEBUG_MSG_P(PSTR("[RELAY] Invalid API payload (%s)\n"), payload);
  141. return false;
  142. }
  143. bool _relayHandlePayload(unsigned char relayID, const String& payload) {
  144. return _relayHandlePayload(relayID, payload.c_str());
  145. }
  146. bool _relayHandlePulsePayload(unsigned char id, const char* payload) {
  147. unsigned long pulse = 1000 * atof(payload);
  148. if (!pulse) {
  149. return false;
  150. }
  151. if (RELAY_PULSE_NONE != _relays[id].pulse) {
  152. DEBUG_MSG_P(PSTR("[RELAY] Overriding relayID %u pulse settings\n"), id);
  153. }
  154. _relays[id].pulse_ms = pulse;
  155. _relays[id].pulse = relayStatus(id) ? RELAY_PULSE_ON : RELAY_PULSE_OFF;
  156. relayToggle(id, true, false);
  157. return true;
  158. }
  159. bool _relayHandlePulsePayload(unsigned char id, const String& payload) {
  160. return _relayHandlePulsePayload(id, payload.c_str());
  161. }
  162. PayloadStatus _relayStatusInvert(PayloadStatus status) {
  163. return (status == PayloadStatus::On) ? PayloadStatus::Off : status;
  164. }
  165. PayloadStatus _relayStatusTyped(unsigned char id) {
  166. if (id >= _relays.size()) return PayloadStatus::Off;
  167. const bool status = _relays[id].current_status;
  168. return (status) ? PayloadStatus::On : PayloadStatus::Off;
  169. }
  170. void _relayLockAll() {
  171. for (auto& relay : _relays) {
  172. relay.lock = relay.target_status ? RELAY_LOCK_ON : RELAY_LOCK_OFF;
  173. }
  174. _relay_sync_locked = true;
  175. }
  176. void _relayUnlockAll() {
  177. for (auto& relay : _relays) {
  178. relay.lock = RELAY_LOCK_DISABLED;
  179. }
  180. _relay_sync_locked = false;
  181. }
  182. bool _relayStatusLock(unsigned char id, bool status) {
  183. if (_relays[id].lock != RELAY_LOCK_DISABLED) {
  184. bool lock = _relays[id].lock == RELAY_LOCK_ON;
  185. if ((lock != status) || (lock != _relays[id].target_status)) {
  186. _relays[id].target_status = lock;
  187. _relays[id].change_delay = 0;
  188. return false;
  189. }
  190. }
  191. return true;
  192. }
  193. // https://github.com/xoseperez/espurna/issues/1510#issuecomment-461894516
  194. // completely reset timing on the other relay to sync with this one
  195. // to ensure that they change state sequentially
  196. void _relaySyncRelaysDelay(unsigned char first, unsigned char second) {
  197. _relays[second].fw_start = _relays[first].change_start;
  198. _relays[second].fw_count = 1;
  199. _relays[second].change_delay = std::max({
  200. _relay_delay_interlock,
  201. _relays[first].change_delay,
  202. _relays[second].change_delay
  203. });
  204. }
  205. void _relaySyncUnlock() {
  206. bool unlock = true;
  207. bool all_off = true;
  208. for (const auto& relay : _relays) {
  209. unlock = unlock && (relay.current_status == relay.target_status);
  210. if (!unlock) break;
  211. all_off = all_off && !relay.current_status;
  212. }
  213. if (!unlock) return;
  214. auto action = []() {
  215. _relayUnlockAll();
  216. #if WEB_SUPPORT
  217. _relay_report_ws = true;
  218. #endif
  219. };
  220. if (all_off) {
  221. _relay_sync_timer.once_ms(_relay_delay_interlock, action);
  222. } else {
  223. action();
  224. }
  225. }
  226. // -----------------------------------------------------------------------------
  227. // RELAY PROVIDERS
  228. // -----------------------------------------------------------------------------
  229. void _relayProviderStatus(unsigned char id, bool status) {
  230. // Check relay ID
  231. if (id >= _relays.size()) return;
  232. // Store new current status
  233. _relays[id].current_status = status;
  234. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  235. rfbStatus(id, status);
  236. #endif
  237. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  238. // Calculate mask
  239. unsigned char mask=0;
  240. for (unsigned char i=0; i<_relays.size(); i++) {
  241. if (_relays[i].current_status) mask = mask + (1 << i);
  242. }
  243. DEBUG_MSG_P(PSTR("[RELAY] [DUAL] Sending relay mask: %d\n"), mask);
  244. // Send it to F330
  245. Serial.flush();
  246. Serial.write(0xA0);
  247. Serial.write(0x04);
  248. Serial.write(mask);
  249. Serial.write(0xA1);
  250. Serial.flush();
  251. #endif
  252. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  253. Serial.flush();
  254. Serial.write(0xA0);
  255. Serial.write(id + 1);
  256. Serial.write(status);
  257. Serial.write(0xA1 + status + id);
  258. // The serial init are not full recognized by relais board.
  259. // References: https://github.com/xoseperez/espurna/issues/1519 , https://github.com/xoseperez/espurna/issues/1130
  260. delay(100);
  261. Serial.flush();
  262. #endif
  263. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  264. // Real relays
  265. size_t physical = _relays.size() - _relayDummy;
  266. // Support for a mixed of dummy and real relays
  267. // Reference: https://github.com/xoseperez/espurna/issues/1305
  268. if (id >= physical) {
  269. // If the number of dummy relays matches the number of light channels
  270. // assume each relay controls one channel.
  271. // If the number of dummy relays is the number of channels plus 1
  272. // assume the first one controls all the channels and
  273. // the rest one channel each.
  274. // Otherwise every dummy relay controls all channels.
  275. if (_relayDummy == lightChannels()) {
  276. lightState(id-physical, status);
  277. lightState(true);
  278. } else if (_relayDummy == (lightChannels() + 1u)) {
  279. if (id == physical) {
  280. lightState(status);
  281. } else {
  282. lightState(id-1-physical, status);
  283. }
  284. } else {
  285. lightState(status);
  286. }
  287. lightUpdate(true, true);
  288. return;
  289. }
  290. #endif
  291. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || \
  292. (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT) || \
  293. (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  294. // If this is a light, all dummy relays have already been processed above
  295. // we reach here if the user has toggled a physical relay
  296. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  297. _relays[id].pin->digitalWrite(status);
  298. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  299. _relays[id].pin->digitalWrite(!status);
  300. } else if (_relays[id].type == RELAY_TYPE_LATCHED || _relays[id].type == RELAY_TYPE_LATCHED_INVERSE) {
  301. bool pulse = (_relays[id].type == RELAY_TYPE_LATCHED) ? HIGH : LOW;
  302. _relays[id].pin->digitalWrite(!pulse);
  303. if (GPIO_NONE != _relays[id].reset_pin->pin) {
  304. _relays[id].reset_pin->digitalWrite(!pulse);
  305. }
  306. if (status || (GPIO_NONE == _relays[id].reset_pin->pin)) {
  307. _relays[id].pin->digitalWrite(pulse);
  308. } else {
  309. _relays[id].reset_pin->digitalWrite(pulse);
  310. }
  311. nice_delay(RELAY_LATCHING_PULSE);
  312. _relays[id].pin->digitalWrite(!pulse);
  313. if (GPIO_NONE != _relays[id].reset_pin->pin) {
  314. _relays[id].reset_pin->digitalWrite(!pulse);
  315. }
  316. }
  317. #endif
  318. }
  319. /**
  320. * Walks the relay vector processing only those relays
  321. * that have to change to the requested mode
  322. * @bool mode Requested mode
  323. */
  324. void _relayProcess(bool mode) {
  325. bool changed = false;
  326. for (unsigned char id = 0; id < _relays.size(); id++) {
  327. bool target = _relays[id].target_status;
  328. // Only process the relays we have to change
  329. if (target == _relays[id].current_status) continue;
  330. // Only process the relays we have to change to the requested mode
  331. if (target != mode) continue;
  332. // Only process if the change delay has expired
  333. if (_relays[id].change_delay && (millis() - _relays[id].change_start < _relays[id].change_delay)) continue;
  334. // Purge existing delay in case of cancelation
  335. _relays[id].change_delay = 0;
  336. changed = true;
  337. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, target ? "ON" : "OFF");
  338. // Call the provider to perform the action
  339. _relayProviderStatus(id, target);
  340. // Send to Broker
  341. #if BROKER_SUPPORT
  342. StatusBroker::Publish(MQTT_TOPIC_RELAY, id, target);
  343. #endif
  344. // Send MQTT
  345. #if MQTT_SUPPORT
  346. relayMQTT(id);
  347. #endif
  348. #if WEB_SUPPORT
  349. _relay_report_ws = true;
  350. #endif
  351. if (!_relayRecursive) {
  352. relayPulse(id);
  353. // We will trigger a eeprom save only if
  354. // we care about current relay status on boot
  355. const auto boot_mode = getSetting({"relayBoot", id}, RELAY_BOOT_MODE);
  356. const bool save_eeprom = ((RELAY_BOOT_SAME == boot_mode) || (RELAY_BOOT_TOGGLE == boot_mode));
  357. _relay_save_timer.once_ms(RELAY_SAVE_DELAY, relaySave, save_eeprom);
  358. }
  359. _relays[id].report = false;
  360. _relays[id].group_report = false;
  361. }
  362. // Whenever we are using sync modes and any relay had changed the state, check if we can unlock
  363. const bool needs_unlock = ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE));
  364. if (_relay_sync_locked && needs_unlock && changed) {
  365. _relaySyncUnlock();
  366. }
  367. }
  368. #if defined(ITEAD_SONOFF_IFAN02)
  369. unsigned char _relay_ifan02_speeds[] = {0, 1, 3, 5};
  370. unsigned char getSpeed() {
  371. unsigned char speed =
  372. (_relays[1].target_status ? 1 : 0) +
  373. (_relays[2].target_status ? 2 : 0) +
  374. (_relays[3].target_status ? 4 : 0);
  375. for (unsigned char i=0; i<4; i++) {
  376. if (_relay_ifan02_speeds[i] == speed) return i;
  377. }
  378. return 0;
  379. }
  380. void setSpeed(unsigned char speed) {
  381. if ((0 <= speed) & (speed <= 3)) {
  382. if (getSpeed() == speed) return;
  383. unsigned char states = _relay_ifan02_speeds[speed];
  384. for (unsigned char i=0; i<3; i++) {
  385. relayStatus(i+1, states & 1 == 1);
  386. states >>= 1;
  387. }
  388. }
  389. }
  390. #endif
  391. // -----------------------------------------------------------------------------
  392. // RELAY
  393. // -----------------------------------------------------------------------------
  394. // State persistance persistance
  395. namespace {
  396. String u32toString(uint32_t value, int base) {
  397. String result;
  398. result.reserve(32 + 2);
  399. if (base == 2) {
  400. result += "0b";
  401. } else if (base == 8) {
  402. result += "0o";
  403. } else if (base == 16) {
  404. result += "0x";
  405. }
  406. char buffer[33] = {0};
  407. ultoa(value, buffer, base);
  408. result += buffer;
  409. return result;
  410. }
  411. struct RelayMask {
  412. const String as_string;
  413. uint32_t as_u32;
  414. };
  415. RelayMask INLINE _relayMask(uint32_t mask) {
  416. return {std::move(u32toString(mask, 2)), mask};
  417. }
  418. RelayMask INLINE _relayMaskRtcmem() {
  419. return _relayMask(Rtcmem->relay);
  420. }
  421. void INLINE _relayMaskRtcmem(uint32_t mask) {
  422. Rtcmem->relay = mask;
  423. }
  424. void INLINE _relayMaskRtcmem(const RelayMask& mask) {
  425. _relayMaskRtcmem(mask.as_u32);
  426. }
  427. void INLINE _relayMaskRtcmem(const std::bitset<RelaysMax>& bitset) {
  428. _relayMaskRtcmem(bitset.to_ulong());
  429. }
  430. RelayMask INLINE _relayMaskSettings() {
  431. constexpr unsigned long defaultMask { 0ul };
  432. auto value = getSetting("relayBootMask", defaultMask);
  433. return _relayMask(value);
  434. }
  435. void INLINE _relayMaskSettings(uint32_t mask) {
  436. setSetting("relayBootMask", u32toString(mask, 2));
  437. }
  438. void INLINE _relayMaskSettings(const RelayMask& mask) {
  439. setSetting("relayBootMask", mask.as_string);
  440. }
  441. void INLINE _relayMaskSettings(const std::bitset<RelaysMax>& bitset) {
  442. _relayMaskSettings(bitset.to_ulong());
  443. }
  444. } // ns anonymous
  445. // Pulse timers (timer after ON or OFF event)
  446. void relayPulse(unsigned char id) {
  447. _relays[id].pulseTicker.detach();
  448. byte mode = _relays[id].pulse;
  449. if (mode == RELAY_PULSE_NONE) return;
  450. unsigned long ms = _relays[id].pulse_ms;
  451. if (ms == 0) return;
  452. bool status = relayStatus(id);
  453. bool pulseStatus = (mode == RELAY_PULSE_ON);
  454. if (pulseStatus != status) {
  455. DEBUG_MSG_P(PSTR("[RELAY] Scheduling relay #%d back in %lums (pulse)\n"), id, ms);
  456. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  457. // Reconfigure after dynamic pulse
  458. _relays[id].pulse = getSetting({"relayPulse", id}, RELAY_PULSE_MODE);
  459. _relays[id].pulse_ms = 1000 * getSetting({"relayTime", id}, 0.);
  460. }
  461. }
  462. // General relay status control
  463. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  464. if (id == RELAY_NONE) return false;
  465. if (id >= _relays.size()) return false;
  466. if (!_relayStatusLock(id, status)) {
  467. DEBUG_MSG_P(PSTR("[RELAY] #%d is locked to %s\n"), id, _relays[id].current_status ? "ON" : "OFF");
  468. _relays[id].report = true;
  469. _relays[id].group_report = true;
  470. return false;
  471. }
  472. bool changed = false;
  473. if (_relays[id].current_status == status) {
  474. if (_relays[id].target_status != status) {
  475. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  476. _relays[id].target_status = status;
  477. _relays[id].report = false;
  478. _relays[id].group_report = false;
  479. _relays[id].change_delay = 0;
  480. changed = true;
  481. }
  482. // For RFBridge, keep sending the message even if the status is already the required
  483. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  484. rfbStatus(id, status);
  485. #endif
  486. // Update the pulse counter if the relay is already in the non-normal state (#454)
  487. relayPulse(id);
  488. } else {
  489. unsigned long current_time = millis();
  490. unsigned long change_delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  491. _relays[id].fw_count++;
  492. _relays[id].change_start = current_time;
  493. _relays[id].change_delay = std::max(_relays[id].change_delay, change_delay);
  494. // If current_time is off-limits the floodWindow...
  495. const auto fw_diff = current_time - _relays[id].fw_start;
  496. if (fw_diff > _relay_flood_window) {
  497. // We reset the floodWindow
  498. _relays[id].fw_start = current_time;
  499. _relays[id].fw_count = 1;
  500. // If current_time is in the floodWindow and there have been too many requests...
  501. } else if (_relays[id].fw_count >= _relay_flood_changes) {
  502. // We schedule the changes to the end of the floodWindow
  503. // unless it's already delayed beyond that point
  504. _relays[id].change_delay = std::max(change_delay, _relay_flood_window - fw_diff);
  505. // Another option is to always move it forward, starting from current time
  506. //_relays[id].fw_start = current_time;
  507. }
  508. _relays[id].target_status = status;
  509. _relays[id].report = report;
  510. _relays[id].group_report = group_report;
  511. relaySync(id);
  512. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  513. id, status ? "ON" : "OFF", _relays[id].change_delay
  514. );
  515. changed = true;
  516. }
  517. return changed;
  518. }
  519. bool relayStatus(unsigned char id, bool status) {
  520. #if MQTT_SUPPORT
  521. return relayStatus(id, status, mqttForward(), true);
  522. #else
  523. return relayStatus(id, status, false, true);
  524. #endif
  525. }
  526. bool relayStatus(unsigned char id) {
  527. // Check that relay ID is valid
  528. if (id >= _relays.size()) return false;
  529. // Get status directly from storage
  530. return _relays[id].current_status;
  531. }
  532. bool relayStatusTarget(unsigned char id) {
  533. if (id >= _relays.size()) return false;
  534. return _relays[id].target_status;
  535. }
  536. void relaySync(unsigned char id) {
  537. // No sync if none or only one relay
  538. if (_relays.size() < 2) return;
  539. // Do not go on if we are comming from a previous sync
  540. if (_relayRecursive) return;
  541. // Flag sync mode
  542. _relayRecursive = true;
  543. bool status = _relays[id].target_status;
  544. // If RELAY_SYNC_SAME all relays should have the same state
  545. if (_relay_sync_mode == RELAY_SYNC_SAME) {
  546. for (unsigned short i=0; i<_relays.size(); i++) {
  547. if (i != id) relayStatus(i, status);
  548. }
  549. // If RELAY_SYNC_FIRST all relays should have the same state as first if first changes
  550. } else if (_relay_sync_mode == RELAY_SYNC_FIRST) {
  551. if (id == 0) {
  552. for (unsigned short i=1; i<_relays.size(); i++) {
  553. relayStatus(i, status);
  554. }
  555. }
  556. } else if ((_relay_sync_mode == RELAY_SYNC_NONE_OR_ONE) || (_relay_sync_mode == RELAY_SYNC_ONE)) {
  557. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  558. if (status) {
  559. if (_relay_sync_mode != RELAY_SYNC_ANY) {
  560. for (unsigned short other_id=0; other_id<_relays.size(); other_id++) {
  561. if (other_id != id) {
  562. relayStatus(other_id, false);
  563. if (relayStatus(other_id)) {
  564. _relaySyncRelaysDelay(other_id, id);
  565. }
  566. }
  567. }
  568. }
  569. // If ONLY_ONE and setting OFF we should set ON the other one
  570. } else {
  571. if (_relay_sync_mode == RELAY_SYNC_ONE) {
  572. unsigned char other_id = (id + 1) % _relays.size();
  573. _relaySyncRelaysDelay(id, other_id);
  574. relayStatus(other_id, true);
  575. }
  576. }
  577. _relayLockAll();
  578. }
  579. // Unflag sync mode
  580. _relayRecursive = false;
  581. }
  582. void relaySave(bool eeprom) {
  583. const unsigned char count = constrain(relayCount(), 0, RelaysMax);
  584. auto statuses = std::bitset<RelaysMax>(0);
  585. for (unsigned int id = 0; id < count; ++id) {
  586. statuses.set(id, relayStatus(id));
  587. }
  588. const auto mask = _relayMask(statuses.to_ulong() & 0xffffffffu);
  589. DEBUG_MSG_P(PSTR("[RELAY] Setting relay mask: %s\n"), mask.as_string.c_str());
  590. // Persist only to rtcmem, unless requested to save to the eeprom
  591. _relayMaskRtcmem(mask);
  592. // The 'eeprom' flag controls whether we are commiting this change or not.
  593. // It is useful to set it to 'false' if the relay change triggering the
  594. // save involves a relay whose boot mode is independent from current mode,
  595. // thus storing the last relay value is not absolutely necessary.
  596. // Nevertheless, we store the value in the EEPROM buffer so it will be written
  597. // on the next commit.
  598. if (eeprom) {
  599. _relayMaskSettings(mask);
  600. // We are actually enqueuing the commit so it will be
  601. // executed on the main loop, in case this is called from a system context callback
  602. eepromCommit();
  603. }
  604. }
  605. void relaySave() {
  606. relaySave(false);
  607. }
  608. void relayToggle(unsigned char id, bool report, bool group_report) {
  609. if (id >= _relays.size()) return;
  610. relayStatus(id, !relayStatus(id), report, group_report);
  611. }
  612. void relayToggle(unsigned char id) {
  613. #if MQTT_SUPPORT
  614. relayToggle(id, mqttForward(), true);
  615. #else
  616. relayToggle(id, false, true);
  617. #endif
  618. }
  619. unsigned char relayCount() {
  620. return _relays.size();
  621. }
  622. PayloadStatus relayParsePayload(const char * payload) {
  623. #if MQTT_SUPPORT || API_SUPPORT
  624. return rpcParsePayload(payload, [](const char* payload) {
  625. if (_relay_rpc_payload_off.equals(payload)) return PayloadStatus::Off;
  626. if (_relay_rpc_payload_on.equals(payload)) return PayloadStatus::On;
  627. if (_relay_rpc_payload_toggle.equals(payload)) return PayloadStatus::Toggle;
  628. return PayloadStatus::Unknown;
  629. });
  630. #else
  631. return rpcParsePayload(payload);
  632. #endif
  633. }
  634. // BACKWARDS COMPATIBILITY
  635. void _relayBackwards() {
  636. for (unsigned char id = 0; id < _relays.size(); ++id) {
  637. const settings_key_t key {"mqttGroupInv", id};
  638. if (!hasSetting(key)) continue;
  639. setSetting({"mqttGroupSync", id}, getSetting(key));
  640. delSetting(key);
  641. }
  642. }
  643. void _relayBoot() {
  644. _relayRecursive = true;
  645. const auto stored_mask = rtcmemStatus()
  646. ? _relayMaskRtcmem()
  647. : _relayMaskSettings();
  648. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %s\n"), stored_mask.as_string.c_str());
  649. auto mask = std::bitset<RelaysMax>(stored_mask.as_u32);
  650. // Walk the relays
  651. unsigned char lock;
  652. bool status;
  653. for (unsigned char i=0; i<relayCount(); ++i) {
  654. const auto boot_mode = getSetting({"relayBoot", i}, RELAY_BOOT_MODE);
  655. DEBUG_MSG_P(PSTR("[RELAY] Relay #%u boot mode %d\n"), i, boot_mode);
  656. status = false;
  657. lock = RELAY_LOCK_DISABLED;
  658. switch (boot_mode) {
  659. case RELAY_BOOT_SAME:
  660. status = mask.test(i);
  661. break;
  662. case RELAY_BOOT_TOGGLE:
  663. mask.flip(i);
  664. status = mask[i];
  665. break;
  666. case RELAY_BOOT_LOCKED_ON:
  667. status = true;
  668. lock = RELAY_LOCK_ON;
  669. break;
  670. case RELAY_BOOT_LOCKED_OFF:
  671. lock = RELAY_LOCK_OFF;
  672. break;
  673. case RELAY_BOOT_ON:
  674. status = true;
  675. break;
  676. case RELAY_BOOT_OFF:
  677. default:
  678. break;
  679. }
  680. _relays[i].current_status = !status;
  681. _relays[i].target_status = status;
  682. _relays[i].change_start = millis();
  683. _relays[i].change_delay = status
  684. ? _relays[i].delay_on
  685. : _relays[i].delay_off;
  686. #if RELAY_PROVIDER == RELAY_PROVIDER_STM
  687. // XXX hack for correctly restoring relay state on boot
  688. // because of broken stm relay firmware
  689. _relays[i].change_delay = 3000 + 1000 * i;
  690. #endif
  691. _relays[i].lock = lock;
  692. }
  693. _relayRecursive = false;
  694. #if TUYA_SUPPORT
  695. Tuya::tuyaSyncSwitchStatus();
  696. #endif
  697. }
  698. void _relayConfigure() {
  699. for (unsigned char i = 0, relays = _relays.size() ; (i < relays); ++i) {
  700. _relays[i].pulse = getSetting({"relayPulse", i}, RELAY_PULSE_MODE);
  701. _relays[i].pulse_ms = 1000 * getSetting({"relayTime", i}, 0.);
  702. _relays[i].delay_on = getSetting({"relayDelayOn", i}, _relayDelayOn(i));
  703. _relays[i].delay_off = getSetting({"relayDelayOff", i}, _relayDelayOff(i));
  704. // make sure pin is valid before continuing with writes
  705. if (!static_cast<bool>(*_relays[i].pin)) continue;
  706. _relays[i].pin->pinMode(OUTPUT);
  707. if (static_cast<bool>(*_relays[i].reset_pin)) {
  708. _relays[i].reset_pin->pinMode(OUTPUT);
  709. }
  710. if (_relays[i].type == RELAY_TYPE_INVERSE) {
  711. //set to high to block short opening of relay
  712. _relays[i].pin->digitalWrite(HIGH);
  713. }
  714. }
  715. _relay_flood_window = (1000 * getSetting("relayFloodTime", RELAY_FLOOD_WINDOW));
  716. _relay_flood_changes = getSetting("relayFloodChanges", RELAY_FLOOD_CHANGES);
  717. _relay_delay_interlock = getSetting("relayDelayInterlock", RELAY_DELAY_INTERLOCK);
  718. _relay_sync_mode = getSetting("relaySync", RELAY_SYNC);
  719. #if MQTT_SUPPORT || API_SUPPORT
  720. settingsProcessConfig({
  721. {_relay_rpc_payload_on, "relayPayloadOn", RELAY_MQTT_ON},
  722. {_relay_rpc_payload_off, "relayPayloadOff", RELAY_MQTT_OFF},
  723. {_relay_rpc_payload_toggle, "relayPayloadToggle", RELAY_MQTT_TOGGLE},
  724. });
  725. #endif // MQTT_SUPPORT
  726. }
  727. //------------------------------------------------------------------------------
  728. // WEBSOCKETS
  729. //------------------------------------------------------------------------------
  730. #if WEB_SUPPORT
  731. bool _relayWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  732. return (strncmp(key, "relay", 5) == 0);
  733. }
  734. void _relayWebSocketUpdate(JsonObject& root) {
  735. JsonObject& state = root.createNestedObject("relayState");
  736. state["size"] = relayCount();
  737. JsonArray& status = state.createNestedArray("status");
  738. JsonArray& lock = state.createNestedArray("lock");
  739. // Note: we use byte instead of bool to ever so slightly compress json output
  740. for (unsigned char i=0; i<relayCount(); i++) {
  741. status.add<uint8_t>(_relays[i].target_status);
  742. lock.add(_relays[i].lock);
  743. }
  744. }
  745. String _relayFriendlyName(unsigned char i) {
  746. String res = String("GPIO") + String(_relays[i].pin->pin);
  747. if (GPIO_NONE == _relays[i].pin->pin) {
  748. #if (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  749. uint8_t physical = _relays.size() - _relayDummy;
  750. if (i >= physical) {
  751. if (_relayDummy == lightChannels()) {
  752. res = String("CH") + String(i-physical);
  753. } else if (_relayDummy == (lightChannels() + 1u)) {
  754. if (physical == i) {
  755. res = String("Light");
  756. } else {
  757. res = String("CH") + String(i-1-physical);
  758. }
  759. } else {
  760. res = String("Light");
  761. }
  762. } else {
  763. res = String("?");
  764. }
  765. #else
  766. res = String("SW") + String(i);
  767. #endif
  768. }
  769. return res;
  770. }
  771. void _relayWebSocketSendRelays(JsonObject& root) {
  772. JsonObject& relays = root.createNestedObject("relayConfig");
  773. relays["size"] = relayCount();
  774. relays["start"] = 0;
  775. JsonArray& gpio = relays.createNestedArray("gpio");
  776. JsonArray& type = relays.createNestedArray("type");
  777. JsonArray& reset = relays.createNestedArray("reset");
  778. JsonArray& boot = relays.createNestedArray("boot");
  779. JsonArray& pulse = relays.createNestedArray("pulse");
  780. JsonArray& pulse_time = relays.createNestedArray("pulse_time");
  781. #if SCHEDULER_SUPPORT
  782. JsonArray& sch_last = relays.createNestedArray("sch_last");
  783. #endif
  784. #if MQTT_SUPPORT
  785. JsonArray& group = relays.createNestedArray("group");
  786. JsonArray& group_sync = relays.createNestedArray("group_sync");
  787. JsonArray& on_disconnect = relays.createNestedArray("on_disc");
  788. #endif
  789. for (unsigned char i=0; i<relayCount(); i++) {
  790. gpio.add(_relayFriendlyName(i));
  791. type.add(_relays[i].type);
  792. reset.add(_relays[i].reset_pin->pin);
  793. boot.add(getSetting({"relayBoot", i}, RELAY_BOOT_MODE));
  794. pulse.add(_relays[i].pulse);
  795. pulse_time.add(_relays[i].pulse_ms / 1000.0);
  796. #if SCHEDULER_SUPPORT
  797. sch_last.add(getSetting({"relayLastSch", i}, SCHEDULER_RESTORE_LAST_SCHEDULE));
  798. #endif
  799. #if MQTT_SUPPORT
  800. group.add(getSetting({"mqttGroup", i}));
  801. group_sync.add(getSetting({"mqttGroupSync", i}, 0));
  802. on_disconnect.add(getSetting({"relayOnDisc", i}, 0));
  803. #endif
  804. }
  805. }
  806. void _relayWebSocketOnVisible(JsonObject& root) {
  807. if (relayCount() == 0) return;
  808. if (relayCount() > 1) {
  809. root["multirelayVisible"] = 1;
  810. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  811. }
  812. root["relayVisible"] = 1;
  813. }
  814. void _relayWebSocketOnConnected(JsonObject& root) {
  815. if (relayCount() == 0) return;
  816. // Per-relay configuration
  817. _relayWebSocketSendRelays(root);
  818. }
  819. void _relayWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  820. if (strcmp(action, "relay") != 0) return;
  821. if (data.containsKey("status")) {
  822. unsigned int relayID = 0;
  823. if (data.containsKey("id") && data.is<int>("id")) {
  824. relayID = data["id"];
  825. }
  826. _relayHandlePayload(relayID, data["status"].as<const char*>());
  827. }
  828. }
  829. void relaySetupWS() {
  830. wsRegister()
  831. .onVisible(_relayWebSocketOnVisible)
  832. .onConnected(_relayWebSocketOnConnected)
  833. .onData(_relayWebSocketUpdate)
  834. .onAction(_relayWebSocketOnAction)
  835. .onKeyCheck(_relayWebSocketOnKeyCheck);
  836. }
  837. #endif // WEB_SUPPORT
  838. //------------------------------------------------------------------------------
  839. // REST API
  840. //------------------------------------------------------------------------------
  841. #if API_SUPPORT
  842. template <typename T>
  843. bool _relayApiTryHandle(ApiRequest& request, T&& callback) {
  844. auto id_param = request.wildcard(0);
  845. unsigned char id;
  846. if (!_relayTryParseId(id_param.c_str(), id)) {
  847. return false;
  848. }
  849. return callback(id);
  850. }
  851. void relaySetupAPI() {
  852. apiRegister(F(MQTT_TOPIC_RELAY),
  853. [](ApiRequest&, JsonObject& root) {
  854. JsonArray& relays = root.createNestedArray("relayStatus");
  855. for (unsigned char id = 0; id < relayCount(); ++id) {
  856. relays.add(_relays[id].target_status ? 1 : 0);
  857. }
  858. return true;
  859. },
  860. nullptr
  861. );
  862. apiRegister(F(MQTT_TOPIC_RELAY "/+"),
  863. [](ApiRequest& request) {
  864. return _relayApiTryHandle(request, [&](unsigned char id) {
  865. request.send(String(_relays[id].target_status ? 1 : 0));
  866. return true;
  867. });
  868. },
  869. [](ApiRequest& request) {
  870. return _relayApiTryHandle(request, [&](unsigned char id) {
  871. return _relayHandlePayload(id, request.param(F("value")));
  872. });
  873. }
  874. );
  875. apiRegister(F(MQTT_TOPIC_PULSE "/+"),
  876. [](ApiRequest& request) {
  877. return _relayApiTryHandle(request, [&](unsigned char id) {
  878. request.send(String(static_cast<double>(_relays[id].pulse_ms) / 1000));
  879. return true;
  880. });
  881. },
  882. [](ApiRequest& request) {
  883. return _relayApiTryHandle(request, [&](unsigned char id) {
  884. return _relayHandlePulsePayload(id, request.param(F("value")));
  885. });
  886. }
  887. );
  888. #if defined(ITEAD_SONOFF_IFAN02)
  889. apiRegister(F(MQTT_TOPIC_SPEED), {
  890. [](ApiRequest& request) {
  891. request.send(String(static_cast<int>(getSpeed())));
  892. return true;
  893. },
  894. [](ApiRequest& request) {
  895. setSpeed(atoi(request.param(F("value"))));
  896. return true;
  897. },
  898. nullptr
  899. });
  900. #endif
  901. }
  902. #endif // API_SUPPORT
  903. //------------------------------------------------------------------------------
  904. // MQTT
  905. //------------------------------------------------------------------------------
  906. #if MQTT_SUPPORT || API_SUPPORT
  907. const String& relayPayloadOn() {
  908. return _relay_rpc_payload_on;
  909. }
  910. const String& relayPayloadOff() {
  911. return _relay_rpc_payload_off;
  912. }
  913. const String& relayPayloadToggle() {
  914. return _relay_rpc_payload_toggle;
  915. }
  916. const char* relayPayload(PayloadStatus status) {
  917. switch (status) {
  918. case PayloadStatus::Off:
  919. return _relay_rpc_payload_off.c_str();
  920. case PayloadStatus::On:
  921. return _relay_rpc_payload_on.c_str();
  922. case PayloadStatus::Toggle:
  923. return _relay_rpc_payload_toggle.c_str();
  924. case PayloadStatus::Unknown:
  925. default:
  926. return "";
  927. }
  928. }
  929. #endif // MQTT_SUPPORT || API_SUPPORT
  930. #if MQTT_SUPPORT
  931. void _relayMQTTGroup(unsigned char id) {
  932. const String topic = getSetting({"mqttGroup", id});
  933. if (!topic.length()) return;
  934. const auto mode = getSetting({"mqttGroupSync", id}, RELAY_GROUP_SYNC_NORMAL);
  935. if (mode == RELAY_GROUP_SYNC_RECEIVEONLY) return;
  936. auto status = _relayStatusTyped(id);
  937. if (mode == RELAY_GROUP_SYNC_INVERSE) status = _relayStatusInvert(status);
  938. mqttSendRaw(topic.c_str(), relayPayload(status));
  939. }
  940. void relayMQTT(unsigned char id) {
  941. if (id >= _relays.size()) return;
  942. // Send state topic
  943. if (_relays[id].report) {
  944. _relays[id].report = false;
  945. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  946. }
  947. // Check group topic
  948. if (_relays[id].group_report) {
  949. _relays[id].group_report = false;
  950. _relayMQTTGroup(id);
  951. }
  952. // Send speed for IFAN02
  953. #if defined (ITEAD_SONOFF_IFAN02)
  954. char buffer[5];
  955. snprintf(buffer, sizeof(buffer), "%u", getSpeed());
  956. mqttSend(MQTT_TOPIC_SPEED, buffer);
  957. #endif
  958. }
  959. void relayMQTT() {
  960. for (unsigned int id=0; id < _relays.size(); id++) {
  961. mqttSend(MQTT_TOPIC_RELAY, id, relayPayload(_relayStatusTyped(id)));
  962. }
  963. }
  964. void relayStatusWrap(unsigned char id, PayloadStatus value, bool is_group_topic) {
  965. #if MQTT_SUPPORT
  966. const auto forward = mqttForward();
  967. #else
  968. const auto forward = false;
  969. #endif
  970. switch (value) {
  971. case PayloadStatus::Off:
  972. relayStatus(id, false, forward, !is_group_topic);
  973. break;
  974. case PayloadStatus::On:
  975. relayStatus(id, true, forward, !is_group_topic);
  976. break;
  977. case PayloadStatus::Toggle:
  978. relayToggle(id, true, true);
  979. break;
  980. case PayloadStatus::Unknown:
  981. default:
  982. _relays[id].report = true;
  983. relayMQTT(id);
  984. break;
  985. }
  986. }
  987. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  988. if (type == MQTT_CONNECT_EVENT) {
  989. // Send status on connect
  990. #if (HEARTBEAT_MODE == HEARTBEAT_NONE) or (not HEARTBEAT_REPORT_RELAY)
  991. relayMQTT();
  992. #endif
  993. // Subscribe to own /set topic
  994. char relay_topic[strlen(MQTT_TOPIC_RELAY) + 3];
  995. snprintf_P(relay_topic, sizeof(relay_topic), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  996. mqttSubscribe(relay_topic);
  997. // Subscribe to pulse topic
  998. char pulse_topic[strlen(MQTT_TOPIC_PULSE) + 3];
  999. snprintf_P(pulse_topic, sizeof(pulse_topic), PSTR("%s/+"), MQTT_TOPIC_PULSE);
  1000. mqttSubscribe(pulse_topic);
  1001. #if defined(ITEAD_SONOFF_IFAN02)
  1002. mqttSubscribe(MQTT_TOPIC_SPEED);
  1003. #endif
  1004. // Subscribe to group topics
  1005. for (unsigned char i=0; i < _relays.size(); i++) {
  1006. const auto t = getSetting({"mqttGroup", i});
  1007. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  1008. }
  1009. }
  1010. if (type == MQTT_MESSAGE_EVENT) {
  1011. String t = mqttMagnitude((char *) topic);
  1012. unsigned char id;
  1013. if (!_relayTryParseIdFromPath(t.c_str(), id)) {
  1014. return;
  1015. }
  1016. if (t.startsWith(MQTT_TOPIC_PULSE)) {
  1017. _relayHandlePulsePayload(id, payload);
  1018. _relays[id].report = mqttForward();
  1019. return;
  1020. }
  1021. if (t.startsWith(MQTT_TOPIC_RELAY)) {
  1022. _relayHandlePayload(id, payload);
  1023. _relays[id].report = mqttForward();
  1024. return;
  1025. }
  1026. // TODO: cache group topics instead of reading settings each time?
  1027. // TODO: this is another kvs::foreach case, since we slow down MQTT when settings grow
  1028. for (unsigned char i=0; i < _relays.size(); i++) {
  1029. const String t = getSetting({"mqttGroup", i});
  1030. if (!t.length()) break;
  1031. if (t == topic) {
  1032. auto value = relayParsePayload(payload);
  1033. if (value == PayloadStatus::Unknown) return;
  1034. if ((value == PayloadStatus::On) || (value == PayloadStatus::Off)) {
  1035. if (getSetting({"mqttGroupSync", i}, RELAY_GROUP_SYNC_NORMAL) == RELAY_GROUP_SYNC_INVERSE) {
  1036. value = _relayStatusInvert(value);
  1037. }
  1038. }
  1039. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  1040. _relayHandleStatus(i, value);
  1041. _relays[i].group_report = false;
  1042. }
  1043. }
  1044. // Itead Sonoff IFAN02
  1045. #if defined (ITEAD_SONOFF_IFAN02)
  1046. if (t.startsWith(MQTT_TOPIC_SPEED)) {
  1047. setSpeed(atoi(payload));
  1048. }
  1049. #endif
  1050. }
  1051. // TODO: safeguard against network issues. this one has good intentions, but we may end up
  1052. // switching relays back and forth when connection is unstable but reconnects very fast after the failure
  1053. if (type == MQTT_DISCONNECT_EVENT) {
  1054. for (unsigned char i=0; i < _relays.size(); i++) {
  1055. const auto reaction = getSetting({"relayOnDisc", i}, 0);
  1056. bool status;
  1057. switch (reaction) {
  1058. case 1:
  1059. status = false;
  1060. break;
  1061. case 2:
  1062. status = true;
  1063. break;
  1064. default:
  1065. return;
  1066. }
  1067. DEBUG_MSG_P(PSTR("[RELAY] Turn %s relay #%u due to MQTT disconnection\n"), status ? "ON" : "OFF", i);
  1068. relayStatus(i, status);
  1069. }
  1070. }
  1071. }
  1072. void relaySetupMQTT() {
  1073. mqttRegister(relayMQTTCallback);
  1074. }
  1075. #endif
  1076. void _relaySetupProvider() {
  1077. // TODO: implement something like `RelayProvider tuya_provider({.setup_cb = ..., .send_cb = ...})`?
  1078. // note of the function call order! relay code is initialized before tuya's, and the easiest
  1079. // way to accomplish that is to use ctor as a way to "register" callbacks even before setup() is called
  1080. #if TUYA_SUPPORT
  1081. Tuya::tuyaSetupSwitch();
  1082. #endif
  1083. }
  1084. //------------------------------------------------------------------------------
  1085. // Settings
  1086. //------------------------------------------------------------------------------
  1087. #if TERMINAL_SUPPORT
  1088. void _relayInitCommands() {
  1089. terminalRegisterCommand(F("RELAY"), [](const terminal::CommandContext& ctx) {
  1090. if (ctx.argc < 2) {
  1091. terminalError(F("Wrong arguments"));
  1092. return;
  1093. }
  1094. int id = ctx.argv[1].toInt();
  1095. if (id >= relayCount()) {
  1096. DEBUG_MSG_P(PSTR("-ERROR: Wrong relayID (%d)\n"), id);
  1097. return;
  1098. }
  1099. if (ctx.argc > 2) {
  1100. int value = ctx.argv[2].toInt();
  1101. if (value == 2) {
  1102. relayToggle(id);
  1103. } else {
  1104. relayStatus(id, value == 1);
  1105. }
  1106. }
  1107. DEBUG_MSG_P(PSTR("Status: %s\n"), _relays[id].target_status ? "true" : "false");
  1108. if (_relays[id].pulse != RELAY_PULSE_NONE) {
  1109. DEBUG_MSG_P(PSTR("Pulse: %s\n"), (_relays[id].pulse == RELAY_PULSE_ON) ? "ON" : "OFF");
  1110. DEBUG_MSG_P(PSTR("Pulse time: %d\n"), _relays[id].pulse_ms);
  1111. }
  1112. terminalOK();
  1113. });
  1114. #if 0
  1115. terminalRegisterCommand(F("RELAY.INFO"), [](const terminal::CommandContext&) {
  1116. DEBUG_MSG_P(PSTR(" cur tgt pin type reset lock delay_on delay_off pulse pulse_ms\n"));
  1117. DEBUG_MSG_P(PSTR(" --- --- --- ---- ----- ---- ---------- ----------- ----- ----------\n"));
  1118. for (unsigned char index = 0; index < _relays.size(); ++index) {
  1119. const auto& relay = _relays.at(index);
  1120. DEBUG_MSG_P(PSTR("%3u %3s %3s %3u %4u %5u %4u %10u %11u %5u %10u\n"),
  1121. index,
  1122. relay.current_status ? "ON" : "OFF",
  1123. relay.target_status ? "ON" : "OFF",
  1124. relay.pin, relay.type, relay.reset_pin,
  1125. relay.lock,
  1126. relay.delay_on, relay.delay_off,
  1127. relay.pulse, relay.pulse_ms
  1128. );
  1129. }
  1130. });
  1131. #endif
  1132. }
  1133. #endif // TERMINAL_SUPPORT
  1134. //------------------------------------------------------------------------------
  1135. // Setup
  1136. //------------------------------------------------------------------------------
  1137. void _relayLoop() {
  1138. _relayProcess(false);
  1139. _relayProcess(true);
  1140. #if WEB_SUPPORT
  1141. if (_relay_report_ws) {
  1142. wsPost(_relayWebSocketUpdate);
  1143. _relay_report_ws = false;
  1144. }
  1145. #endif
  1146. }
  1147. // Dummy relays for virtual light switches, Sonoff Dual, Sonoff RF Bridge and Tuya
  1148. void relaySetupDummy(size_t size, bool reconfigure) {
  1149. if (size == _relayDummy) return;
  1150. const size_t new_size = ((_relays.size() - _relayDummy) + size);
  1151. if (new_size > RelaysMax) return;
  1152. _relayDummy = size;
  1153. _relays.resize(new_size);
  1154. if (reconfigure) {
  1155. _relayConfigure();
  1156. }
  1157. #if BROKER_SUPPORT
  1158. ConfigBroker::Publish("relayDummy", String(int(size)));
  1159. #endif
  1160. }
  1161. void _relaySetupAdhoc() {
  1162. size_t relays [[gnu::unused]] = 0;
  1163. #if RELAY1_PIN != GPIO_NONE
  1164. ++relays;
  1165. #endif
  1166. #if RELAY2_PIN != GPIO_NONE
  1167. ++relays;
  1168. #endif
  1169. #if RELAY3_PIN != GPIO_NONE
  1170. ++relays;
  1171. #endif
  1172. #if RELAY4_PIN != GPIO_NONE
  1173. ++relays;
  1174. #endif
  1175. #if RELAY5_PIN != GPIO_NONE
  1176. ++relays;
  1177. #endif
  1178. #if RELAY6_PIN != GPIO_NONE
  1179. ++relays;
  1180. #endif
  1181. #if RELAY7_PIN != GPIO_NONE
  1182. ++relays;
  1183. #endif
  1184. #if RELAY8_PIN != GPIO_NONE
  1185. ++relays;
  1186. #endif
  1187. _relays.reserve(relays);
  1188. #if (RELAY_PROVIDER == RELAY_PROVIDER_RELAY) || (RELAY_PROVIDER == RELAY_PROVIDER_LIGHT)
  1189. using gpio_type = GpioPin;
  1190. #elif (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  1191. using gpio_type = McpGpioPin;
  1192. #else
  1193. using gpio_type = DummyPin;
  1194. #endif
  1195. for (unsigned char id = 0; id < RelaysMax; ++id) {
  1196. const auto pin = _relayPin(id);
  1197. #if (RELAY_PROVIDER == RELAY_PROVIDER_MCP23S08)
  1198. if (!mcpGpioValid(pin)) {
  1199. #else
  1200. if (!gpioValid(pin)) {
  1201. #endif
  1202. break;
  1203. }
  1204. _relays.emplace_back(
  1205. new gpio_type(pin),
  1206. _relayType(id),
  1207. new gpio_type(_relayResetPin(id))
  1208. );
  1209. }
  1210. }
  1211. void relaySetup() {
  1212. // Ad-hoc relays
  1213. _relaySetupAdhoc();
  1214. // Dummy (virtual) relays
  1215. relaySetupDummy(getSetting("relayDummy", DUMMY_RELAY_COUNT));
  1216. _relaySetupProvider();
  1217. _relayBackwards();
  1218. _relayConfigure();
  1219. _relayBoot();
  1220. _relayLoop();
  1221. #if WEB_SUPPORT
  1222. relaySetupWS();
  1223. #endif
  1224. #if API_SUPPORT
  1225. relaySetupAPI();
  1226. #endif
  1227. #if MQTT_SUPPORT
  1228. relaySetupMQTT();
  1229. #endif
  1230. #if TERMINAL_SUPPORT
  1231. _relayInitCommands();
  1232. #endif
  1233. // Main callbacks
  1234. espurnaRegisterLoop(_relayLoop);
  1235. espurnaRegisterReload(_relayConfigure);
  1236. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  1237. }
  1238. #endif // RELAY_SUPPORT == 1