Mirror of espurna firmware for wireless switches and more
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.

3042 lines
89 KiB

3 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...)
3 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 years ago
webui: remove jquery dependencies and clean-up websocket API Refactor WebUI: - remove jquery dependency from the base custom.js and use vanilla JS - remove jquery + jquery-datatables dependency from the RFM69 module - replace jquery-datatables handlers with pure-css table + some basic cell filtering (may be incomplete, but tbh it is not worth additional 50Kb to the .bin size) - introduce a common way to notify about the app errors, show small text notification at the top of the page instead of relying on user to find out about errors by using the Web Developer Tools - replace <span name=...> with <span data-settings-key=...> - replace <div> templates with <template>, disallowing modification without an explicit DOM clone - run `eslint` on html/custom.js and `html-validate` on html/index.html, and fix issues detected by both tools Streamline settings group handling in custom.js & index.html - drop module-specific button-add-... in favour of button-add-settings-group - only enforce data-settings-max requirement when the property actually exists - re-create label for=... and input id=... when settings group is modified, so checkboxes refer to the correct element - introduce additional data-... properties to generalize settings group additions - introduce Enumerable object to track some common list elements for <select>, allow to re-create <option> list when messages come in different order Minor fixes that also came with this: - fix relay code incorrectly parsing the payload, causing no relay names to be displayed in the SWITCHES panel - fix scheduler code accidentally combining keys b/c of the way C parses string literals on separate lines, without any commas in-between - thermostat should not reference tmpUnit directly in the webui, replace with module-specific thermostatUnit that is handled on the device itself - fix index.html initial setup invalid adminPass ids - fix index.html layout when removing specific schedules
2 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...)
3 years ago
3 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...)
3 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...)
3 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...)
3 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...)
3 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...)
3 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...)
3 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
6 years ago
6 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
providers: relays, lights and buttons refactoring (#2414) - gpio module now tracks the known providers (right now, hardware and mcp expander) - refactored relay struct to use 'Provider' implementing setup,notify,change,boot instead of just BasePin actions - refactored button module to use gpio provider instead of referencing types itself - removed dual & stm code from buttons, migrate both to relay module - added status notify and change callbacks for relayStatus (i.e. 'notify' when relay status was called, but not changed. and 'changed' when it did) - relays runtime configuration keys - relay command now shows configured relays and current & target statuses - refactor the code using relayStatus(0, blah) under LIGHT_PROVIDER check to use lightState instead - remove rfbridge code form relay module. implement through a basic state listener in the rfbridge module, depend on RELAY_SUPPORT - allow to bind rf codes to real relays - drop tuya-specific lights provider, remove tuya code from relays and lights modules - integrate tuya via relay listeners and providers, use lights custom provider - implement channel transitions for tuya. disabled by default, and transition time and step are overridden to 2000 + 100. needs to be set to some value below the total time (i.e. `total transition time / step time == number of steps`, we need to figure out a correct time that serial comms could handle) - lights custom provider (global, not per-pin) and state listeners - remove lights code from relay module. implement through providers & listeners in the lights module, depend on RELAY_SUPPORT - lights per-channel relay provider (unused atm), depend on RELAY_SUPPORT - refactored channel transition - calculate step only once, make sure time + step values are sane, generate quick transitions with very small delay (10ms hardcoded) for transitions during OFF state i.e. we no longer waste 500ms (or whatever transition time is set to) on boot doing nothing - transition time + step parameter for the lightUpdate - report mask parameter for the lightUpdate - minor fixes across the board resolve #2222
3 years ago
6 years ago
5 years ago
5 years ago
6 years ago
6 years ago
  1. /*
  2. SENSOR MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. Copyright (C) 2020-2021 by Maxim Prokhorov <prokhorov dot max at outlook dot com>
  5. */
  6. #include "espurna.h"
  7. #if SENSOR_SUPPORT
  8. #include "sensor.h"
  9. #include "api.h"
  10. #include "domoticz.h"
  11. #include "i2c.h"
  12. #include "mqtt.h"
  13. #include "ntp.h"
  14. #include "relay.h"
  15. #include "terminal.h"
  16. #include "thingspeak.h"
  17. #include "rtcmem.h"
  18. #include "ws.h"
  19. #include <cfloat>
  20. #include <cmath>
  21. #include <limits>
  22. #include <vector>
  23. //--------------------------------------------------------------------------------
  24. namespace {
  25. #include "filters/LastFilter.h"
  26. #include "filters/MaxFilter.h"
  27. #include "filters/MedianFilter.h"
  28. #include "filters/MovingAverageFilter.h"
  29. #include "filters/SumFilter.h"
  30. } // namespace
  31. #include "sensors/BaseSensor.h"
  32. #include "sensors/BaseEmonSensor.h"
  33. #include "sensors/BaseAnalogEmonSensor.h"
  34. #include "sensors/BaseAnalogSensor.h"
  35. #if AM2320_SUPPORT
  36. #include "sensors/AM2320Sensor.h"
  37. #endif
  38. #if ANALOG_SUPPORT
  39. #include "sensors/AnalogSensor.h"
  40. #endif
  41. #if BH1750_SUPPORT
  42. #include "sensors/BH1750Sensor.h"
  43. #endif
  44. #if BMP180_SUPPORT
  45. #include "sensors/BMP180Sensor.h"
  46. #endif
  47. #if BMX280_SUPPORT
  48. #include "sensors/BMX280Sensor.h"
  49. #endif
  50. #if BME680_SUPPORT
  51. #include "sensors/BME680Sensor.h"
  52. #endif
  53. #if CSE7766_SUPPORT
  54. #include "sensors/CSE7766Sensor.h"
  55. #endif
  56. #if DALLAS_SUPPORT
  57. #include "sensors/DallasSensor.h"
  58. #endif
  59. #if DHT_SUPPORT
  60. #include "sensors/DHTSensor.h"
  61. #endif
  62. #if DIGITAL_SUPPORT
  63. #include "sensors/DigitalSensor.h"
  64. #endif
  65. #if ECH1560_SUPPORT
  66. #include "sensors/ECH1560Sensor.h"
  67. #endif
  68. #if EMON_ADC121_SUPPORT
  69. #include "sensors/EmonADC121Sensor.h"
  70. #endif
  71. #if EMON_ADS1X15_SUPPORT
  72. #include "sensors/EmonADS1X15Sensor.h"
  73. #endif
  74. #if EMON_ANALOG_SUPPORT
  75. #include "sensors/EmonAnalogSensor.h"
  76. #endif
  77. #if EVENTS_SUPPORT
  78. #include "sensors/EventSensor.h"
  79. #endif
  80. #if EZOPH_SUPPORT
  81. #include "sensors/EZOPHSensor.h"
  82. #endif
  83. #if GEIGER_SUPPORT
  84. #include "sensors/GeigerSensor.h"
  85. #endif
  86. #if GUVAS12SD_SUPPORT
  87. #include "sensors/GUVAS12SDSensor.h"
  88. #endif
  89. #if HLW8012_SUPPORT
  90. #include "sensors/HLW8012Sensor.h"
  91. #endif
  92. #if LDR_SUPPORT
  93. #include "sensors/LDRSensor.h"
  94. #endif
  95. #if MAX6675_SUPPORT
  96. #include "sensors/MAX6675Sensor.h"
  97. #endif
  98. #if MICS2710_SUPPORT
  99. #include "sensors/MICS2710Sensor.h"
  100. #endif
  101. #if MICS5525_SUPPORT
  102. #include "sensors/MICS5525Sensor.h"
  103. #endif
  104. #if MHZ19_SUPPORT
  105. #include "sensors/MHZ19Sensor.h"
  106. #endif
  107. #if NTC_SUPPORT
  108. #include "sensors/NTCSensor.h"
  109. #endif
  110. #if SDS011_SUPPORT
  111. #include "sensors/SDS011Sensor.h"
  112. #endif
  113. #if SENSEAIR_SUPPORT
  114. #include "sensors/SenseAirSensor.h"
  115. #endif
  116. #if PMSX003_SUPPORT
  117. #include "sensors/PMSX003Sensor.h"
  118. #endif
  119. #if PULSEMETER_SUPPORT
  120. #include "sensors/PulseMeterSensor.h"
  121. #endif
  122. #if PZEM004T_SUPPORT
  123. #include "sensors/PZEM004TSensor.h"
  124. #endif
  125. #if SHT3X_I2C_SUPPORT
  126. #include "sensors/SHT3XI2CSensor.h"
  127. #endif
  128. #if SI7021_SUPPORT
  129. #include "sensors/SI7021Sensor.h"
  130. #endif
  131. #if SM300D2_SUPPORT
  132. #include "sensors/SM300D2Sensor.h"
  133. #endif
  134. #if SONAR_SUPPORT
  135. #include "sensors/SonarSensor.h"
  136. #endif
  137. #if T6613_SUPPORT
  138. #include "sensors/T6613Sensor.h"
  139. #endif
  140. #if TMP3X_SUPPORT
  141. #include "sensors/TMP3XSensor.h"
  142. #endif
  143. #if V9261F_SUPPORT
  144. #include "sensors/V9261FSensor.h"
  145. #endif
  146. #if VEML6075_SUPPORT
  147. #include "sensors/VEML6075Sensor.h"
  148. #endif
  149. #if VL53L1X_SUPPORT
  150. #include "sensors/VL53L1XSensor.h"
  151. #endif
  152. #if ADE7953_SUPPORT
  153. #include "sensors/ADE7953Sensor.h"
  154. #endif
  155. #if SI1145_SUPPORT
  156. #include "sensors/SI1145Sensor.h"
  157. #endif
  158. #if HDC1080_SUPPORT
  159. #include "sensors/HDC1080Sensor.h"
  160. #endif
  161. #if PZEM004TV30_SUPPORT
  162. // TODO: this is temporary, until we have external API giving us swserial stream objects
  163. #include <SoftwareSerial.h>
  164. #include "sensors/PZEM004TV30Sensor.h"
  165. #endif
  166. //--------------------------------------------------------------------------------
  167. namespace {
  168. class sensor_magnitude_t {
  169. private:
  170. constexpr static double _unset = std::numeric_limits<double>::quiet_NaN();
  171. static unsigned char _counts[MAGNITUDE_MAX];
  172. sensor_magnitude_t& operator=(const sensor_magnitude_t&) = default;
  173. void move(sensor_magnitude_t&& other) noexcept {
  174. *this = other;
  175. other.filter = nullptr;
  176. }
  177. public:
  178. static unsigned char counts(unsigned char type) {
  179. return _counts[type];
  180. }
  181. sensor_magnitude_t() = delete;
  182. sensor_magnitude_t(const sensor_magnitude_t&) = delete;
  183. sensor_magnitude_t(sensor_magnitude_t&& other) noexcept {
  184. *this = other;
  185. other.filter = nullptr;
  186. }
  187. sensor_magnitude_t& operator=(sensor_magnitude_t&& other) noexcept {
  188. move(std::move(other));
  189. return *this;
  190. }
  191. ~sensor_magnitude_t() noexcept {
  192. delete filter;
  193. }
  194. sensor_magnitude_t(unsigned char slot, unsigned char index_local, unsigned char type, sensor::Unit units, BaseSensor* sensor);
  195. BaseSensor * sensor { nullptr }; // Sensor object
  196. BaseFilter * filter { nullptr }; // Filter object
  197. unsigned char slot { 0u }; // Sensor slot # taken by the magnitude, used to access the measurement
  198. unsigned char type { MAGNITUDE_NONE }; // Type of measurement, returned by the BaseSensor::type(slot)
  199. unsigned char index_local { 0u }; // N'th magnitude of it's type, local to the sensor
  200. unsigned char index_global { 0u }; // ... and across all of the active sensors
  201. sensor::Unit units { sensor::Unit::None }; // Units of measurement
  202. unsigned char decimals { 0u }; // Number of decimals in textual representation
  203. double last { _unset }; // Last raw value from sensor (unfiltered)
  204. double reported { _unset }; // Last reported value
  205. double min_change { 0.0 }; // Minimum value change to report
  206. double max_change { 0.0 }; // Maximum value change to report
  207. double correction { 0.0 }; // Value correction (applied when processing)
  208. double zero_threshold { _unset }; // Reset value to zero when below threshold (applied when reading)
  209. };
  210. static_assert(
  211. std::is_nothrow_move_constructible<sensor_magnitude_t>::value,
  212. "std::vector<sensor_magnitude_t> should be able to work with resize()"
  213. );
  214. static_assert(
  215. !std::is_copy_constructible<sensor_magnitude_t>::value,
  216. "std::vector<sensor_magnitude_t> should only use move ctor"
  217. );
  218. unsigned char sensor_magnitude_t::_counts[MAGNITUDE_MAX] = {0};
  219. } // namespace
  220. namespace sensor {
  221. // Base units
  222. // TODO: implement through a single class and allow direct access to the ::value
  223. KWh::KWh() :
  224. value(0)
  225. {}
  226. KWh::KWh(uint32_t value) :
  227. value(value)
  228. {}
  229. Ws::Ws() :
  230. value(0)
  231. {}
  232. Ws::Ws(uint32_t value) :
  233. value(value)
  234. {}
  235. // Generic storage. Most of the time we init this on boot with both members or start at 0 and increment with watt-second
  236. Energy::Energy(KWh kwh, Ws ws) :
  237. kwh(kwh)
  238. {
  239. *this += ws;
  240. }
  241. Energy::Energy(KWh kwh) :
  242. kwh(kwh),
  243. ws()
  244. {}
  245. Energy::Energy(Ws ws) :
  246. kwh()
  247. {
  248. *this += ws;
  249. }
  250. Energy::Energy(double raw) {
  251. *this = raw;
  252. }
  253. Energy& Energy::operator =(double raw) {
  254. double _wh;
  255. kwh = modf(raw, &_wh);
  256. ws = _wh * 3600.0;
  257. return *this;
  258. }
  259. Energy& Energy::operator +=(Ws _ws) {
  260. while (_ws.value >= KwhMultiplier) {
  261. _ws.value -= KwhMultiplier;
  262. ++kwh.value;
  263. }
  264. ws.value += _ws.value;
  265. while (ws.value >= KwhMultiplier) {
  266. ws.value -= KwhMultiplier;
  267. ++kwh.value;
  268. }
  269. return *this;
  270. }
  271. Energy Energy::operator +(Ws watt_s) {
  272. Energy result(*this);
  273. result += watt_s;
  274. return result;
  275. }
  276. Energy::operator bool() {
  277. return (kwh.value > 0) && (ws.value > 0);
  278. }
  279. Ws Energy::asWs() {
  280. auto _kwh = kwh.value;
  281. while (_kwh >= KwhLimit) {
  282. _kwh -= KwhLimit;
  283. }
  284. return (_kwh * KwhMultiplier) + ws.value;
  285. }
  286. double Energy::asDouble() {
  287. return (double)kwh.value + ((double)ws.value / (double)KwhMultiplier);
  288. }
  289. void Energy::reset() {
  290. kwh.value = 0;
  291. ws.value = 0;
  292. }
  293. } // namespace sensor
  294. namespace {
  295. // -----------------------------------------------------------------------------
  296. // Configuration
  297. // -----------------------------------------------------------------------------
  298. constexpr double _magnitudeCorrection(unsigned char type) {
  299. return (
  300. (MAGNITUDE_TEMPERATURE == type) ? (SENSOR_TEMPERATURE_CORRECTION) :
  301. (MAGNITUDE_HUMIDITY == type) ? (SENSOR_HUMIDITY_CORRECTION) :
  302. (MAGNITUDE_LUX == type) ? (SENSOR_LUX_CORRECTION) :
  303. (MAGNITUDE_PRESSURE == type) ? (SENSOR_PRESSURE_CORRECTION) :
  304. 0.0
  305. );
  306. }
  307. constexpr bool _magnitudeCanUseCorrection(unsigned char type) {
  308. return (
  309. (MAGNITUDE_TEMPERATURE == type) ? (true) :
  310. (MAGNITUDE_HUMIDITY == type) ? (true) :
  311. (MAGNITUDE_LUX == type) ? (true) :
  312. (MAGNITUDE_PRESSURE == type) ? (true) :
  313. false
  314. );
  315. }
  316. } // namespace
  317. // -----------------------------------------------------------------------------
  318. // Energy persistence
  319. // -----------------------------------------------------------------------------
  320. namespace {
  321. std::vector<unsigned char> _sensor_save_count;
  322. unsigned char _sensor_save_every = SENSOR_SAVE_EVERY;
  323. bool _sensorIsEmon(BaseSensor* sensor) {
  324. return sensor->type() & (sensor::type::Emon | sensor::type::AnalogEmon);
  325. }
  326. bool _sensorIsAnalogEmon(BaseSensor* sensor) {
  327. return sensor->type() & sensor::type::AnalogEmon;
  328. }
  329. sensor::Energy _sensorRtcmemLoadEnergy(unsigned char index) {
  330. return sensor::Energy {
  331. sensor::KWh { Rtcmem->energy[index].kwh },
  332. sensor::Ws { Rtcmem->energy[index].ws }
  333. };
  334. }
  335. void _sensorRtcmemSaveEnergy(unsigned char index, const sensor::Energy& source) {
  336. Rtcmem->energy[index].kwh = source.kwh.value;
  337. Rtcmem->energy[index].ws = source.ws.value;
  338. }
  339. sensor::Energy _sensorParseEnergy(const String& value) {
  340. sensor::Energy result;
  341. if (!value.length()) {
  342. return result;
  343. }
  344. const char* p { value.c_str() };
  345. char* endp { nullptr };
  346. auto kwh = strtoul(p, &endp, 10);
  347. if (!endp || (endp == p)) {
  348. return result;
  349. }
  350. result.kwh = kwh;
  351. const char* plus { strchr(p, '+') };
  352. if (!plus) {
  353. return result;
  354. }
  355. p = plus + 1;
  356. if (*p == '\0') {
  357. return result;
  358. }
  359. auto ws = strtoul(p, &endp, 10);
  360. if (!endp || (endp == p)) {
  361. return result;
  362. }
  363. result.ws = ws;
  364. return result;
  365. }
  366. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const char* payload) {
  367. if (!payload || !strlen(payload)) return;
  368. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  369. auto energy = _sensorParseEnergy(payload);
  370. sensor->resetEnergy(magnitude.index_local, energy);
  371. }
  372. void _sensorApiResetEnergy(const sensor_magnitude_t& magnitude, const String& payload) {
  373. _sensorApiResetEnergy(magnitude, payload.c_str());
  374. }
  375. sensor::Energy _sensorEnergyTotal(unsigned char index) {
  376. sensor::Energy result;
  377. if (rtcmemStatus() && (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy)))) {
  378. result = _sensorRtcmemLoadEnergy(index);
  379. } else {
  380. result = _sensorParseEnergy(getSetting({"eneTotal", index}));
  381. }
  382. return result;
  383. }
  384. void _sensorResetEnergyTotal(unsigned char index) {
  385. delSetting({"eneTotal", index});
  386. delSetting({"eneTime", index});
  387. if (index < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  388. Rtcmem->energy[index].kwh = 0;
  389. Rtcmem->energy[index].ws = 0;
  390. }
  391. }
  392. void _magnitudeSaveEnergyTotal(sensor_magnitude_t& magnitude, bool persistent) {
  393. if (magnitude.type != MAGNITUDE_ENERGY) return;
  394. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  395. const auto energy = sensor->totalEnergy();
  396. // Always save to RTCMEM
  397. if (magnitude.index_global < (sizeof(Rtcmem->energy) / sizeof(*Rtcmem->energy))) {
  398. _sensorRtcmemSaveEnergy(magnitude.index_global, energy);
  399. }
  400. // Save to EEPROM every '_sensor_save_every' readings
  401. // Format is `<kwh>+<ws>`, value without `+` is treated as `<ws>`
  402. if (persistent && _sensor_save_every) {
  403. _sensor_save_count[magnitude.index_global] =
  404. (_sensor_save_count[magnitude.index_global] + 1) % _sensor_save_every;
  405. if (0 == _sensor_save_count[magnitude.index_global]) {
  406. const String total = String(energy.kwh.value) + "+" + String(energy.ws.value);
  407. setSetting({"eneTotal", magnitude.index_global}, total);
  408. #if NTP_SUPPORT
  409. if (ntpSynced()) setSetting({"eneTime", magnitude.index_global}, ntpDateTime());
  410. #endif
  411. }
  412. }
  413. }
  414. } // namespace
  415. sensor::Energy sensorEnergyTotal() {
  416. return _sensorEnergyTotal(0);
  417. }
  418. // -----------------------------------------------------------------------------
  419. // Data processing
  420. // -----------------------------------------------------------------------------
  421. namespace {
  422. std::vector<BaseSensor *> _sensors;
  423. std::vector<sensor_magnitude_t> _magnitudes;
  424. bool _sensors_ready = false;
  425. bool _sensor_realtime = API_REAL_TIME_VALUES;
  426. unsigned long _sensor_read_interval = 1000 * SENSOR_READ_INTERVAL;
  427. unsigned char _sensor_report_every = SENSOR_REPORT_EVERY;
  428. using MagnitudeReadHandlers = std::forward_list<MagnitudeReadHandler>;
  429. MagnitudeReadHandlers _magnitude_read_handlers;
  430. MagnitudeReadHandlers _magnitude_report_handlers;
  431. BaseFilter* _magnitudeCreateFilter(unsigned char type, size_t size) {
  432. BaseFilter* filter { nullptr };
  433. switch (type) {
  434. case MAGNITUDE_IAQ:
  435. case MAGNITUDE_IAQ_STATIC:
  436. case MAGNITUDE_ENERGY:
  437. filter = new LastFilter();
  438. break;
  439. case MAGNITUDE_COUNT:
  440. case MAGNITUDE_GEIGER_CPM:
  441. case MAGNITUDE_GEIGER_SIEVERT:
  442. case MAGNITUDE_ENERGY_DELTA:
  443. filter = new SumFilter();
  444. break;
  445. case MAGNITUDE_EVENT:
  446. case MAGNITUDE_DIGITAL:
  447. filter = new MaxFilter();
  448. break;
  449. default:
  450. filter = new MedianFilter();
  451. break;
  452. }
  453. filter->resize(size);
  454. return filter;
  455. }
  456. sensor_magnitude_t::sensor_magnitude_t(unsigned char slot_, unsigned char index_local_, unsigned char type_, sensor::Unit units_, BaseSensor* sensor_) :
  457. sensor(sensor_),
  458. filter(_magnitudeCreateFilter(type_, _sensor_report_every)),
  459. slot(slot_),
  460. type(type_),
  461. index_local(index_local_),
  462. index_global(_counts[type]),
  463. units(units_)
  464. {
  465. ++_counts[type];
  466. }
  467. // Hardcoded decimals for each magnitude
  468. unsigned char _sensorUnitDecimals(sensor::Unit unit) {
  469. switch (unit) {
  470. case sensor::Unit::Celcius:
  471. case sensor::Unit::Farenheit:
  472. return 1;
  473. case sensor::Unit::Percentage:
  474. return 0;
  475. case sensor::Unit::Hectopascal:
  476. return 2;
  477. case sensor::Unit::Ampere:
  478. return 3;
  479. case sensor::Unit::Volt:
  480. return 0;
  481. case sensor::Unit::Watt:
  482. case sensor::Unit::Voltampere:
  483. case sensor::Unit::VoltampereReactive:
  484. return 0;
  485. case sensor::Unit::Kilowatt:
  486. case sensor::Unit::Kilovoltampere:
  487. case sensor::Unit::KilovoltampereReactive:
  488. return 3;
  489. case sensor::Unit::KilowattHour:
  490. return 3;
  491. case sensor::Unit::WattSecond:
  492. return 0;
  493. case sensor::Unit::CountsPerMinute:
  494. case sensor::Unit::MicrosievertPerHour:
  495. return 4;
  496. case sensor::Unit::Meter:
  497. return 3;
  498. case sensor::Unit::Hertz:
  499. return 1;
  500. case sensor::Unit::UltravioletIndex:
  501. return 3;
  502. case sensor::Unit::Ph:
  503. return 3;
  504. case sensor::Unit::None:
  505. default:
  506. return 0;
  507. }
  508. }
  509. String _magnitudeTopic(unsigned char type) {
  510. const __FlashStringHelper* result = nullptr;
  511. switch (type) {
  512. case MAGNITUDE_TEMPERATURE:
  513. result = F("temperature");
  514. break;
  515. case MAGNITUDE_HUMIDITY:
  516. result = F("humidity");
  517. break;
  518. case MAGNITUDE_PRESSURE:
  519. result = F("pressure");
  520. break;
  521. case MAGNITUDE_CURRENT:
  522. result = F("current");
  523. break;
  524. case MAGNITUDE_VOLTAGE:
  525. result = F("voltage");
  526. break;
  527. case MAGNITUDE_POWER_ACTIVE:
  528. result = F("power");
  529. break;
  530. case MAGNITUDE_POWER_APPARENT:
  531. result = F("apparent");
  532. break;
  533. case MAGNITUDE_POWER_REACTIVE:
  534. result = F("reactive");
  535. break;
  536. case MAGNITUDE_POWER_FACTOR:
  537. result = F("factor");
  538. break;
  539. case MAGNITUDE_ENERGY:
  540. result = F("energy");
  541. break;
  542. case MAGNITUDE_ENERGY_DELTA:
  543. result = F("energy_delta");
  544. break;
  545. case MAGNITUDE_ANALOG:
  546. result = F("analog");
  547. break;
  548. case MAGNITUDE_DIGITAL:
  549. result = F("digital");
  550. break;
  551. case MAGNITUDE_EVENT:
  552. result = F("event");
  553. break;
  554. case MAGNITUDE_PM1dot0:
  555. result = F("pm1dot0");
  556. break;
  557. case MAGNITUDE_PM2dot5:
  558. result = F("pm2dot5");
  559. break;
  560. case MAGNITUDE_PM10:
  561. result = F("pm10");
  562. break;
  563. case MAGNITUDE_CO2:
  564. result = F("co2");
  565. break;
  566. case MAGNITUDE_VOC:
  567. result = F("voc");
  568. break;
  569. case MAGNITUDE_IAQ:
  570. result = F("iaq");
  571. break;
  572. case MAGNITUDE_IAQ_ACCURACY:
  573. result = F("iaq_accuracy");
  574. break;
  575. case MAGNITUDE_IAQ_STATIC:
  576. result = F("iaq_static");
  577. break;
  578. case MAGNITUDE_LUX:
  579. result = F("lux");
  580. break;
  581. case MAGNITUDE_UVA:
  582. result = F("uva");
  583. break;
  584. case MAGNITUDE_UVB:
  585. result = F("uvb");
  586. break;
  587. case MAGNITUDE_UVI:
  588. result = F("uvi");
  589. break;
  590. case MAGNITUDE_DISTANCE:
  591. result = F("distance");
  592. break;
  593. case MAGNITUDE_HCHO:
  594. result = F("hcho");
  595. break;
  596. case MAGNITUDE_GEIGER_CPM:
  597. result = F("ldr_cpm"); // local dose rate [Counts per minute]
  598. break;
  599. case MAGNITUDE_GEIGER_SIEVERT:
  600. result = F("ldr_uSvh"); // local dose rate [µSievert per hour]
  601. break;
  602. case MAGNITUDE_COUNT:
  603. result = F("count");
  604. break;
  605. case MAGNITUDE_NO2:
  606. result = F("no2");
  607. break;
  608. case MAGNITUDE_CO:
  609. result = F("co");
  610. break;
  611. case MAGNITUDE_RESISTANCE:
  612. result = F("resistance");
  613. break;
  614. case MAGNITUDE_PH:
  615. result = F("ph");
  616. break;
  617. case MAGNITUDE_FREQUENCY:
  618. result = F("frequency");
  619. break;
  620. case MAGNITUDE_TVOC:
  621. result = F("tvoc");
  622. break;
  623. case MAGNITUDE_CH2O:
  624. result = F("ch2o");
  625. break;
  626. case MAGNITUDE_NONE:
  627. default:
  628. result = F("unknown");
  629. break;
  630. }
  631. return String(result);
  632. }
  633. String _magnitudeUnits(const sensor_magnitude_t& magnitude) {
  634. const __FlashStringHelper* result = nullptr;
  635. switch (magnitude.units) {
  636. case sensor::Unit::Farenheit:
  637. result = F("°F");
  638. break;
  639. case sensor::Unit::Celcius:
  640. result = F("°C");
  641. break;
  642. case sensor::Unit::Percentage:
  643. result = F("%");
  644. break;
  645. case sensor::Unit::Hectopascal:
  646. result = F("hPa");
  647. break;
  648. case sensor::Unit::Ampere:
  649. result = F("A");
  650. break;
  651. case sensor::Unit::Volt:
  652. result = F("V");
  653. break;
  654. case sensor::Unit::Watt:
  655. result = F("W");
  656. break;
  657. case sensor::Unit::Kilowatt:
  658. result = F("kW");
  659. break;
  660. case sensor::Unit::Voltampere:
  661. result = F("VA");
  662. break;
  663. case sensor::Unit::Kilovoltampere:
  664. result = F("kVA");
  665. break;
  666. case sensor::Unit::VoltampereReactive:
  667. result = F("VAR");
  668. break;
  669. case sensor::Unit::KilovoltampereReactive:
  670. result = F("kVAR");
  671. break;
  672. case sensor::Unit::Joule:
  673. //aka case sensor::Unit::WattSecond:
  674. result = F("J");
  675. break;
  676. case sensor::Unit::KilowattHour:
  677. result = F("kWh");
  678. break;
  679. case sensor::Unit::MicrogrammPerCubicMeter:
  680. result = F("µg/m³");
  681. break;
  682. case sensor::Unit::PartsPerMillion:
  683. result = F("ppm");
  684. break;
  685. case sensor::Unit::Lux:
  686. result = F("lux");
  687. break;
  688. case sensor::Unit::Ohm:
  689. result = F("ohm");
  690. break;
  691. case sensor::Unit::MilligrammPerCubicMeter:
  692. result = F("mg/m³");
  693. break;
  694. case sensor::Unit::CountsPerMinute:
  695. result = F("cpm");
  696. break;
  697. case sensor::Unit::MicrosievertPerHour:
  698. result = F("µSv/h");
  699. break;
  700. case sensor::Unit::Meter:
  701. result = F("m");
  702. break;
  703. case sensor::Unit::Hertz:
  704. result = F("Hz");
  705. break;
  706. case sensor::Unit::None:
  707. default:
  708. result = F("");
  709. break;
  710. }
  711. return String(result);
  712. }
  713. } // namespace
  714. String magnitudeUnits(unsigned char index) {
  715. if (index >= magnitudeCount()) return String();
  716. return _magnitudeUnits(_magnitudes[index]);
  717. }
  718. namespace {
  719. // Choose unit based on type of magnitude we use
  720. sensor::Unit _magnitudeUnitFilter(const sensor_magnitude_t& magnitude, sensor::Unit updated) {
  721. auto result = magnitude.units;
  722. switch (magnitude.type) {
  723. case MAGNITUDE_TEMPERATURE: {
  724. switch (updated) {
  725. case sensor::Unit::Celcius:
  726. case sensor::Unit::Farenheit:
  727. case sensor::Unit::Kelvin:
  728. result = updated;
  729. break;
  730. default:
  731. break;
  732. }
  733. break;
  734. }
  735. case MAGNITUDE_POWER_ACTIVE: {
  736. switch (updated) {
  737. case sensor::Unit::Kilowatt:
  738. case sensor::Unit::Watt:
  739. result = updated;
  740. break;
  741. default:
  742. break;
  743. }
  744. break;
  745. }
  746. case MAGNITUDE_ENERGY: {
  747. switch (updated) {
  748. case sensor::Unit::KilowattHour:
  749. case sensor::Unit::Joule:
  750. result = updated;
  751. break;
  752. default:
  753. break;
  754. }
  755. break;
  756. }
  757. default:
  758. result = updated;
  759. break;
  760. }
  761. return result;
  762. };
  763. double _magnitudeProcess(const sensor_magnitude_t& magnitude, double value) {
  764. // Process input (sensor) units and convert to the ones that magnitude specifies as output
  765. switch (magnitude.sensor->units(magnitude.slot)) {
  766. case sensor::Unit::Celcius:
  767. if (magnitude.units == sensor::Unit::Farenheit) {
  768. value = (value * 1.8) + 32.0;
  769. } else if (magnitude.units == sensor::Unit::Kelvin) {
  770. value = value + 273.15;
  771. }
  772. break;
  773. case sensor::Unit::Percentage:
  774. value = constrain(value, 0.0, 100.0);
  775. break;
  776. case sensor::Unit::Watt:
  777. case sensor::Unit::Voltampere:
  778. case sensor::Unit::VoltampereReactive:
  779. if ((magnitude.units == sensor::Unit::Kilowatt)
  780. || (magnitude.units == sensor::Unit::Kilovoltampere)
  781. || (magnitude.units == sensor::Unit::KilovoltampereReactive)) {
  782. value = value / 1.0e+3;
  783. }
  784. break;
  785. case sensor::Unit::KilowattHour:
  786. // TODO: we may end up with inf at some point?
  787. if (magnitude.units == sensor::Unit::Joule) {
  788. value = value * 3.6e+6;
  789. }
  790. break;
  791. default:
  792. break;
  793. }
  794. value = value + magnitude.correction;
  795. return roundTo(value, magnitude.decimals);
  796. }
  797. String _magnitudeDescription(const sensor_magnitude_t& magnitude) {
  798. return magnitude.sensor->description(magnitude.slot);
  799. }
  800. // -----------------------------------------------------------------------------
  801. // do `callback(type)` for each present magnitude
  802. template<typename T>
  803. void _magnitudeForEachCounted(T callback) {
  804. for (unsigned char type = MAGNITUDE_NONE + 1; type < MAGNITUDE_MAX; ++type) {
  805. if (sensor_magnitude_t::counts(type)) {
  806. callback(type);
  807. }
  808. }
  809. }
  810. // check if `callback(type)` returns `true` at least once
  811. template<typename T>
  812. bool _magnitudeForEachCountedCheck(T callback) {
  813. for (unsigned char type = MAGNITUDE_NONE + 1; type < MAGNITUDE_MAX; ++type) {
  814. if (sensor_magnitude_t::counts(type) && callback(type)) {
  815. return true;
  816. }
  817. }
  818. return false;
  819. }
  820. // do `callback(type)` for each error type
  821. template<typename T>
  822. void _sensorForEachError(T callback) {
  823. for (unsigned char error = SENSOR_ERROR_OK; error < SENSOR_ERROR_MAX; ++error) {
  824. callback(error);
  825. }
  826. }
  827. const char * const _magnitudeSettingsPrefix(unsigned char type) {
  828. switch (type) {
  829. case MAGNITUDE_TEMPERATURE: return "tmp";
  830. case MAGNITUDE_HUMIDITY: return "hum";
  831. case MAGNITUDE_PRESSURE: return "press";
  832. case MAGNITUDE_CURRENT: return "curr";
  833. case MAGNITUDE_VOLTAGE: return "volt";
  834. case MAGNITUDE_POWER_ACTIVE: return "pwrP";
  835. case MAGNITUDE_POWER_APPARENT: return "pwrQ";
  836. case MAGNITUDE_POWER_REACTIVE: return "pwrModS";
  837. case MAGNITUDE_POWER_FACTOR: return "pwrPF";
  838. case MAGNITUDE_ENERGY: return "ene";
  839. case MAGNITUDE_ENERGY_DELTA: return "eneDelta";
  840. case MAGNITUDE_ANALOG: return "analog";
  841. case MAGNITUDE_DIGITAL: return "digital";
  842. case MAGNITUDE_EVENT: return "event";
  843. case MAGNITUDE_PM1dot0: return "pm1dot0";
  844. case MAGNITUDE_PM2dot5: return "pm1dot5";
  845. case MAGNITUDE_PM10: return "pm10";
  846. case MAGNITUDE_CO2: return "co2";
  847. case MAGNITUDE_VOC: return "voc";
  848. case MAGNITUDE_IAQ: return "iaq";
  849. case MAGNITUDE_IAQ_ACCURACY: return "iaqAccuracy";
  850. case MAGNITUDE_IAQ_STATIC: return "iaqStatic";
  851. case MAGNITUDE_LUX: return "lux";
  852. case MAGNITUDE_UVA: return "uva";
  853. case MAGNITUDE_UVB: return "uvb";
  854. case MAGNITUDE_UVI: return "uvi";
  855. case MAGNITUDE_DISTANCE: return "distance";
  856. case MAGNITUDE_HCHO: return "hcho";
  857. case MAGNITUDE_GEIGER_CPM: return "gcpm";
  858. case MAGNITUDE_GEIGER_SIEVERT: return "gsiev";
  859. case MAGNITUDE_COUNT: return "count";
  860. case MAGNITUDE_NO2: return "no2";
  861. case MAGNITUDE_CO: return "co";
  862. case MAGNITUDE_RESISTANCE: return "res";
  863. case MAGNITUDE_PH: return "ph";
  864. case MAGNITUDE_FREQUENCY: return "freq";
  865. case MAGNITUDE_TVOC: return "tvoc";
  866. case MAGNITUDE_CH2O: return "ch2o";
  867. default: return nullptr;
  868. }
  869. }
  870. template <typename T>
  871. String _magnitudeSettingsKey(unsigned char type, T&& suffix) {
  872. return String(_magnitudeSettingsPrefix(type)) + suffix;
  873. }
  874. template <typename T>
  875. String _magnitudeSettingsKey(sensor_magnitude_t& magnitude, T&& suffix) {
  876. return _magnitudeSettingsKey(magnitude.type, std::forward<T>(suffix));
  877. }
  878. bool _sensorMatchKeyPrefix(const char * key) {
  879. if (strncmp(key, "sns", 3) == 0) return true;
  880. if (strncmp(key, "pwr", 3) == 0) return true;
  881. return _magnitudeForEachCountedCheck([key](unsigned char type) {
  882. const char* const prefix { _magnitudeSettingsPrefix(type) };
  883. return (strncmp(prefix, key, strlen(prefix)) == 0);
  884. });
  885. }
  886. SettingsKey _magnitudeSettingsRatioKey(unsigned char type, size_t index) {
  887. return {_magnitudeSettingsKey(type, F("Ratio")), index};
  888. }
  889. SettingsKey _magnitudeSettingsRatioKey(const sensor_magnitude_t& magnitude) {
  890. return _magnitudeSettingsRatioKey(magnitude.type, magnitude.index_global);
  891. }
  892. double _magnitudeSettingsRatio(const sensor_magnitude_t& magnitude, double defaultValue) {
  893. return getSetting(_magnitudeSettingsRatioKey(magnitude), defaultValue);
  894. };
  895. String _sensorQueryDefault(const String& key) {
  896. auto get_defaults = [](unsigned char type, BaseSensor* ptr) -> String {
  897. if (!ptr) return String();
  898. auto* sensor = static_cast<BaseEmonSensor*>(ptr);
  899. switch (type) {
  900. case MAGNITUDE_CURRENT:
  901. return String(sensor->defaultCurrentRatio());
  902. case MAGNITUDE_VOLTAGE:
  903. return String(sensor->defaultVoltageRatio());
  904. case MAGNITUDE_POWER_ACTIVE:
  905. return String(sensor->defaultPowerRatio());
  906. case MAGNITUDE_ENERGY:
  907. return String(sensor->defaultEnergyRatio());
  908. default:
  909. return String();
  910. }
  911. };
  912. auto magnitude_key = [](const sensor_magnitude_t& magnitude) -> SettingsKey {
  913. switch (magnitude.type) {
  914. case MAGNITUDE_CURRENT:
  915. case MAGNITUDE_VOLTAGE:
  916. case MAGNITUDE_POWER_ACTIVE:
  917. case MAGNITUDE_ENERGY:
  918. return _magnitudeSettingsRatioKey(magnitude);
  919. }
  920. return "";
  921. };
  922. unsigned char type = MAGNITUDE_NONE;
  923. BaseSensor* target = nullptr;
  924. for (auto& magnitude : _magnitudes) {
  925. switch (magnitude.type) {
  926. case MAGNITUDE_CURRENT:
  927. case MAGNITUDE_VOLTAGE:
  928. case MAGNITUDE_POWER_ACTIVE:
  929. case MAGNITUDE_ENERGY: {
  930. auto ratioKey(magnitude_key(magnitude));
  931. if (ratioKey == key) {
  932. target = magnitude.sensor;
  933. type = magnitude.type;
  934. goto return_defaults;
  935. }
  936. break;
  937. }
  938. default:
  939. break;
  940. }
  941. }
  942. return_defaults:
  943. return get_defaults(type, target);
  944. }
  945. } // namespace
  946. #if WEB_SUPPORT
  947. namespace {
  948. bool _sensorWebSocketOnKeyCheck(const char* key, JsonVariant&) {
  949. return _sensorMatchKeyPrefix(key);
  950. }
  951. String _sensorError(unsigned char error) {
  952. const __FlashStringHelper* result = nullptr;
  953. switch (error) {
  954. case SENSOR_ERROR_OK:
  955. result = F("OK");
  956. break;
  957. case SENSOR_ERROR_OUT_OF_RANGE:
  958. result = F("Out of Range");
  959. break;
  960. case SENSOR_ERROR_WARM_UP:
  961. result = F("Warming Up");
  962. break;
  963. case SENSOR_ERROR_TIMEOUT:
  964. result = F("Timeout");
  965. break;
  966. case SENSOR_ERROR_UNKNOWN_ID:
  967. result = F("Unknown ID");
  968. break;
  969. case SENSOR_ERROR_CRC:
  970. result = F("CRC / Data Error");
  971. break;
  972. case SENSOR_ERROR_I2C:
  973. result = F("I2C Error");
  974. break;
  975. case SENSOR_ERROR_GPIO_USED:
  976. result = F("GPIO Already Used");
  977. break;
  978. case SENSOR_ERROR_CALIBRATION:
  979. result = F("Calibration Error");
  980. break;
  981. default:
  982. case SENSOR_ERROR_OTHER:
  983. result = F("Other / Unknown Error");
  984. break;
  985. }
  986. return result;
  987. }
  988. String _magnitudeName(unsigned char type) {
  989. const __FlashStringHelper* result = nullptr;
  990. switch (type) {
  991. case MAGNITUDE_TEMPERATURE:
  992. result = F("Temperature");
  993. break;
  994. case MAGNITUDE_HUMIDITY:
  995. result = F("Humidity");
  996. break;
  997. case MAGNITUDE_PRESSURE:
  998. result = F("Pressure");
  999. break;
  1000. case MAGNITUDE_CURRENT:
  1001. result = F("Current");
  1002. break;
  1003. case MAGNITUDE_VOLTAGE:
  1004. result = F("Voltage");
  1005. break;
  1006. case MAGNITUDE_POWER_ACTIVE:
  1007. result = F("Active Power");
  1008. break;
  1009. case MAGNITUDE_POWER_APPARENT:
  1010. result = F("Apparent Power");
  1011. break;
  1012. case MAGNITUDE_POWER_REACTIVE:
  1013. result = F("Reactive Power");
  1014. break;
  1015. case MAGNITUDE_POWER_FACTOR:
  1016. result = F("Power Factor");
  1017. break;
  1018. case MAGNITUDE_ENERGY:
  1019. result = F("Energy");
  1020. break;
  1021. case MAGNITUDE_ENERGY_DELTA:
  1022. result = F("Energy (delta)");
  1023. break;
  1024. case MAGNITUDE_ANALOG:
  1025. result = F("Analog");
  1026. break;
  1027. case MAGNITUDE_DIGITAL:
  1028. result = F("Digital");
  1029. break;
  1030. case MAGNITUDE_EVENT:
  1031. result = F("Event");
  1032. break;
  1033. case MAGNITUDE_PM1dot0:
  1034. result = F("PM1.0");
  1035. break;
  1036. case MAGNITUDE_PM2dot5:
  1037. result = F("PM2.5");
  1038. break;
  1039. case MAGNITUDE_PM10:
  1040. result = F("PM10");
  1041. break;
  1042. case MAGNITUDE_CO2:
  1043. result = F("CO2");
  1044. break;
  1045. case MAGNITUDE_VOC:
  1046. result = F("VOC");
  1047. break;
  1048. case MAGNITUDE_IAQ_STATIC:
  1049. result = F("IAQ (Static)");
  1050. break;
  1051. case MAGNITUDE_IAQ:
  1052. result = F("IAQ");
  1053. break;
  1054. case MAGNITUDE_IAQ_ACCURACY:
  1055. result = F("IAQ Accuracy");
  1056. break;
  1057. case MAGNITUDE_LUX:
  1058. result = F("Lux");
  1059. break;
  1060. case MAGNITUDE_UVA:
  1061. result = F("UVA");
  1062. break;
  1063. case MAGNITUDE_UVB:
  1064. result = F("UVB");
  1065. break;
  1066. case MAGNITUDE_UVI:
  1067. result = F("UVI");
  1068. break;
  1069. case MAGNITUDE_DISTANCE:
  1070. result = F("Distance");
  1071. break;
  1072. case MAGNITUDE_HCHO:
  1073. result = F("HCHO");
  1074. break;
  1075. case MAGNITUDE_GEIGER_CPM:
  1076. case MAGNITUDE_GEIGER_SIEVERT:
  1077. result = F("Local Dose Rate");
  1078. break;
  1079. case MAGNITUDE_COUNT:
  1080. result = F("Count");
  1081. break;
  1082. case MAGNITUDE_NO2:
  1083. result = F("NO2");
  1084. break;
  1085. case MAGNITUDE_CO:
  1086. result = F("CO");
  1087. break;
  1088. case MAGNITUDE_RESISTANCE:
  1089. result = F("Resistance");
  1090. break;
  1091. case MAGNITUDE_PH:
  1092. result = F("pH");
  1093. break;
  1094. case MAGNITUDE_FREQUENCY:
  1095. result = F("Frequency");
  1096. break;
  1097. case MAGNITUDE_TVOC:
  1098. result = F("TVOC");
  1099. break;
  1100. case MAGNITUDE_CH2O:
  1101. result = F("CH2O");
  1102. break;
  1103. case MAGNITUDE_NONE:
  1104. default:
  1105. break;
  1106. }
  1107. return String(result);
  1108. }
  1109. // prepare available magnitude, unit and error types
  1110. void _sensorWebSocketTypes(JsonObject& root) {
  1111. JsonObject& container = root.createNestedObject("types");
  1112. static const char* const keys[] PROGMEM = {
  1113. "type", "prefix", "name"
  1114. };
  1115. JsonArray& schema = container.createNestedArray("schema");
  1116. schema.copyFrom(keys, sizeof(keys) / sizeof(*keys));
  1117. JsonArray& values = container.createNestedArray("values");
  1118. _magnitudeForEachCounted([&](unsigned char type) {
  1119. JsonArray& value = values.createNestedArray();
  1120. value.add(type);
  1121. value.add(_magnitudeSettingsPrefix(type));
  1122. value.add(_magnitudeName(type));
  1123. });
  1124. }
  1125. void _sensorWebSocketErrors(JsonObject& root) {
  1126. JsonObject& container = root.createNestedObject("errors");
  1127. static const char* const keys[] PROGMEM = {
  1128. "type", "name"
  1129. };
  1130. JsonArray& schema = container.createNestedArray("schema");
  1131. schema.copyFrom(keys, sizeof(keys) / sizeof(*keys));
  1132. JsonArray& values = container.createNestedArray("values");
  1133. _sensorForEachError([&](unsigned char type) {
  1134. JsonArray& value = values.createNestedArray();
  1135. value.add(type);
  1136. value.add(_sensorError(type));
  1137. });
  1138. }
  1139. void _sensorWebSocketMagnitudes(JsonObject& root) {
  1140. JsonObject& container = root.createNestedObject("magnitudes");
  1141. static const char* const keys[] PROGMEM = {
  1142. "index_global", "type", "units", "description"
  1143. };
  1144. JsonArray& schema = container.createNestedArray("schema");
  1145. schema.copyFrom(keys, sizeof(keys) / sizeof(*keys));
  1146. JsonArray& values = container.createNestedArray("values");
  1147. for (auto& magnitude : _magnitudes) {
  1148. JsonArray& value = values.createNestedArray();
  1149. value.add(magnitude.index_global);
  1150. value.add(magnitude.type);
  1151. value.add(_magnitudeUnits(magnitude));
  1152. value.add(_magnitudeDescription(magnitude));
  1153. }
  1154. }
  1155. void _sensorWebSocketMagnitudesConfig(JsonObject& root) {
  1156. JsonObject& container = root.createNestedObject("magnitudesConfig");
  1157. _sensorWebSocketTypes(container);
  1158. _sensorWebSocketErrors(container);
  1159. _sensorWebSocketMagnitudes(container);
  1160. }
  1161. void _sensorWebSocketSendData(JsonObject& root) {
  1162. JsonObject& container = root.createNestedObject("magnitudes");
  1163. static const char* const keys[] PROGMEM = {
  1164. "value", "error", "info"
  1165. };
  1166. JsonArray& schema = container.createNestedArray("schema");
  1167. schema.copyFrom(keys, sizeof(keys) / sizeof(*keys));
  1168. char buffer[64];
  1169. JsonArray& values = container.createNestedArray("values");
  1170. for (auto& magnitude : _magnitudes) {
  1171. JsonArray& entry = values.createNestedArray();
  1172. dtostrf(_magnitudeProcess(magnitude, magnitude.last), 1, magnitude.decimals, buffer);
  1173. entry.add(buffer);
  1174. entry.add(magnitude.sensor->error());
  1175. #if NTP_SUPPORT
  1176. if ((_sensor_save_every > 0) && (magnitude.type == MAGNITUDE_ENERGY)) {
  1177. String string = F("Last saved: ");
  1178. string += getSetting({"eneTime", magnitude.index_global}, F("(unknown)"));
  1179. entry.add(string);
  1180. } else {
  1181. entry.add("");
  1182. }
  1183. #else
  1184. entry.add("");
  1185. #endif
  1186. }
  1187. }
  1188. void _sensorWebSocketOnVisible(JsonObject& root) {
  1189. wsPayloadModule(root, "sns");
  1190. }
  1191. void _sensorWebSocketOnConnected(JsonObject& root) {
  1192. for (auto* sensor [[gnu::unused]] : _sensors) {
  1193. if (_sensorIsEmon(sensor)) {
  1194. wsPayloadModule(root, "emon");
  1195. wsPayloadModule(root, "pwr");
  1196. }
  1197. if (_sensorIsAnalogEmon(sensor)) {
  1198. root["voltMains0"] = static_cast<BaseAnalogEmonSensor*>(sensor)->getVoltage();
  1199. }
  1200. #if HLW8012_SUPPORT
  1201. if (sensor->getID() == SENSOR_HLW8012_ID) {
  1202. wsPayloadModule(root, "hlw");
  1203. }
  1204. #endif
  1205. #if CSE7766_SUPPORT
  1206. if (sensor->getID() == SENSOR_CSE7766_ID) {
  1207. wsPayloadModule(root, "cse");
  1208. }
  1209. #endif
  1210. #if PZEM004T_SUPPORT || PZEM004TV30_SUPPORT
  1211. switch (sensor->getID()) {
  1212. case SENSOR_PZEM004T_ID:
  1213. case SENSOR_PZEM004TV30_ID:
  1214. wsPayloadModule(root, "pzem");
  1215. break;
  1216. default:
  1217. break;
  1218. }
  1219. #endif
  1220. #if PULSEMETER_SUPPORT
  1221. if (sensor->getID() == SENSOR_PULSEMETER_ID) {
  1222. wsPayloadModule(root, "pm");
  1223. root["eneRatio0"] = ((PulseMeterSensor *) sensor)->getEnergyRatio();
  1224. }
  1225. #endif
  1226. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  1227. switch (sensor->getID()) {
  1228. case SENSOR_MICS2710_ID:
  1229. case SENSOR_MICS5525_ID:
  1230. wsPayloadModule(root, "mics");
  1231. break;
  1232. default:
  1233. break;
  1234. }
  1235. #endif
  1236. }
  1237. if (magnitudeCount()) {
  1238. root["snsRead"] = _sensor_read_interval / 1000;
  1239. root["snsReport"] = _sensor_report_every;
  1240. root["snsSave"] = _sensor_save_every;
  1241. _sensorWebSocketMagnitudesConfig(root);
  1242. }
  1243. }
  1244. } // namespace
  1245. // Used by modules to generate magnitude_id<->module_id mapping for the WebUI
  1246. // WS produces tuples <prefix>Magnitudes that contain type, sensor's global index and module's index
  1247. // Settings use <prefix>Magnitude<index_global> keys to allow us to retrieve module's index
  1248. void sensorWebSocketMagnitudes(JsonObject& root, const String& prefix) {
  1249. const String wsKey = prefix + F("Magnitudes");
  1250. const String confKey = wsKey.substring(0, wsKey.length() - 1);
  1251. JsonObject& namedList = root.createNestedObject(wsKey);
  1252. static const char* const keys[] PROGMEM = {
  1253. "type", "index_global", "index_module"
  1254. };
  1255. JsonArray& schema = namedList.createNestedArray("schema");
  1256. schema.copyFrom(keys, sizeof(keys) / sizeof(*keys));
  1257. JsonArray& values = namedList.createNestedArray("values");
  1258. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  1259. JsonArray& tuple = values.createNestedArray();
  1260. auto& magnitude = _magnitudes[index];
  1261. tuple.add(magnitude.type);
  1262. tuple.add(magnitude.index_global);
  1263. tuple.add(getSetting({confKey, index}, 0));
  1264. }
  1265. }
  1266. #endif // WEB_SUPPORT
  1267. #if API_SUPPORT
  1268. namespace {
  1269. String _sensorApiMagnitudeName(sensor_magnitude_t& magnitude) {
  1270. String name = _magnitudeTopic(magnitude.type);
  1271. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) name = name + "/" + String(magnitude.index_global);
  1272. return name;
  1273. }
  1274. bool _sensorApiTryParseMagnitudeIndex(const char* p, unsigned char type, unsigned char& magnitude_index) {
  1275. char* endp { nullptr };
  1276. const unsigned long result { strtoul(p, &endp, 10) };
  1277. if ((endp == p) || (*endp != '\0') || (result >= sensor_magnitude_t::counts(type))) {
  1278. DEBUG_MSG_P(PSTR("[SENSOR] Invalid magnitude ID (%s)\n"), p);
  1279. return false;
  1280. }
  1281. magnitude_index = result;
  1282. return true;
  1283. }
  1284. template <typename T>
  1285. bool _sensorApiTryHandle(ApiRequest& request, unsigned char type, T&& callback) {
  1286. unsigned char index { 0u };
  1287. if (request.wildcards()) {
  1288. auto index_param = request.wildcard(0);
  1289. if (!_sensorApiTryParseMagnitudeIndex(index_param.c_str(), type, index)) {
  1290. return false;
  1291. }
  1292. }
  1293. for (auto& magnitude : _magnitudes) {
  1294. if ((type == magnitude.type) && (index == magnitude.index_global)) {
  1295. callback(magnitude);
  1296. return true;
  1297. }
  1298. }
  1299. return false;
  1300. }
  1301. void _sensorApiSetup() {
  1302. apiRegister(F("magnitudes"),
  1303. [](ApiRequest&, JsonObject& root) {
  1304. JsonArray& magnitudes = root.createNestedArray("magnitudes");
  1305. for (auto& magnitude : _magnitudes) {
  1306. JsonArray& data = magnitudes.createNestedArray();
  1307. data.add(_sensorApiMagnitudeName(magnitude));
  1308. data.add(magnitude.last);
  1309. data.add(magnitude.reported);
  1310. }
  1311. return true;
  1312. },
  1313. nullptr
  1314. );
  1315. _magnitudeForEachCounted([](unsigned char type) {
  1316. String pattern = _magnitudeTopic(type);
  1317. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(type) > 1)) {
  1318. pattern += "/+";
  1319. }
  1320. ApiBasicHandler get {
  1321. [type](ApiRequest& request) {
  1322. return _sensorApiTryHandle(request, type, [&](const sensor_magnitude_t& magnitude) {
  1323. char buffer[64] { 0 };
  1324. dtostrf(
  1325. _sensor_realtime ? magnitude.last : magnitude.reported,
  1326. 1, magnitude.decimals,
  1327. buffer
  1328. );
  1329. request.send(String(buffer));
  1330. return true;
  1331. });
  1332. }
  1333. };
  1334. ApiBasicHandler put { nullptr };
  1335. if (type == MAGNITUDE_ENERGY) {
  1336. put = [](ApiRequest& request) {
  1337. return _sensorApiTryHandle(request, MAGNITUDE_ENERGY, [&](const sensor_magnitude_t& magnitude) {
  1338. _sensorApiResetEnergy(magnitude, request.param(F("value")));
  1339. });
  1340. };
  1341. }
  1342. apiRegister(pattern, std::move(get), std::move(put));
  1343. });
  1344. }
  1345. } // namespace
  1346. #endif // API_SUPPORT == 1
  1347. #if MQTT_SUPPORT
  1348. namespace {
  1349. void _sensorMqttCallback(unsigned int type, const char* topic, char* payload) {
  1350. static const auto energy_topic = _magnitudeTopic(MAGNITUDE_ENERGY);
  1351. switch (type) {
  1352. case MQTT_MESSAGE_EVENT: {
  1353. String t = mqttMagnitude(topic);
  1354. if (!t.startsWith(energy_topic)) break;
  1355. unsigned int index = t.substring(energy_topic.length() + 1).toInt();
  1356. if (index >= sensor_magnitude_t::counts(MAGNITUDE_ENERGY)) break;
  1357. for (auto& magnitude : _magnitudes) {
  1358. if (MAGNITUDE_ENERGY != magnitude.type) continue;
  1359. if (index != magnitude.index_global) continue;
  1360. _sensorApiResetEnergy(magnitude, payload);
  1361. break;
  1362. }
  1363. }
  1364. case MQTT_CONNECT_EVENT: {
  1365. for (auto& magnitude : _magnitudes) {
  1366. if (MAGNITUDE_ENERGY == magnitude.type) {
  1367. const String topic = energy_topic + "/+";
  1368. mqttSubscribe(topic.c_str());
  1369. break;
  1370. }
  1371. }
  1372. }
  1373. case MQTT_DISCONNECT_EVENT:
  1374. default:
  1375. break;
  1376. }
  1377. }
  1378. } // namespace
  1379. #endif // MQTT_SUPPORT == 1
  1380. #if TERMINAL_SUPPORT
  1381. namespace {
  1382. void _sensorInitCommands() {
  1383. terminalRegisterCommand(F("MAGNITUDES"), [](const terminal::CommandContext&) {
  1384. char last[64];
  1385. char reported[64];
  1386. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  1387. auto& magnitude = _magnitudes.at(index);
  1388. dtostrf(magnitude.last, 1, magnitude.decimals, last);
  1389. dtostrf(magnitude.reported, 1, magnitude.decimals, reported);
  1390. DEBUG_MSG_P(PSTR("[SENSOR] %2u * %s/%u @ %s (last:%s, reported:%s)\n"),
  1391. index,
  1392. _magnitudeTopic(magnitude.type).c_str(),
  1393. magnitude.index_global,
  1394. _magnitudeDescription(magnitude).c_str(),
  1395. last, reported
  1396. );
  1397. }
  1398. terminalOK();
  1399. });
  1400. }
  1401. } // namespace
  1402. #endif // TERMINAL_SUPPORT == 1
  1403. namespace {
  1404. void _sensorTick() {
  1405. for (auto* sensor : _sensors) {
  1406. sensor->tick();
  1407. }
  1408. }
  1409. void _sensorPre() {
  1410. for (auto* sensor : _sensors) {
  1411. sensor->pre();
  1412. if (!sensor->status()) {
  1413. DEBUG_MSG_P(PSTR("[SENSOR] Error reading data from %s (error: %d)\n"),
  1414. sensor->description().c_str(),
  1415. sensor->error()
  1416. );
  1417. }
  1418. }
  1419. }
  1420. void _sensorPost() {
  1421. for (auto* sensor : _sensors) {
  1422. sensor->post();
  1423. }
  1424. }
  1425. } // namespace
  1426. // -----------------------------------------------------------------------------
  1427. // Sensor initialization
  1428. // -----------------------------------------------------------------------------
  1429. namespace {
  1430. void _sensorLoad() {
  1431. /*
  1432. This is temporal, in the future sensors will be initialized based on
  1433. soft configuration (data stored in EEPROM config) so you will be able
  1434. to define and configure new sensors on the fly
  1435. At the time being, only enabled sensors (those with *_SUPPORT to 1) are being
  1436. loaded and initialized here. If you want to add new sensors of the same type
  1437. just duplicate the block and change the arguments for the set* methods.
  1438. For example, how to add a second DHT sensor:
  1439. #if DHT_SUPPORT
  1440. {
  1441. DHTSensor * sensor = new DHTSensor();
  1442. sensor->setGPIO(DHT2_PIN);
  1443. sensor->setType(DHT2_TYPE);
  1444. _sensors.push_back(sensor);
  1445. }
  1446. #endif
  1447. DHT2_PIN and DHT2_TYPE should be globally accessible:
  1448. - as `src_build_flags = -DDHT2_PIN=... -DDHT2_TYPE=...`
  1449. - in custom.h, as `#define ...`
  1450. */
  1451. #if AM2320_SUPPORT
  1452. {
  1453. AM2320Sensor * sensor = new AM2320Sensor();
  1454. sensor->setAddress(AM2320_ADDRESS);
  1455. _sensors.push_back(sensor);
  1456. }
  1457. #endif
  1458. #if ANALOG_SUPPORT
  1459. {
  1460. AnalogSensor * sensor = new AnalogSensor();
  1461. sensor->setSamples(ANALOG_SAMPLES);
  1462. sensor->setDelay(ANALOG_DELAY);
  1463. //CICM For analog scaling
  1464. sensor->setFactor(ANALOG_FACTOR);
  1465. sensor->setOffset(ANALOG_OFFSET);
  1466. _sensors.push_back(sensor);
  1467. }
  1468. #endif
  1469. #if BH1750_SUPPORT
  1470. {
  1471. BH1750Sensor * sensor = new BH1750Sensor();
  1472. sensor->setAddress(BH1750_ADDRESS);
  1473. sensor->setMode(BH1750_MODE);
  1474. _sensors.push_back(sensor);
  1475. }
  1476. #endif
  1477. #if BMP180_SUPPORT
  1478. {
  1479. BMP180Sensor * sensor = new BMP180Sensor();
  1480. sensor->setAddress(BMP180_ADDRESS);
  1481. _sensors.push_back(sensor);
  1482. }
  1483. #endif
  1484. #if BMX280_SUPPORT
  1485. {
  1486. // Support up to two sensors with full auto-discovery.
  1487. const unsigned char number = constrain(getSetting("bmx280Number", BMX280_NUMBER), 1, 2);
  1488. // For second sensor, if BMX280_ADDRESS is 0x00 then auto-discover
  1489. // otherwise choose the other unnamed sensor address
  1490. const auto first = getSetting("bmx280Address", BMX280_ADDRESS);
  1491. const auto second = (first == 0x00) ? 0x00 : (0x76 + 0x77 - first);
  1492. const decltype(first) address_map[2] { first, second };
  1493. for (unsigned char n=0; n < number; ++n) {
  1494. BMX280Sensor * sensor = new BMX280Sensor();
  1495. sensor->setAddress(address_map[n]);
  1496. _sensors.push_back(sensor);
  1497. }
  1498. }
  1499. #endif
  1500. #if BME680_SUPPORT
  1501. {
  1502. BME680Sensor * sensor = new BME680Sensor();
  1503. sensor->setAddress(BME680_I2C_ADDRESS);
  1504. _sensors.push_back(sensor);
  1505. }
  1506. #endif
  1507. #if CSE7766_SUPPORT
  1508. {
  1509. CSE7766Sensor * sensor = new CSE7766Sensor();
  1510. sensor->setRX(CSE7766_RX_PIN);
  1511. _sensors.push_back(sensor);
  1512. }
  1513. #endif
  1514. #if DALLAS_SUPPORT
  1515. {
  1516. DallasSensor * sensor = new DallasSensor();
  1517. sensor->setGPIO(DALLAS_PIN);
  1518. _sensors.push_back(sensor);
  1519. }
  1520. #endif
  1521. #if DHT_SUPPORT
  1522. {
  1523. DHTSensor * sensor = new DHTSensor();
  1524. sensor->setGPIO(DHT_PIN);
  1525. sensor->setType(DHT_TYPE);
  1526. _sensors.push_back(sensor);
  1527. }
  1528. #endif
  1529. #if DIGITAL_SUPPORT
  1530. {
  1531. auto getPin = [](unsigned char index) -> int {
  1532. switch (index) {
  1533. case 0: return DIGITAL1_PIN;
  1534. case 1: return DIGITAL2_PIN;
  1535. case 2: return DIGITAL3_PIN;
  1536. case 3: return DIGITAL4_PIN;
  1537. case 4: return DIGITAL5_PIN;
  1538. case 5: return DIGITAL6_PIN;
  1539. case 6: return DIGITAL7_PIN;
  1540. case 7: return DIGITAL8_PIN;
  1541. default: return GPIO_NONE;
  1542. }
  1543. };
  1544. auto getDefaultState = [](unsigned char index) -> int {
  1545. switch (index) {
  1546. case 0: return DIGITAL1_DEFAULT_STATE;
  1547. case 1: return DIGITAL2_DEFAULT_STATE;
  1548. case 2: return DIGITAL3_DEFAULT_STATE;
  1549. case 3: return DIGITAL4_DEFAULT_STATE;
  1550. case 4: return DIGITAL5_DEFAULT_STATE;
  1551. case 5: return DIGITAL6_DEFAULT_STATE;
  1552. case 6: return DIGITAL7_DEFAULT_STATE;
  1553. case 7: return DIGITAL8_DEFAULT_STATE;
  1554. default: return 1;
  1555. }
  1556. };
  1557. auto getMode = [](unsigned char index) -> int {
  1558. switch (index) {
  1559. case 0: return DIGITAL1_PIN_MODE;
  1560. case 1: return DIGITAL2_PIN_MODE;
  1561. case 2: return DIGITAL3_PIN_MODE;
  1562. case 3: return DIGITAL4_PIN_MODE;
  1563. case 4: return DIGITAL5_PIN_MODE;
  1564. case 5: return DIGITAL6_PIN_MODE;
  1565. case 6: return DIGITAL7_PIN_MODE;
  1566. case 7: return DIGITAL8_PIN_MODE;
  1567. default: return INPUT_PULLUP;
  1568. }
  1569. };
  1570. auto pins = gpioPins();
  1571. for (unsigned char index = 0; index < pins; ++index) {
  1572. const auto pin = getPin(index);
  1573. if (pin == GPIO_NONE) break;
  1574. DigitalSensor * sensor = new DigitalSensor();
  1575. sensor->setGPIO(pin);
  1576. sensor->setMode(getMode(index));
  1577. sensor->setDefault(getDefaultState(index));
  1578. _sensors.push_back(sensor);
  1579. }
  1580. }
  1581. #endif
  1582. #if ECH1560_SUPPORT
  1583. {
  1584. ECH1560Sensor * sensor = new ECH1560Sensor();
  1585. sensor->setCLK(ECH1560_CLK_PIN);
  1586. sensor->setMISO(ECH1560_MISO_PIN);
  1587. sensor->setInverted(ECH1560_INVERTED);
  1588. _sensors.push_back(sensor);
  1589. }
  1590. #endif
  1591. #if EMON_ADC121_SUPPORT
  1592. {
  1593. EmonADC121Sensor * sensor = new EmonADC121Sensor();
  1594. sensor->setAddress(EMON_ADC121_I2C_ADDRESS);
  1595. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1596. sensor->setReferenceVoltage(EMON_REFERENCE_VOLTAGE);
  1597. _sensors.push_back(sensor);
  1598. }
  1599. #endif
  1600. #if EMON_ADS1X15_SUPPORT
  1601. {
  1602. auto port = std::make_shared<EmonADS1X15Sensor::I2CPort>(
  1603. EMON_ADS1X15_I2C_ADDRESS, EMON_ADS1X15_TYPE, EMON_ADS1X15_GAIN, EMON_ADS1X15_DATARATE);
  1604. unsigned char channel { 0 };
  1605. unsigned char mask { EMON_ADS1X15_MASK };
  1606. constexpr unsigned char FirstBit { 1 };
  1607. while (mask) {
  1608. if (mask & FirstBit) {
  1609. auto* sensor = new EmonADS1X15Sensor(port);
  1610. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1611. sensor->setChannel(channel);
  1612. _sensors.push_back(sensor);
  1613. }
  1614. ++channel;
  1615. }
  1616. }
  1617. #endif
  1618. #if EMON_ANALOG_SUPPORT
  1619. {
  1620. auto* sensor = new EmonAnalogSensor();
  1621. sensor->setVoltage(EMON_MAINS_VOLTAGE);
  1622. sensor->setReferenceVoltage(EMON_REFERENCE_VOLTAGE);
  1623. sensor->setResolution(EMON_ANALOG_RESOLUTION);
  1624. _sensors.push_back(sensor);
  1625. }
  1626. #endif
  1627. #if EVENTS_SUPPORT
  1628. {
  1629. auto getPin = [](unsigned char index) -> int {
  1630. switch (index) {
  1631. case 0: return EVENTS1_PIN;
  1632. case 1: return EVENTS2_PIN;
  1633. case 2: return EVENTS3_PIN;
  1634. case 3: return EVENTS4_PIN;
  1635. case 4: return EVENTS5_PIN;
  1636. case 5: return EVENTS6_PIN;
  1637. case 6: return EVENTS7_PIN;
  1638. case 7: return EVENTS8_PIN;
  1639. default: return GPIO_NONE;
  1640. }
  1641. };
  1642. auto getMode = [](unsigned char index) -> int {
  1643. switch (index) {
  1644. case 0: return EVENTS1_PIN_MODE;
  1645. case 1: return EVENTS2_PIN_MODE;
  1646. case 2: return EVENTS3_PIN_MODE;
  1647. case 3: return EVENTS4_PIN_MODE;
  1648. case 4: return EVENTS5_PIN_MODE;
  1649. case 5: return EVENTS6_PIN_MODE;
  1650. case 6: return EVENTS7_PIN_MODE;
  1651. case 7: return EVENTS8_PIN_MODE;
  1652. default: return INPUT;
  1653. }
  1654. };
  1655. auto getDebounce = [](unsigned char index) -> unsigned long {
  1656. switch (index) {
  1657. case 0: return EVENTS1_DEBOUNCE;
  1658. case 1: return EVENTS2_DEBOUNCE;
  1659. case 2: return EVENTS3_DEBOUNCE;
  1660. case 3: return EVENTS4_DEBOUNCE;
  1661. case 4: return EVENTS5_DEBOUNCE;
  1662. case 5: return EVENTS6_DEBOUNCE;
  1663. case 6: return EVENTS7_DEBOUNCE;
  1664. case 7: return EVENTS8_DEBOUNCE;
  1665. default: return 50;
  1666. }
  1667. };
  1668. auto getIsrMode = [](unsigned char index) -> int {
  1669. switch (index) {
  1670. case 0: return EVENTS1_INTERRUPT_MODE;
  1671. case 1: return EVENTS2_INTERRUPT_MODE;
  1672. case 2: return EVENTS3_INTERRUPT_MODE;
  1673. case 3: return EVENTS4_INTERRUPT_MODE;
  1674. case 4: return EVENTS5_INTERRUPT_MODE;
  1675. case 5: return EVENTS6_INTERRUPT_MODE;
  1676. case 6: return EVENTS7_INTERRUPT_MODE;
  1677. case 7: return EVENTS8_INTERRUPT_MODE;
  1678. default: return RISING;
  1679. }
  1680. };
  1681. auto pins = gpioPins();
  1682. for (unsigned char index = 0; index < pins; ++index) {
  1683. const auto pin = getPin(index);
  1684. if (pin == GPIO_NONE) break;
  1685. EventSensor * sensor = new EventSensor();
  1686. sensor->setGPIO(pin);
  1687. sensor->setPinMode(getMode(index));
  1688. sensor->setDebounceTime(getDebounce(index));
  1689. sensor->setInterruptMode(getIsrMode(index));
  1690. _sensors.push_back(sensor);
  1691. }
  1692. }
  1693. #endif
  1694. #if GEIGER_SUPPORT
  1695. {
  1696. GeigerSensor * sensor = new GeigerSensor(); // Create instance of thr Geiger module.
  1697. sensor->setGPIO(GEIGER_PIN); // Interrupt pin of the attached geiger counter board.
  1698. sensor->setMode(GEIGER_PIN_MODE); // This pin is an input.
  1699. sensor->setDebounceTime(GEIGER_DEBOUNCE); // Debounce time 25ms, because https://github.com/Trickx/espurna/wiki/Geiger-counter
  1700. sensor->setInterruptMode(GEIGER_INTERRUPT_MODE); // Interrupt triggering: edge detection rising.
  1701. sensor->setCPM2SievertFactor(GEIGER_CPM2SIEVERT); // Conversion factor from counts per minute to µSv/h
  1702. _sensors.push_back(sensor);
  1703. }
  1704. #endif
  1705. #if GUVAS12SD_SUPPORT
  1706. {
  1707. GUVAS12SDSensor * sensor = new GUVAS12SDSensor();
  1708. sensor->setGPIO(GUVAS12SD_PIN);
  1709. _sensors.push_back(sensor);
  1710. }
  1711. #endif
  1712. #if SONAR_SUPPORT
  1713. {
  1714. SonarSensor * sensor = new SonarSensor();
  1715. sensor->setEcho(SONAR_ECHO);
  1716. sensor->setIterations(SONAR_ITERATIONS);
  1717. sensor->setMaxDistance(SONAR_MAX_DISTANCE);
  1718. sensor->setTrigger(SONAR_TRIGGER);
  1719. _sensors.push_back(sensor);
  1720. }
  1721. #endif
  1722. #if HLW8012_SUPPORT
  1723. {
  1724. HLW8012Sensor * sensor = new HLW8012Sensor();
  1725. sensor->setSEL(getSetting(F("hlw8012SEL"), HLW8012_SEL_PIN));
  1726. sensor->setCF(getSetting(F("hlw8012CF"), HLW8012_CF_PIN));
  1727. sensor->setCF1(getSetting(F("hlw8012CF1"), HLW8012_CF1_PIN));
  1728. sensor->setSELCurrent(HLW8012_SEL_CURRENT);
  1729. _sensors.push_back(sensor);
  1730. }
  1731. #endif
  1732. #if LDR_SUPPORT
  1733. {
  1734. LDRSensor * sensor = new LDRSensor();
  1735. sensor->setSamples(LDR_SAMPLES);
  1736. sensor->setDelay(LDR_DELAY);
  1737. sensor->setType(LDR_TYPE);
  1738. sensor->setPhotocellPositionOnGround(LDR_ON_GROUND);
  1739. sensor->setResistor(LDR_RESISTOR);
  1740. sensor->setPhotocellParameters(LDR_MULTIPLICATION, LDR_POWER);
  1741. _sensors.push_back(sensor);
  1742. }
  1743. #endif
  1744. #if MHZ19_SUPPORT
  1745. {
  1746. MHZ19Sensor * sensor = new MHZ19Sensor();
  1747. sensor->setRX(MHZ19_RX_PIN);
  1748. sensor->setTX(MHZ19_TX_PIN);
  1749. sensor->setCalibrateAuto(getSetting("mhz19CalibrateAuto", false));
  1750. _sensors.push_back(sensor);
  1751. }
  1752. #endif
  1753. #if MICS2710_SUPPORT
  1754. {
  1755. MICS2710Sensor * sensor = new MICS2710Sensor();
  1756. sensor->setAnalogGPIO(MICS2710_NOX_PIN);
  1757. sensor->setPreHeatGPIO(MICS2710_PRE_PIN);
  1758. sensor->setR0(MICS2710_R0);
  1759. sensor->setRL(MICS2710_RL);
  1760. sensor->setRS(0);
  1761. _sensors.push_back(sensor);
  1762. }
  1763. #endif
  1764. #if MICS5525_SUPPORT
  1765. {
  1766. MICS5525Sensor * sensor = new MICS5525Sensor();
  1767. sensor->setAnalogGPIO(MICS5525_RED_PIN);
  1768. sensor->setR0(MICS5525_R0);
  1769. sensor->setRL(MICS5525_RL);
  1770. sensor->setRS(0);
  1771. _sensors.push_back(sensor);
  1772. }
  1773. #endif
  1774. #if NTC_SUPPORT
  1775. {
  1776. NTCSensor * sensor = new NTCSensor();
  1777. sensor->setSamples(NTC_SAMPLES);
  1778. sensor->setDelay(NTC_DELAY);
  1779. sensor->setUpstreamResistor(NTC_R_UP);
  1780. sensor->setDownstreamResistor(NTC_R_DOWN);
  1781. sensor->setBeta(NTC_BETA);
  1782. sensor->setR0(NTC_R0);
  1783. sensor->setT0(NTC_T0);
  1784. _sensors.push_back(sensor);
  1785. }
  1786. #endif
  1787. #if PMSX003_SUPPORT
  1788. {
  1789. PMSX003Sensor * sensor = new PMSX003Sensor();
  1790. #if PMS_USE_SOFT
  1791. sensor->setRX(PMS_RX_PIN);
  1792. sensor->setTX(PMS_TX_PIN);
  1793. #else
  1794. sensor->setSerial(& PMS_HW_PORT);
  1795. #endif
  1796. sensor->setType(PMS_TYPE);
  1797. _sensors.push_back(sensor);
  1798. }
  1799. #endif
  1800. #if PULSEMETER_SUPPORT
  1801. {
  1802. PulseMeterSensor * sensor = new PulseMeterSensor();
  1803. sensor->setGPIO(PULSEMETER_PIN);
  1804. sensor->setEnergyRatio(PULSEMETER_ENERGY_RATIO);
  1805. sensor->setInterruptMode(PULSEMETER_INTERRUPT_ON);
  1806. sensor->setDebounceTime(PULSEMETER_DEBOUNCE);
  1807. _sensors.push_back(sensor);
  1808. }
  1809. #endif
  1810. #if PZEM004T_SUPPORT
  1811. {
  1812. // TODO: manage indexes like Emon, no need for magic offsets
  1813. // TODO: ...and the same for the v3
  1814. PZEM004TSensor * sensor = new PZEM004TSensor();
  1815. #if !defined(PZEM004T_ADDRESSES)
  1816. for (size_t index = 0; index < PZEM004TSensor::DevicesMax; ++index) {
  1817. auto address = getSetting({"pzemAddr", index}, PZEM004TSensor::defaultAddress(index));
  1818. if (!address.length()) {
  1819. break;
  1820. }
  1821. if (!sensor->addAddress(address)) {
  1822. break;
  1823. }
  1824. }
  1825. #else
  1826. String addrs = getSetting("pzemAddr", F(PZEM004T_ADDRESSES));
  1827. constexpr size_t BufferSize{64};
  1828. char buffer[BufferSize]{0};
  1829. if (addrs.length() < BufferSize) {
  1830. std::copy(addrs.c_str(), addrs.c_str() + addrs.length(), buffer);
  1831. buffer[addrs.length()] = '\0';
  1832. char* address{strtok(buffer, " ")};
  1833. while (address != nullptr) {
  1834. if (!sensor->addAddress(address)) {
  1835. break;
  1836. }
  1837. address = strtok(nullptr, " ");
  1838. }
  1839. }
  1840. #endif
  1841. if (sensor->countDevices()) {
  1842. sensor->setRX(getSetting("pzemRX", PZEM004T_RX_PIN));
  1843. sensor->setTX(getSetting("pzemTX", PZEM004T_TX_PIN));
  1844. if (!getSetting("pzemSoft", 1 == PZEM004T_USE_SOFT)) {
  1845. sensor->setSerial(& PZEM004T_HW_PORT);
  1846. }
  1847. _sensors.push_back(sensor);
  1848. #if TERMINAL_SUPPORT
  1849. pzem004tInitCommands(sensor);
  1850. #endif
  1851. } else {
  1852. delete sensor;
  1853. }
  1854. }
  1855. #endif
  1856. #if SENSEAIR_SUPPORT
  1857. {
  1858. SenseAirSensor * sensor = new SenseAirSensor();
  1859. sensor->setRX(SENSEAIR_RX_PIN);
  1860. sensor->setTX(SENSEAIR_TX_PIN);
  1861. _sensors.push_back(sensor);
  1862. }
  1863. #endif
  1864. #if SDS011_SUPPORT
  1865. {
  1866. SDS011Sensor * sensor = new SDS011Sensor();
  1867. sensor->setRX(SDS011_RX_PIN);
  1868. sensor->setTX(SDS011_TX_PIN);
  1869. _sensors.push_back(sensor);
  1870. }
  1871. #endif
  1872. #if SHT3X_I2C_SUPPORT
  1873. {
  1874. SHT3XI2CSensor * sensor = new SHT3XI2CSensor();
  1875. sensor->setAddress(SHT3X_I2C_ADDRESS);
  1876. _sensors.push_back(sensor);
  1877. }
  1878. #endif
  1879. #if SI7021_SUPPORT
  1880. {
  1881. SI7021Sensor * sensor = new SI7021Sensor();
  1882. sensor->setAddress(SI7021_ADDRESS);
  1883. _sensors.push_back(sensor);
  1884. }
  1885. #endif
  1886. #if SM300D2_SUPPORT
  1887. {
  1888. SM300D2Sensor * sensor = new SM300D2Sensor();
  1889. sensor->setRX(SM300D2_RX_PIN);
  1890. _sensors.push_back(sensor);
  1891. }
  1892. #endif
  1893. #if T6613_SUPPORT
  1894. {
  1895. T6613Sensor * sensor = new T6613Sensor();
  1896. sensor->setRX(T6613_RX_PIN);
  1897. sensor->setTX(T6613_TX_PIN);
  1898. _sensors.push_back(sensor);
  1899. }
  1900. #endif
  1901. #if TMP3X_SUPPORT
  1902. {
  1903. TMP3XSensor * sensor = new TMP3XSensor();
  1904. sensor->setType(TMP3X_TYPE);
  1905. _sensors.push_back(sensor);
  1906. }
  1907. #endif
  1908. #if V9261F_SUPPORT
  1909. {
  1910. V9261FSensor * sensor = new V9261FSensor();
  1911. sensor->setRX(V9261F_PIN);
  1912. sensor->setInverted(V9261F_PIN_INVERSE);
  1913. _sensors.push_back(sensor);
  1914. }
  1915. #endif
  1916. #if MAX6675_SUPPORT
  1917. {
  1918. MAX6675Sensor * sensor = new MAX6675Sensor();
  1919. sensor->setCS(MAX6675_CS_PIN);
  1920. sensor->setSO(MAX6675_SO_PIN);
  1921. sensor->setSCK(MAX6675_SCK_PIN);
  1922. _sensors.push_back(sensor);
  1923. }
  1924. #endif
  1925. #if VEML6075_SUPPORT
  1926. {
  1927. VEML6075Sensor * sensor = new VEML6075Sensor();
  1928. sensor->setIntegrationTime(VEML6075_INTEGRATION_TIME);
  1929. sensor->setDynamicMode(VEML6075_DYNAMIC_MODE);
  1930. _sensors.push_back(sensor);
  1931. }
  1932. #endif
  1933. #if VL53L1X_SUPPORT
  1934. {
  1935. VL53L1XSensor * sensor = new VL53L1XSensor();
  1936. sensor->setInterMeasurementPeriod(VL53L1X_INTER_MEASUREMENT_PERIOD);
  1937. sensor->setDistanceMode(VL53L1X_DISTANCE_MODE);
  1938. sensor->setMeasurementTimingBudget(VL53L1X_MEASUREMENT_TIMING_BUDGET);
  1939. _sensors.push_back(sensor);
  1940. }
  1941. #endif
  1942. #if EZOPH_SUPPORT
  1943. {
  1944. EZOPHSensor * sensor = new EZOPHSensor();
  1945. sensor->setRX(EZOPH_RX_PIN);
  1946. sensor->setTX(EZOPH_TX_PIN);
  1947. _sensors.push_back(sensor);
  1948. }
  1949. #endif
  1950. #if ADE7953_SUPPORT
  1951. {
  1952. ADE7953Sensor * sensor = new ADE7953Sensor();
  1953. sensor->setAddress(ADE7953_ADDRESS);
  1954. _sensors.push_back(sensor);
  1955. }
  1956. #endif
  1957. #if SI1145_SUPPORT
  1958. {
  1959. SI1145Sensor * sensor = new SI1145Sensor();
  1960. sensor->setAddress(SI1145_ADDRESS);
  1961. _sensors.push_back(sensor);
  1962. }
  1963. #endif
  1964. #if HDC1080_SUPPORT
  1965. {
  1966. HDC1080Sensor * sensor = new HDC1080Sensor();
  1967. sensor->setAddress(HDC1080_ADDRESS);
  1968. _sensors.push_back(sensor);
  1969. }
  1970. #endif
  1971. #if PZEM004TV30_SUPPORT
  1972. {
  1973. PZEM004TV30Sensor * sensor = PZEM004TV30Sensor::create();
  1974. // TODO: we need an equivalent to the `pzem.address` command
  1975. sensor->setAddress(getSetting("pzemv30Addr", PZEM004TV30Sensor::DefaultAddress));
  1976. sensor->setReadTimeout(getSetting("pzemv30ReadTimeout", PZEM004TV30Sensor::DefaultReadTimeout));
  1977. sensor->setDebug(getSetting("pzemv30Debug", 1 == PZEM004TV30_DEBUG));
  1978. bool soft = getSetting("pzemv30Soft", 1 == PZEM004TV30_USE_SOFT);
  1979. int tx = getSetting("pzemv30TX", PZEM004TV30_TX_PIN);
  1980. int rx = getSetting("pzemv30RX", PZEM004TV30_RX_PIN);
  1981. // we operate only with Serial, as Serial1 cannot not receive any data
  1982. if (!soft) {
  1983. sensor->setStream(&Serial);
  1984. sensor->setDescription("HwSerial");
  1985. Serial.begin(PZEM004TV30Sensor::Baudrate);
  1986. // Core does not allow us to begin(baud, cfg, rx, tx) / pins(rx, tx) before begin(baud)
  1987. // b/c internal UART handler does not exist yet
  1988. // Also see https://github.com/esp8266/Arduino/issues/2380 as to why there is flush()
  1989. if ((tx == 15) && (rx == 13)) {
  1990. Serial.flush();
  1991. Serial.swap();
  1992. }
  1993. } else {
  1994. auto* ptr = new SoftwareSerial(rx, tx);
  1995. sensor->setDescription("SwSerial");
  1996. sensor->setStream(ptr); // we don't care about lifetime
  1997. ptr->begin(PZEM004TV30Sensor::Baudrate);
  1998. }
  1999. //TODO: getSetting("pzemv30*Cfg", (SW)SERIAL_8N1); ?
  2000. // may not be relevant, but some sources claim we need 8N2
  2001. _sensors.push_back(sensor);
  2002. }
  2003. #endif
  2004. }
  2005. String _magnitudeTopicIndex(const sensor_magnitude_t& magnitude) {
  2006. char buffer[32] = {0};
  2007. String topic { _magnitudeTopic(magnitude.type) };
  2008. if (SENSOR_USE_INDEX || (sensor_magnitude_t::counts(magnitude.type) > 1)) {
  2009. snprintf(buffer, sizeof(buffer), "%s/%u", topic.c_str(), magnitude.index_global);
  2010. } else {
  2011. snprintf(buffer, sizeof(buffer), "%s", topic.c_str());
  2012. }
  2013. return String(buffer);
  2014. }
  2015. void _sensorReport(unsigned char index, const sensor_magnitude_t& magnitude) {
  2016. // XXX: dtostrf only handles basic floating point values and will never produce scientific notation
  2017. // ensure decimals is within some sane limit and the actual value never goes above this buffer size
  2018. char buffer[64];
  2019. dtostrf(magnitude.reported, 1, magnitude.decimals, buffer);
  2020. for (auto& handler : _magnitude_report_handlers) {
  2021. handler(_magnitudeTopic(magnitude.type), magnitude.index_global, magnitude.reported, buffer);
  2022. }
  2023. #if MQTT_SUPPORT
  2024. {
  2025. const String topic(_magnitudeTopicIndex(magnitude));
  2026. mqttSend(topic.c_str(), buffer);
  2027. #if SENSOR_PUBLISH_ADDRESSES
  2028. String address_topic;
  2029. address_topic.reserve(topic.length() + 1 + strlen(SENSOR_ADDRESS_TOPIC));
  2030. address_topic += F(SENSOR_ADDRESS_TOPIC);
  2031. address_topic += '/';
  2032. address_topic += topic;
  2033. mqttSend(address_topic.c_str(), magnitude.sensor->address(magnitude.slot).c_str());
  2034. #endif // SENSOR_PUBLISH_ADDRESSES
  2035. }
  2036. #endif // MQTT_SUPPORT
  2037. // TODO: both integrations depend on the absolute index instead of specific type
  2038. // so, we still need to pass / know the 'global' index inside of _magnitudes[]
  2039. #if THINGSPEAK_SUPPORT
  2040. tspkEnqueueMeasurement(index, buffer);
  2041. #endif // THINGSPEAK_SUPPORT
  2042. #if DOMOTICZ_SUPPORT
  2043. domoticzSendMagnitude(magnitude.type, index, magnitude.reported, buffer);
  2044. #endif // DOMOTICZ_SUPPORT
  2045. }
  2046. void _sensorInit() {
  2047. _sensors_ready = true;
  2048. for (auto& sensor : _sensors) {
  2049. // Do not process an already initialized sensor
  2050. if (sensor->ready()) continue;
  2051. DEBUG_MSG_P(PSTR("[SENSOR] Initializing %s\n"), sensor->description().c_str());
  2052. // Force sensor to reload config
  2053. sensor->begin();
  2054. if (!sensor->ready()) {
  2055. if (0 != sensor->error()) {
  2056. DEBUG_MSG_P(PSTR("[SENSOR] -> ERROR %d\n"), sensor->error());
  2057. }
  2058. _sensors_ready = false;
  2059. break;
  2060. }
  2061. // Initialize sensor magnitudes
  2062. for (unsigned char magnitude_index = 0; magnitude_index < sensor->count(); ++magnitude_index) {
  2063. const auto magnitude_type = sensor->type(magnitude_index);
  2064. const auto magnitude_local = sensor->local(magnitude_index);
  2065. _magnitudes.emplace_back(
  2066. magnitude_index, // id of the magnitude, unique to the sensor
  2067. magnitude_local, // index_local, # of the magnitude
  2068. magnitude_type, // specific type of the magnitude
  2069. sensor::Unit::None, // set up later, in configuration
  2070. sensor // bind the sensor to allow us to reference it later
  2071. );
  2072. auto& magnitude = _magnitudes.back();
  2073. if (_sensorIsEmon(sensor) && (MAGNITUDE_ENERGY == magnitude_type)) {
  2074. const auto index_global = magnitude.index_global;
  2075. auto* ptr = static_cast<BaseEmonSensor*>(sensor);
  2076. ptr->resetEnergy(magnitude.index_local, _sensorEnergyTotal(index_global));
  2077. _sensor_save_count.push_back(0);
  2078. }
  2079. DEBUG_MSG_P(PSTR("[SENSOR] -> %s:%u\n"),
  2080. _magnitudeTopic(magnitude.type).c_str(),
  2081. sensor_magnitude_t::counts(magnitude.type));
  2082. }
  2083. // Custom initializations are based on IDs
  2084. switch (sensor->getID()) {
  2085. case SENSOR_MICS2710_ID:
  2086. case SENSOR_MICS5525_ID: {
  2087. auto* ptr = static_cast<BaseAnalogSensor*>(sensor);
  2088. ptr->setR0(getSetting("snsR0", ptr->getR0()));
  2089. ptr->setRS(getSetting("snsRS", ptr->getRS()));
  2090. ptr->setRL(getSetting("snsRL", ptr->getRL()));
  2091. break;
  2092. }
  2093. default:
  2094. break;
  2095. }
  2096. }
  2097. }
  2098. } // namespace
  2099. namespace settings {
  2100. namespace internal {
  2101. template <>
  2102. sensor::Unit convert(const String& value) {
  2103. auto len = value.length();
  2104. if (len && isNumber(value)) {
  2105. constexpr int Min { static_cast<int>(sensor::Unit::Min_) };
  2106. constexpr int Max { static_cast<int>(sensor::Unit::Max_) };
  2107. auto num = convert<int>(value);
  2108. if ((Min < num) && (num < Max)) {
  2109. return static_cast<sensor::Unit>(num);
  2110. }
  2111. }
  2112. return sensor::Unit::None;
  2113. }
  2114. String serialize(sensor::Unit unit) {
  2115. return serialize(static_cast<int>(unit));
  2116. }
  2117. } // namespace internal
  2118. } // namespace settings
  2119. namespace {
  2120. void _sensorConfigure() {
  2121. // General sensor settings for reporting and saving
  2122. _sensor_read_interval = 1000 * constrain(getSetting("snsRead", SENSOR_READ_INTERVAL), SENSOR_READ_MIN_INTERVAL, SENSOR_READ_MAX_INTERVAL);
  2123. _sensor_report_every = constrain(getSetting("snsReport", SENSOR_REPORT_EVERY), SENSOR_REPORT_MIN_EVERY, SENSOR_REPORT_MAX_EVERY);
  2124. _sensor_save_every = getSetting("snsSave", SENSOR_SAVE_EVERY);
  2125. _sensor_realtime = getSetting("apiRealTime", 1 == API_REAL_TIME_VALUES);
  2126. // pre-load some settings that are controlled via old build flags
  2127. const auto tmp_min_delta = getSetting("tmpMinDelta", TEMPERATURE_MIN_CHANGE);
  2128. const auto hum_min_delta = getSetting("humMinDelta", HUMIDITY_MIN_CHANGE);
  2129. const auto ene_max_delta = getSetting("eneMaxDelta", ENERGY_MAX_CHANGE);
  2130. // Apply settings based on sensor type
  2131. for (unsigned char index = 0; index < _sensors.size(); ++index) {
  2132. #if MICS2710_SUPPORT || MICS5525_SUPPORT
  2133. {
  2134. if (getSetting("snsResetCalibration", false)) {
  2135. switch (_sensors[index]->getID()) {
  2136. case SENSOR_MICS2710_ID:
  2137. case SENSOR_MICS5525_ID: {
  2138. auto* sensor = static_cast<BaseAnalogSensor*>(_sensors[index]);
  2139. sensor->calibrate();
  2140. setSetting("snsR0", sensor->getR0());
  2141. break;
  2142. }
  2143. default:
  2144. break;
  2145. }
  2146. }
  2147. }
  2148. #endif // MICS2710_SUPPORT || MICS5525_SUPPORT
  2149. if (_sensorIsEmon(_sensors[index])) {
  2150. // TODO: ::isEmon() ?
  2151. double value;
  2152. auto* sensor = static_cast<BaseEmonSensor*>(_sensors[index]);
  2153. if ((value = getSetting("pwrExpectedC", 0.0))) {
  2154. sensor->expectedCurrent(value);
  2155. delSetting("pwrExpectedC");
  2156. setSetting(_magnitudeSettingsRatioKey(MAGNITUDE_CURRENT, 0), sensor->getCurrentRatio());
  2157. }
  2158. if ((value = getSetting("pwrExpectedV", 0.0))) {
  2159. delSetting("pwrExpectedV");
  2160. sensor->expectedVoltage(value);
  2161. setSetting(_magnitudeSettingsRatioKey(MAGNITUDE_VOLTAGE, 0), sensor->getVoltageRatio());
  2162. }
  2163. if ((value = getSetting("pwrExpectedP", 0.0))) {
  2164. delSetting("pwrExpectedP");
  2165. sensor->expectedPower(value);
  2166. setSetting(_magnitudeSettingsRatioKey(MAGNITUDE_POWER_ACTIVE, 0), sensor->getPowerRatio());
  2167. }
  2168. if (getSetting("pwrResetE", false)) {
  2169. delSetting("pwrResetE");
  2170. for (size_t index = 0; index < sensor->countDevices(); ++index) {
  2171. sensor->resetEnergy(index);
  2172. _sensorResetEnergyTotal(index);
  2173. }
  2174. }
  2175. if (getSetting("pwrResetCalibration", false)) {
  2176. delSetting("pwrResetCalibration");
  2177. delSetting(_magnitudeSettingsRatioKey(MAGNITUDE_CURRENT, 0));
  2178. delSetting(_magnitudeSettingsRatioKey(MAGNITUDE_VOLTAGE, 0));
  2179. delSetting(_magnitudeSettingsRatioKey(MAGNITUDE_ENERGY, 0));
  2180. sensor->resetRatios();
  2181. }
  2182. } // is emon?
  2183. }
  2184. // Update magnitude config, filter sizes and reset energy if needed
  2185. {
  2186. for (size_t index = 0; index < _magnitudes.size(); ++index) {
  2187. auto& magnitude = _magnitudes.at(index);
  2188. // process emon-specific settings first. ensure that settings use global index and we access sensor with the local one
  2189. if (_sensorIsEmon(magnitude.sensor)) {
  2190. // TODO: compatibility proxy, fetch global key before indexed
  2191. // TODO: *remove* local index, favour separate sensor instances instead of index magic
  2192. auto* sensor = static_cast<BaseEmonSensor*>(magnitude.sensor);
  2193. switch (magnitude.type) {
  2194. case MAGNITUDE_CURRENT:
  2195. sensor->setCurrentRatio(
  2196. magnitude.index_local, _magnitudeSettingsRatio(magnitude, sensor->defaultCurrentRatio()));
  2197. break;
  2198. case MAGNITUDE_POWER_ACTIVE:
  2199. sensor->setPowerRatio(
  2200. magnitude.index_local, _magnitudeSettingsRatio(magnitude, sensor->defaultPowerRatio()));
  2201. break;
  2202. case MAGNITUDE_VOLTAGE:
  2203. sensor->setVoltageRatio(
  2204. magnitude.index_local, _magnitudeSettingsRatio(magnitude, sensor->defaultVoltageRatio()));
  2205. break;
  2206. case MAGNITUDE_ENERGY:
  2207. sensor->setEnergyRatio(
  2208. magnitude.index_local, _magnitudeSettingsRatio(magnitude, sensor->defaultEnergyRatio()));
  2209. break;
  2210. default:
  2211. break;
  2212. }
  2213. }
  2214. // analog variant of emon sensor has some additional settings
  2215. if (_sensorIsAnalogEmon(magnitude.sensor) && magnitude.type == MAGNITUDE_VOLTAGE) {
  2216. auto* sensor = static_cast<BaseAnalogEmonSensor*>(magnitude.sensor);
  2217. sensor->setVoltage(
  2218. getSetting({_magnitudeSettingsKey(magnitude, F("Mains")), magnitude.index_global},
  2219. sensor->defaultVoltage()));
  2220. sensor->setReferenceVoltage(
  2221. getSetting({_magnitudeSettingsKey(magnitude, F("Reference")), magnitude.index_global},
  2222. sensor->defaultReferenceVoltage()));
  2223. }
  2224. // adjust type-specific units
  2225. {
  2226. const sensor::Unit default_unit { magnitude.sensor->units(magnitude.slot) };
  2227. const String key {
  2228. String(_magnitudeSettingsPrefix(magnitude.type)) + F("Units") + String(magnitude.index_global, 10) };
  2229. magnitude.units = _magnitudeUnitFilter(magnitude, getSetting(key, default_unit));
  2230. }
  2231. // some magnitudes allow to be corrected with an offset
  2232. {
  2233. if (_magnitudeCanUseCorrection(magnitude.type)) {
  2234. auto key = String(_magnitudeSettingsPrefix(magnitude.type)) + F("Correction");
  2235. magnitude.correction = getSetting({key, magnitude.index_global}, getSetting(key, _magnitudeCorrection(magnitude.type)));
  2236. }
  2237. }
  2238. // some sensors can override decimal values if sensor has more precision than default
  2239. {
  2240. signed char decimals = magnitude.sensor->decimals(magnitude.units);
  2241. if (decimals < 0) decimals = _sensorUnitDecimals(magnitude.units);
  2242. magnitude.decimals = (unsigned char) decimals;
  2243. }
  2244. // Per-magnitude min & max delta settings
  2245. // - min controls whether we report at all when report_count overflows
  2246. // - max will trigger report as soon as read value is greater than the specified delta
  2247. // (atm this works best for accumulated magnitudes, like energy)
  2248. {
  2249. auto min_default = 0.0;
  2250. auto max_default = 0.0;
  2251. switch (magnitude.type) {
  2252. case MAGNITUDE_TEMPERATURE:
  2253. min_default = tmp_min_delta;
  2254. break;
  2255. case MAGNITUDE_HUMIDITY:
  2256. min_default = hum_min_delta;
  2257. break;
  2258. case MAGNITUDE_ENERGY:
  2259. max_default = ene_max_delta;
  2260. break;
  2261. default:
  2262. break;
  2263. }
  2264. magnitude.min_change = getSetting(
  2265. {_magnitudeSettingsKey(magnitude, F("MinDelta")), magnitude.index_global},
  2266. min_default
  2267. );
  2268. magnitude.max_change = getSetting(
  2269. {_magnitudeSettingsKey(magnitude, F("MaxDelta")), magnitude.index_global},
  2270. max_default
  2271. );
  2272. }
  2273. // Sometimes we want to ensure the value is above certain threshold before reporting
  2274. {
  2275. magnitude.zero_threshold = getSetting(
  2276. {_magnitudeSettingsKey(magnitude, F("ZeroThreshold")), magnitude.index_global},
  2277. std::numeric_limits<double>::quiet_NaN()
  2278. );
  2279. }
  2280. // in case we don't save energy periodically, purge existing value in ram & settings
  2281. if ((MAGNITUDE_ENERGY == magnitude.type) && (0 == _sensor_save_every)) {
  2282. _sensorResetEnergyTotal(magnitude.index_global);
  2283. }
  2284. }
  2285. }
  2286. saveSettings();
  2287. }
  2288. } // namespace
  2289. // -----------------------------------------------------------------------------
  2290. // Public
  2291. // -----------------------------------------------------------------------------
  2292. void sensorOnMagnitudeRead(MagnitudeReadHandler handler) {
  2293. _magnitude_read_handlers.push_front(handler);
  2294. }
  2295. void sensorOnMagnitudeReport(MagnitudeReadHandler handler) {
  2296. _magnitude_report_handlers.push_front(handler);
  2297. }
  2298. unsigned char sensorCount() {
  2299. return _sensors.size();
  2300. }
  2301. unsigned char magnitudeCount() {
  2302. return _magnitudes.size();
  2303. }
  2304. unsigned char magnitudeType(unsigned char index) {
  2305. if (index < _magnitudes.size()) {
  2306. return _magnitudes[index].type;
  2307. }
  2308. return MAGNITUDE_NONE;
  2309. }
  2310. String magnitudeTopic(unsigned char type) {
  2311. return _magnitudeTopic(type);
  2312. }
  2313. double sensor::Value::get() {
  2314. return _sensor_realtime ? last : reported;
  2315. }
  2316. sensor::Value magnitudeValue(unsigned char index) {
  2317. sensor::Value result;
  2318. if (index >= _magnitudes.size()) {
  2319. result.last = std::numeric_limits<double>::quiet_NaN(),
  2320. result.reported = std::numeric_limits<double>::quiet_NaN(),
  2321. result.decimals = 0u;
  2322. return result;
  2323. }
  2324. auto& magnitude = _magnitudes[index];
  2325. result.last = magnitude.last;
  2326. result.reported = magnitude.reported;
  2327. result.decimals = magnitude.decimals;
  2328. return result;
  2329. }
  2330. void magnitudeFormat(const sensor::Value& value, char* out, size_t) {
  2331. // TODO: 'size' does not do anything, since dtostrf used here is expected to be 'sane', but
  2332. // it does not allow any size arguments besides for digits after the decimal point
  2333. dtostrf(
  2334. _sensor_realtime ? value.last : value.reported,
  2335. 1, value.decimals,
  2336. out
  2337. );
  2338. }
  2339. unsigned char magnitudeIndex(unsigned char index) {
  2340. if (index < _magnitudes.size()) {
  2341. return _magnitudes[index].index_global;
  2342. }
  2343. return 0;
  2344. }
  2345. String magnitudeDescription(unsigned char index) {
  2346. if (index < _magnitudes.size()) {
  2347. return _magnitudeDescription(_magnitudes[index]);
  2348. }
  2349. return String();
  2350. }
  2351. String magnitudeTopicIndex(unsigned char index) {
  2352. if (index < _magnitudes.size()) {
  2353. return _magnitudeTopicIndex(_magnitudes[index]);
  2354. }
  2355. return String();
  2356. }
  2357. // -----------------------------------------------------------------------------
  2358. namespace {
  2359. void _sensorSettingsMigrate(int version) {
  2360. // Some keys from older versions were longer
  2361. if (version < 3) {
  2362. moveSetting("powerUnits", "pwrUnits");
  2363. moveSetting("energyUnits", "eneUnits");
  2364. }
  2365. // Energy is now indexed (based on magnitude.index_global)
  2366. // Also update PZEM004T energy total across multiple devices
  2367. if (version < 5) {
  2368. moveSetting("eneTotal", "eneTotal0");
  2369. moveSettings("pzEneTotal", "eneTotal");
  2370. }
  2371. // Unit ID is no longer shared, drop when equal to Min_ or None
  2372. if (version < 5) {
  2373. delSetting("pwrUnits");
  2374. delSetting("eneUnits");
  2375. delSetting("tmpUnits");
  2376. }
  2377. // generic pwr settings have magnitude prefixes
  2378. if (version < 7) {
  2379. moveSetting(F("pwrVoltage"), _magnitudeSettingsKey(MAGNITUDE_VOLTAGE, F("Mains0")));
  2380. moveSetting(F("pwrRatioC"), _magnitudeSettingsRatioKey(MAGNITUDE_CURRENT, 0).value());
  2381. moveSetting(F("pwrRatioV"), _magnitudeSettingsRatioKey(MAGNITUDE_VOLTAGE, 0).value());
  2382. moveSetting(F("pwrRatioP"), _magnitudeSettingsRatioKey(MAGNITUDE_POWER_ACTIVE, 0).value());
  2383. moveSetting(F("pwrRatioE"), _magnitudeSettingsRatioKey(MAGNITUDE_ENERGY, 0).value());
  2384. }
  2385. #if HLW8012_SUPPORT
  2386. if (version < 9) {
  2387. moveSetting(F("snsHlw8012SelGPIO"), F("hlw8012SEL"));
  2388. moveSetting(F("snsHlw8012CfGPIO"), F("hlw8012CF"));
  2389. moveSetting(F("snsHlw8012Cf1GPIO"), F("hlw8012CF1"));
  2390. }
  2391. #endif
  2392. }
  2393. } // namespace
  2394. void sensorSetup() {
  2395. // Settings backwards compatibility
  2396. migrateVersion(_sensorSettingsMigrate);
  2397. // Load configured sensors and set up all of magnitudes
  2398. _sensorLoad();
  2399. _sensorInit();
  2400. // Configure based on settings
  2401. _sensorConfigure();
  2402. // Allow us to query key default
  2403. settingsRegisterDefaults("pwr", _sensorQueryDefault);
  2404. // Websockets integration, send sensor readings and configuration
  2405. #if WEB_SUPPORT
  2406. wsRegister()
  2407. .onVisible(_sensorWebSocketOnVisible)
  2408. .onConnected(_sensorWebSocketOnConnected)
  2409. .onData(_sensorWebSocketSendData)
  2410. .onKeyCheck(_sensorWebSocketOnKeyCheck);
  2411. #endif
  2412. // MQTT receive callback, atm only for energy reset
  2413. #if MQTT_SUPPORT
  2414. mqttRegister(_sensorMqttCallback);
  2415. #endif
  2416. // API
  2417. #if API_SUPPORT
  2418. _sensorApiSetup();
  2419. #endif
  2420. // Terminal
  2421. #if TERMINAL_SUPPORT
  2422. _sensorInitCommands();
  2423. #endif
  2424. // Main callbacks
  2425. espurnaRegisterLoop(sensorLoop);
  2426. espurnaRegisterReload(_sensorConfigure);
  2427. }
  2428. void sensorLoop() {
  2429. // Check if we still have uninitialized sensors
  2430. static unsigned long last_init = 0;
  2431. if (!_sensors_ready) {
  2432. if (millis() - last_init > SENSOR_INIT_INTERVAL) {
  2433. last_init = millis();
  2434. _sensorInit();
  2435. }
  2436. }
  2437. if (_magnitudes.size() == 0) return;
  2438. // Tick hook, called every loop()
  2439. _sensorTick();
  2440. // Check if we should read new data
  2441. static unsigned long last_update = 0;
  2442. static unsigned long report_count = 0;
  2443. if (millis() - last_update > _sensor_read_interval) {
  2444. last_update = millis();
  2445. report_count = (report_count + 1) % _sensor_report_every;
  2446. double value_raw; // holds the raw value as the sensor returns it
  2447. double value_show; // holds the processed value applying units and decimals
  2448. double value_filtered; // holds the processed value applying filters, and the units and decimals
  2449. // Pre-read hook, called every reading
  2450. _sensorPre();
  2451. // Get the first relay state
  2452. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2453. const bool relay_off = (relayCount() == 1) && (relayStatus(0) == 0);
  2454. #endif
  2455. // Get readings
  2456. for (unsigned char magnitude_index = 0; magnitude_index < _magnitudes.size(); ++magnitude_index) {
  2457. auto& magnitude = _magnitudes[magnitude_index];
  2458. if (!magnitude.sensor->status()) continue;
  2459. // -------------------------------------------------------------
  2460. // Instant value
  2461. // -------------------------------------------------------------
  2462. value_raw = magnitude.sensor->value(magnitude.slot);
  2463. // Completely remove spurious values if relay is OFF
  2464. #if RELAY_SUPPORT && SENSOR_POWER_CHECK_STATUS
  2465. switch (magnitude.type) {
  2466. case MAGNITUDE_POWER_ACTIVE:
  2467. case MAGNITUDE_POWER_REACTIVE:
  2468. case MAGNITUDE_POWER_APPARENT:
  2469. case MAGNITUDE_POWER_FACTOR:
  2470. case MAGNITUDE_CURRENT:
  2471. case MAGNITUDE_ENERGY_DELTA:
  2472. if (relay_off) {
  2473. value_raw = 0.0;
  2474. }
  2475. break;
  2476. default:
  2477. break;
  2478. }
  2479. #endif
  2480. // In addition to that, we also check that value is above a certain threshold
  2481. if ((!std::isnan(magnitude.zero_threshold)) && ((value_raw < magnitude.zero_threshold))) {
  2482. value_raw = 0.0;
  2483. }
  2484. magnitude.last = value_raw;
  2485. magnitude.filter->add(value_raw);
  2486. // -------------------------------------------------------------
  2487. // Procesing (units and decimals)
  2488. // -------------------------------------------------------------
  2489. value_show = _magnitudeProcess(magnitude, value_raw);
  2490. {
  2491. char buffer[64];
  2492. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2493. for (auto& handler : _magnitude_read_handlers) {
  2494. handler(_magnitudeTopic(magnitude.type), magnitude.index_global, value_show, buffer);
  2495. }
  2496. }
  2497. // -------------------------------------------------------------
  2498. // Debug
  2499. // -------------------------------------------------------------
  2500. #if SENSOR_DEBUG
  2501. {
  2502. char buffer[64];
  2503. dtostrf(value_show, 1, magnitude.decimals, buffer);
  2504. DEBUG_MSG_P(PSTR("[SENSOR] %s - %s: %s%s\n"),
  2505. _magnitudeDescription(magnitude).c_str(),
  2506. _magnitudeTopic(magnitude.type).c_str(),
  2507. buffer,
  2508. _magnitudeUnits(magnitude).c_str()
  2509. );
  2510. }
  2511. #endif
  2512. // -------------------------------------------------------------------
  2513. // Report when
  2514. // - report_count overflows after reaching _sensor_report_every
  2515. // - when magnitude specifies max_change and we greater or equal to it
  2516. // -------------------------------------------------------------------
  2517. bool report = (0 == report_count);
  2518. if (!std::isnan(magnitude.reported) && (magnitude.max_change > 0)) {
  2519. report = (std::abs(value_show - magnitude.reported) >= magnitude.max_change);
  2520. }
  2521. // Special case for energy, save readings to RAM and EEPROM
  2522. if (MAGNITUDE_ENERGY == magnitude.type) {
  2523. _magnitudeSaveEnergyTotal(magnitude, report);
  2524. }
  2525. if (report) {
  2526. value_filtered = _magnitudeProcess(magnitude, magnitude.filter->result());
  2527. magnitude.filter->reset();
  2528. if (magnitude.filter->size() != _sensor_report_every) {
  2529. magnitude.filter->resize(_sensor_report_every);
  2530. }
  2531. // Check if there is a minimum change threshold to report
  2532. if (std::isnan(magnitude.reported) || (std::abs(value_filtered - magnitude.reported) >= magnitude.min_change)) {
  2533. magnitude.reported = value_filtered;
  2534. _sensorReport(magnitude_index, magnitude);
  2535. }
  2536. } // if (report_count == 0)
  2537. }
  2538. // Post-read hook, called every reading
  2539. _sensorPost();
  2540. // And report data to modules that don't specifically track them
  2541. #if WEB_SUPPORT
  2542. wsPost(_sensorWebSocketSendData);
  2543. #endif
  2544. #if THINGSPEAK_SUPPORT
  2545. if (report_count == 0) tspkFlush();
  2546. #endif
  2547. }
  2548. }
  2549. #endif // SENSOR_SUPPORT