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

2453 lines
71 KiB

8 years ago
7 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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 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
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
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
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
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
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
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
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
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
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
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
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
8 years ago
8 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 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
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
6 years ago
6 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
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
6 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
  1. var debug = false;
  2. var websock;
  3. var password = false;
  4. var maxNetworks;
  5. var messages = [];
  6. var free_size = 0;
  7. var urls = {};
  8. var numChanged = 0;
  9. var numReboot = 0;
  10. var numReconnect = 0;
  11. var numReload = 0;
  12. var configurationSaved = false;
  13. var ws_pingpong;
  14. //removeIf(!light)
  15. var colorPicker;
  16. var useWhite = false;
  17. var useCCT = false;
  18. //endRemoveIf(!light)
  19. var now = 0;
  20. var ago = 0;
  21. //removeIf(!rfm69)
  22. var packets;
  23. var filters = [];
  24. //endRemoveIf(!rfm69)
  25. //removeIf(!sensor)
  26. var Magnitudes = [];
  27. var MagnitudeErrors = {};
  28. var MagnitudeNames = {};
  29. var MagnitudeTypePrefixes = {};
  30. var MagnitudePrefixTypes = {};
  31. //endRemoveIf(!sensor)
  32. // -----------------------------------------------------------------------------
  33. // Messages
  34. // -----------------------------------------------------------------------------
  35. function initMessages() {
  36. messages[1] = "Remote update started";
  37. messages[2] = "OTA update started";
  38. messages[3] = "Error parsing data!";
  39. messages[4] = "The file does not look like a valid configuration backup or is corrupted";
  40. messages[5] = "Changes saved. You should reboot your board now";
  41. messages[7] = "Passwords do not match!";
  42. messages[8] = "Changes saved";
  43. messages[9] = "No changes detected";
  44. messages[10] = "Session expired, please reload page...";
  45. }
  46. // -----------------------------------------------------------------------------
  47. // Utils
  48. // -----------------------------------------------------------------------------
  49. $.fn.enterKey = function (fnc) {
  50. return this.each(function () {
  51. $(this).keypress(function (ev) {
  52. var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
  53. if (13 === keycode) {
  54. return fnc.call(this, ev);
  55. }
  56. });
  57. });
  58. };
  59. function followScroll(id, threshold) {
  60. if (threshold === undefined) {
  61. threshold = 90;
  62. }
  63. var elem = document.getElementById(id);
  64. var offset = (elem.scrollTop + elem.offsetHeight) / elem.scrollHeight * 100;
  65. if (offset > threshold) {
  66. elem.scrollTop = elem.scrollHeight;
  67. }
  68. }
  69. function fromSchema(source, schema) {
  70. if (schema.length !== source.length) {
  71. throw "Schema mismatch!";
  72. }
  73. var target = {};
  74. schema.forEach(function(key, index) {
  75. target[key] = source[index];
  76. });
  77. return target;
  78. }
  79. function keepTime() {
  80. $("span[name='ago']").html(ago);
  81. ago++;
  82. if (0 === now) { return; }
  83. var date = new Date(now * 1000);
  84. var text = date.toISOString().substring(0, 19).replace("T", " ");
  85. $("input[name='now']").val(text);
  86. $("span[name='now']").html(text);
  87. now++;
  88. }
  89. function zeroPad(number, positions) {
  90. return number.toString().padStart(positions, "0");
  91. }
  92. function validatePassword(password) {
  93. // http://www.the-art-of-web.com/javascript/validate-password/
  94. // at least one lowercase and one uppercase letter or number
  95. // at least eight characters (letters, numbers or special characters)
  96. // MUST be 8..63 printable ASCII characters. See:
  97. // https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
  98. // https://github.com/xoseperez/espurna/issues/1151
  99. var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
  100. return (
  101. (password !== undefined)
  102. && (typeof password === "string")
  103. && (password.length > 0)
  104. && re_password.test(password)
  105. );
  106. }
  107. function validateFormPasswords(form) {
  108. var passwords = $("input[name='adminPass1'],input[name='adminPass2']", form);
  109. var adminPass1 = passwords.first().val(),
  110. adminPass2 = passwords.last().val();
  111. var formValidity = passwords.first()[0].checkValidity();
  112. if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
  113. return true;
  114. }
  115. var validPass1 = validatePassword(adminPass1),
  116. validPass2 = validatePassword(adminPass2);
  117. if (formValidity && validPass1 && validPass2) {
  118. return true;
  119. }
  120. if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
  121. alert("The password you have entered is not valid, it must be 8..63 characters and have at least 1 lowercase and 1 uppercase / number!");
  122. }
  123. if (adminPass1 !== adminPass2) {
  124. alert("Passwords are different!");
  125. }
  126. return false;
  127. }
  128. function validateFormHostname(form) {
  129. // RFCs mandate that a hostname's labels may contain only
  130. // the ASCII letters 'a' through 'z' (case-insensitive),
  131. // the digits '0' through '9', and the hyphen.
  132. // Hostname labels cannot begin or end with a hyphen.
  133. // No other symbols, punctuation characters, or blank spaces are permitted.
  134. // Negative lookbehind does not work in Javascript
  135. // var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,32}(?<!-)$');
  136. var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,31}[A-Za-z0-9]$');
  137. var hostname = $("input[name='hostname']", form);
  138. if ("true" !== hostname.attr("hasChanged")) {
  139. return true;
  140. }
  141. if (re_hostname.test(hostname.val())) {
  142. return true;
  143. }
  144. alert("Hostname cannot be empty and may only contain the ASCII letters ('A' through 'Z' and 'a' through 'z'), the digits '0' through '9', and the hyphen ('-')! They can neither start or end with an hyphen.");
  145. return false;
  146. }
  147. function validateForm(form) {
  148. return validateFormPasswords(form) && validateFormHostname(form);
  149. }
  150. // Observe all group settings to selectively update originals based on the current data
  151. var groupSettingsObserver = new MutationObserver(function(mutations) {
  152. mutations.forEach(function(mutation) {
  153. // If any new elements are added, set "settings-target" element as changed to forcibly send the data
  154. var targets = $(mutation.target).attr("data-settings-target");
  155. if (targets !== undefined) {
  156. mutation.addedNodes.forEach(function(node) {
  157. var overrides = [];
  158. targets.split(" ").forEach(function(target) {
  159. var elem = $("[name='" + target + "']", node);
  160. if (!elem.length) return;
  161. var value = getValue(elem);
  162. if ((value === null) || (value === elem[0].defaultValue)) {
  163. overrides.push(elem);
  164. }
  165. });
  166. setOriginalsFromValues($("input,select", node));
  167. overrides.forEach(function(elem) {
  168. elem.attr("hasChanged", "true");
  169. if (elem.prop("tagName") === "SELECT") {
  170. elem.prop("value", 0);
  171. }
  172. });
  173. });
  174. }
  175. // If anything was removed, forcibly send **all** of the group to avoid having any outdated keys
  176. // TODO: hide instead of remove?
  177. var changed = $(mutation.target).attr("hasChanged") === "true";
  178. if (changed || mutation.removedNodes.length) {
  179. $(mutation.target).attr("hasChanged", "true");
  180. $("input,select", mutation.target.childNodes).attr("hasChanged", "true");
  181. }
  182. });
  183. });
  184. // These fields will always be a list of values
  185. function isGroupValue(value) {
  186. var names = [
  187. "ssid", "pass", "gw", "mask", "ip", "dns",
  188. "schEnabled", "schSwitch","schAction","schType","schHour","schMinute","schWDs","schUTC",
  189. "relayBoot", "relayPulse", "relayTime", "relayLastSch",
  190. "mqttGroup", "mqttGroupSync", "relayOnDisc",
  191. "dczRelayIdx", "dczMagnitude",
  192. "tspkRelay", "tspkMagnitude",
  193. "ledGPIO", "ledMode", "ledRelay",
  194. "adminPass",
  195. "node", "key", "topic",
  196. "rpnRule", "rpnTopic", "rpnName"
  197. ];
  198. return names.indexOf(value) >= 0;
  199. }
  200. function getValue(element) {
  201. if ($(element).attr("type") === "checkbox") {
  202. return $(element).prop("checked") ? 1 : 0;
  203. } else if ($(element).attr("type") === "radio") {
  204. if (!$(element).prop("checked")) {
  205. return null;
  206. }
  207. }
  208. return $(element).val();
  209. }
  210. function addValue(data, name, value) {
  211. if (name in data) {
  212. if (!Array.isArray(data[name])) {
  213. data[name] = [data[name]];
  214. }
  215. data[name].push(value);
  216. } else if (isGroupValue(name)) {
  217. data[name] = [value];
  218. } else {
  219. data[name] = value;
  220. }
  221. }
  222. function getData(form, changed, cleanup) {
  223. // Populate two sets of data, ones that had been changed and ones that stayed the same
  224. var data = {};
  225. var changed_data = [];
  226. if (cleanup === undefined) {
  227. cleanup = true;
  228. }
  229. if (changed === undefined) {
  230. changed = true;
  231. }
  232. $("input,select", form).each(function() {
  233. if ($(this).attr("data-settings-ignore") === "true") {
  234. return;
  235. }
  236. var name = $(this).attr("name");
  237. var real_name = $(this).attr("data-settings-real-name");
  238. if (real_name !== undefined) {
  239. name = real_name;
  240. }
  241. var value = getValue(this);
  242. if (null !== value) {
  243. var haschanged = ("true" === $(this).attr("hasChanged"));
  244. var indexed = changed_data.indexOf(name) >= 0;
  245. if ((haschanged || !changed) && !indexed) {
  246. changed_data.push(name);
  247. }
  248. addValue(data, name, value);
  249. }
  250. });
  251. // Finally, filter out only fields that had changed.
  252. // Note: We need to preserve dynamic lists like schedules, wifi etc.
  253. // so we don't accidentally break when user deletes entry in the middle
  254. var resulting_data = {};
  255. for (var value in data) {
  256. if (changed_data.indexOf(value) >= 0) {
  257. resulting_data[value] = data[value];
  258. }
  259. }
  260. // Hack: clean-up leftover arrays.
  261. // When empty, the receiving side will prune all keys greater than the current one.
  262. if (cleanup) {
  263. $(".group-settings").each(function() {
  264. var haschanged = ("true" === $(this).attr("hasChanged"));
  265. if (haschanged && !this.children.length) {
  266. var targets = this.dataset.settingsTarget;
  267. if (targets === undefined) return;
  268. targets.split(" ").forEach(function(target) {
  269. resulting_data[target] = [];
  270. });
  271. }
  272. });
  273. }
  274. return resulting_data;
  275. }
  276. function randomString(length, args) {
  277. if (typeof args === "undefined") {
  278. args = {
  279. lowercase: true,
  280. uppercase: true,
  281. numbers: true,
  282. special: true
  283. }
  284. }
  285. var mask = "";
  286. if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
  287. if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
  288. if (args.numbers || args.hex) { mask += "0123456789"; }
  289. if (args.hex) { mask += "ABCDEF"; }
  290. if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
  291. var source = new Uint32Array(length);
  292. var result = new Array(length);
  293. window.crypto.getRandomValues(source).forEach(function(value, i) {
  294. result[i] = mask[value % mask.length];
  295. });
  296. return result.join("");
  297. }
  298. function generateAPIKey() {
  299. var apikey = randomString(16, {hex: true});
  300. $("input[name='apiKey']")
  301. .val(apikey)
  302. .attr("original", "-".repeat(16))
  303. .attr("haschanged", "true");
  304. return false;
  305. }
  306. function generatePassword() {
  307. var password = "";
  308. do {
  309. password = randomString(10);
  310. } while (!validatePassword(password));
  311. return password;
  312. }
  313. function toggleVisiblePassword() {
  314. var elem = this.previousElementSibling;
  315. if (elem.type === "password") {
  316. elem.type = "text";
  317. } else {
  318. elem.type = "password";
  319. }
  320. return false;
  321. }
  322. function doGeneratePassword() {
  323. var elems = $("input", $("#formPassword"));
  324. elems
  325. .val(generatePassword())
  326. .attr("haschanged", "true")
  327. .each(function() {
  328. this.type = "text";
  329. });
  330. return false;
  331. }
  332. function getJson(str) {
  333. try {
  334. return JSON.parse(str);
  335. } catch (e) {
  336. return false;
  337. }
  338. }
  339. function moduleVisible(module) {
  340. if (module == "sch") {
  341. $("li.module-" + module).css("display", "inherit");
  342. $("div.module-" + module).css("display", "flex");
  343. return;
  344. }
  345. $(".module-" + module).css("display", "inherit");
  346. }
  347. //removeIf(!thermostat)
  348. function checkTempRangeMin() {
  349. var min = parseInt($("#tempRangeMinInput").val(), 10);
  350. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  351. if (min > max - 1) {
  352. $("#tempRangeMinInput").val(max - 1);
  353. }
  354. }
  355. function checkTempRangeMax() {
  356. var min = parseInt($("#tempRangeMinInput").val(), 10);
  357. var max = parseInt($("#tempRangeMaxInput").val(), 10);
  358. if (max < min + 1) {
  359. $("#tempRangeMaxInput").val(min + 1);
  360. }
  361. }
  362. function doResetThermostatCounters(ask) {
  363. var question = (typeof ask === "undefined" || false === ask) ?
  364. null :
  365. "Are you sure you want to reset burning counters?";
  366. return doAction(question, "thermostat_reset_counters");
  367. }
  368. //endRemoveIf(!thermostat)
  369. function initSelectGPIO(select) {
  370. // TODO: properly lock used GPIOs via locking and apply the mask here
  371. var mapping = [
  372. [153, "NONE"],
  373. [0, "0 (FLASH)"],
  374. [1, "1 (U0TXD)"],
  375. [2, "2 (U1TXD)"],
  376. [3, "3 (U0RXD)"],
  377. [4, "4 (SDA)"],
  378. [5, "5 (SCL)"],
  379. [9, "9 (SDD2)"],
  380. [10, "10 (SDD3)"],
  381. [12, "12 (MTDI)"],
  382. [13, "13 (MTCK)"],
  383. [14, "14 (MTMS)"],
  384. [15, "15 (MTDO)"],
  385. [16, "16 (WAKE)"],
  386. ];
  387. for (n in mapping) {
  388. var elem = $('<option value="' + mapping[n][0] + '">');
  389. elem.html(mapping[n][1]);
  390. elem.appendTo(select);
  391. }
  392. }
  393. // -----------------------------------------------------------------------------
  394. // Actions
  395. // -----------------------------------------------------------------------------
  396. function send(json) {
  397. if (debug) console.log(json);
  398. websock.send(json);
  399. }
  400. function sendAction(action, data) {
  401. send(JSON.stringify({action: action, data: data}));
  402. }
  403. function sendConfig(data) {
  404. send(JSON.stringify({config: data}));
  405. }
  406. function setOriginalsFromValues(elems) {
  407. if (typeof elems == "undefined") {
  408. elems = $("input,select");
  409. }
  410. elems.each(function() {
  411. var value;
  412. if ($(this).attr("type") === "checkbox") {
  413. value = $(this).prop("checked");
  414. } else {
  415. value = $(this).val();
  416. }
  417. $(this).attr("original", value);
  418. hasChanged.call(this);
  419. });
  420. }
  421. function resetOriginals() {
  422. setOriginalsFromValues();
  423. $(".group-settings").attr("haschanged", "false")
  424. numReboot = numReconnect = numReload = 0;
  425. configurationSaved = false;
  426. }
  427. function doReload(milliseconds) {
  428. setTimeout(function() {
  429. window.location.reload();
  430. }, parseInt(milliseconds, 10));
  431. }
  432. /**
  433. * Check a file object to see if it is a valid firmware image
  434. * The file first byte should be 0xE9
  435. * @param {file} file File object
  436. * @param {Function} callback Function to call back with the result
  437. */
  438. function checkFirmware(file, callback) {
  439. var reader = new FileReader();
  440. reader.onloadend = function(evt) {
  441. if (FileReader.DONE === evt.target.readyState) {
  442. var magic = evt.target.result.charCodeAt(0);
  443. if ((0x1F === magic) && (0x8B === evt.target.result.charCodeAt(1))) {
  444. callback(true);
  445. return;
  446. }
  447. if (0xE9 !== magic) {
  448. alert("Binary image does not start with a magic byte");
  449. callback(false);
  450. return;
  451. }
  452. var modes = ['QIO', 'QOUT', 'DIO', 'DOUT'];
  453. var flash_mode = evt.target.result.charCodeAt(2);
  454. if (0x03 !== flash_mode) {
  455. var response = window.confirm("Binary image is using " + modes[flash_mode] + " flash mode! Make sure that the device supports it before proceeding.");
  456. callback(response);
  457. } else {
  458. callback(true);
  459. }
  460. }
  461. };
  462. var blob = file.slice(0, 3);
  463. reader.readAsBinaryString(blob);
  464. }
  465. function doUpgrade() {
  466. var file = $("input[name='upgrade']")[0].files[0];
  467. if (typeof file === "undefined") {
  468. alert("First you have to select a file from your computer.");
  469. return false;
  470. }
  471. if (file.size > free_size) {
  472. alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
  473. return false;
  474. }
  475. checkFirmware(file, function(ok) {
  476. if (!ok) {
  477. return;
  478. }
  479. var data = new FormData();
  480. data.append("upgrade", file, file.name);
  481. var xhr = new XMLHttpRequest();
  482. var msg_ok = "Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.";
  483. var msg_err = "There was an error trying to upload the new image, please try again: ";
  484. var network_error = function(e) {
  485. alert(msg_err + " xhr request " + e.type);
  486. };
  487. xhr.addEventListener("error", network_error, false);
  488. xhr.addEventListener("abort", network_error, false);
  489. xhr.addEventListener("load", function(e) {
  490. $("#upgrade-progress").hide();
  491. if ("OK" === xhr.responseText) {
  492. alert(msg_ok);
  493. doReload(5000);
  494. } else {
  495. alert(msg_err + xhr.status.toString() + " " + xhr.statusText + ", " + xhr.responseText);
  496. }
  497. }, false);
  498. xhr.upload.addEventListener("progress", function(e) {
  499. $("#upgrade-progress").show();
  500. if (e.lengthComputable) {
  501. $("progress").attr({ value: e.loaded, max: e.total });
  502. }
  503. }, false);
  504. xhr.open("POST", urls.upgrade.href);
  505. xhr.send(data);
  506. });
  507. return false;
  508. }
  509. function doUpdatePassword() {
  510. var form = $("#formPassword");
  511. if (validateFormPasswords(form)) {
  512. sendConfig(getData(form, true, false));
  513. }
  514. return false;
  515. }
  516. function checkChanges() {
  517. if (numChanged > 0) {
  518. var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
  519. if (response) {
  520. doUpdate();
  521. }
  522. }
  523. }
  524. function doAction(question, action) {
  525. checkChanges();
  526. if (question) {
  527. var response = window.confirm(question);
  528. if (false === response) {
  529. return false;
  530. }
  531. }
  532. sendAction(action, {});
  533. doReload(5000);
  534. return false;
  535. }
  536. function doReboot(ask) {
  537. var question = (typeof ask === "undefined" || false === ask) ?
  538. null :
  539. "Are you sure you want to reboot the device?";
  540. return doAction(question, "reboot");
  541. }
  542. function doReconnect(ask) {
  543. var question = (typeof ask === "undefined" || false === ask) ?
  544. null :
  545. "Are you sure you want to disconnect from the current WIFI network?";
  546. return doAction(question, "reconnect");
  547. }
  548. function doCheckOriginals() {
  549. var response;
  550. if (numReboot > 0) {
  551. response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
  552. if (response) { doReboot(false); }
  553. } else if (numReconnect > 0) {
  554. response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
  555. if (response) { doReconnect(false); }
  556. } else if (numReload > 0) {
  557. response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
  558. if (response) { doReload(0); }
  559. }
  560. resetOriginals();
  561. }
  562. function waitForSave(){
  563. if (!configurationSaved) {
  564. setTimeout(waitForSave, 1000);
  565. } else {
  566. doCheckOriginals();
  567. }
  568. }
  569. function doUpdate() {
  570. var forms = $(".form-settings");
  571. if (validateForm(forms)) {
  572. // Get data
  573. sendConfig(getData(forms));
  574. // Empty special fields
  575. $(".pwrExpected").val(0);
  576. $("input[name='snsResetCalibration']").prop("checked", false);
  577. $("input[name='pwrResetCalibration']").prop("checked", false);
  578. $("input[name='pwrResetE']").prop("checked", false);
  579. // Change handling
  580. numChanged = 0;
  581. waitForSave();
  582. }
  583. return false;
  584. }
  585. function doBackup() {
  586. document.getElementById("downloader").src = urls.config.href;
  587. return false;
  588. }
  589. function onFileUpload(event) {
  590. var inputFiles = this.files;
  591. if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
  592. return false;
  593. }
  594. var inputFile = inputFiles[0];
  595. this.value = "";
  596. var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
  597. if (!response) {
  598. return false;
  599. }
  600. var reader = new FileReader();
  601. reader.onload = function(e) {
  602. var data = getJson(e.target.result);
  603. if (data) {
  604. sendAction("restore", data);
  605. } else {
  606. window.alert(messages[4]);
  607. }
  608. };
  609. reader.readAsText(inputFile);
  610. return false;
  611. }
  612. function doRestore() {
  613. if (typeof window.FileReader !== "function") {
  614. alert("The file API isn't supported on this browser yet.");
  615. } else {
  616. $("#uploader").click();
  617. }
  618. return false;
  619. }
  620. function doFactoryReset() {
  621. var response = window.confirm("Are you sure you want to restore to factory settings?");
  622. if (!response) {
  623. return false;
  624. }
  625. sendAction("factory_reset", {});
  626. doReload(5000);
  627. return false;
  628. }
  629. function doToggle(id, value) {
  630. sendAction("relay", {id: id, status: value ? 1 : 0 });
  631. return false;
  632. }
  633. function doScan() {
  634. $("#scanResult").html("");
  635. $("div.scan.loading").show();
  636. $("#button-wifi-scan").attr("disabled", true);
  637. sendAction("scan", {});
  638. return false;
  639. }
  640. function doHAConfig() {
  641. $("#haConfig")
  642. .text("")
  643. .height(0)
  644. .show();
  645. sendAction("haconfig", {});
  646. return false;
  647. }
  648. function doDebugCommand() {
  649. var el = $("input[name='dbgcmd']");
  650. var command = el.val();
  651. el.val("");
  652. sendAction("dbgcmd", {command: command});
  653. followScroll("weblog", 0);
  654. return false;
  655. }
  656. function doDebugClear() {
  657. $("#weblog").text("");
  658. return false;
  659. }
  660. //removeIf(!rfm69)
  661. function doClearCounts() {
  662. sendAction("clear-counts", {});
  663. return false;
  664. }
  665. function doClearMessages() {
  666. packets.clear().draw(false);
  667. return false;
  668. }
  669. function doFilter(e) {
  670. var index = packets.cell(this).index();
  671. if (index == 'undefined') return;
  672. var c = index.column;
  673. var column = packets.column(c);
  674. if (filters[c]) {
  675. filters[c] = false;
  676. column.search("");
  677. $(column.header()).removeClass("filtered");
  678. } else {
  679. filters[c] = true;
  680. var data = packets.row(this).data();
  681. if (e.which == 1) {
  682. column.search('^' + data[c] + '$', true, false );
  683. } else {
  684. column.search('^((?!(' + data[c] + ')).)*$', true, false );
  685. }
  686. $(column.header()).addClass("filtered");
  687. }
  688. column.draw();
  689. return false;
  690. }
  691. function doClearFilters() {
  692. for (var i = 0; i < packets.columns()[0].length; i++) {
  693. if (filters[i]) {
  694. filters[i] = false;
  695. var column = packets.column(i);
  696. column.search("");
  697. $(column.header()).removeClass("filtered");
  698. column.draw();
  699. }
  700. }
  701. return false;
  702. }
  703. //endRemoveIf(!rfm69)
  704. function delParent() {
  705. var parent = $(this).parent().parent();
  706. $(parent).remove();
  707. }
  708. // -----------------------------------------------------------------------------
  709. // Visualization
  710. // -----------------------------------------------------------------------------
  711. function toggleMenu() {
  712. $("#layout").toggleClass("active");
  713. $("#menu").toggleClass("active");
  714. $("#menuLink").toggleClass("active");
  715. }
  716. function showPanel() {
  717. $(".panel").hide();
  718. if ($("#layout").hasClass("active")) { toggleMenu(); }
  719. $("#" + $(this).attr("data")).show();
  720. }
  721. // -----------------------------------------------------------------------------
  722. // Relays & magnitudes mapping
  723. // -----------------------------------------------------------------------------
  724. function createRelayList(data, container, template_name) {
  725. var current = $("#" + container + " > div").length;
  726. if (current > 0) { return; }
  727. var template = $("#" + template_name + " .pure-g")[0];
  728. for (var i in data) {
  729. var line = $(template).clone();
  730. $("label", line).html("Switch #" + i);
  731. $("input", line).attr("tabindex", 40 + i).val(data[i]);
  732. setOriginalsFromValues($("input", line));
  733. line.appendTo("#" + container);
  734. }
  735. }
  736. //removeIf(!sensor)
  737. function createMagnitudeList(data, container, template_name) {
  738. var current = $("#" + container + " > div").length;
  739. if (current > 0) { return; }
  740. var template = $("#" + template_name + " .pure-g")[0];
  741. var size = data.size;
  742. for (var i=0; i<size; ++i) {
  743. var line = $(template).clone();
  744. $("label", line).html(MagnitudeNames[data.type[i]] + " #" + parseInt(data.index[i], 10));
  745. $("div.hint", line).html(Magnitudes[i].description);
  746. $("input", line).attr("tabindex", 40 + i).val(data.idx[i]);
  747. setOriginalsFromValues($("input", line));
  748. line.appendTo("#" + container);
  749. }
  750. }
  751. //endRemoveIf(!sensor)
  752. // -----------------------------------------------------------------------------
  753. // RPN Rules
  754. // -----------------------------------------------------------------------------
  755. function addRPNRule() {
  756. var template = $("#rpnRuleTemplate .pure-g")[0];
  757. var line = $(template).clone();
  758. var tabindex = $("#rpnRules > div").length + 100;
  759. $(line).find("input").each(function() {
  760. $(this).attr("tabindex", tabindex++);
  761. });
  762. $(line).find("button").on('click', delParent);
  763. setOriginalsFromValues($("input", line));
  764. line.appendTo("#rpnRules");
  765. }
  766. function addRPNTopic() {
  767. var template = $("#rpnTopicTemplate .pure-g")[0];
  768. var line = $(template).clone();
  769. var tabindex = $("#rpnTopics > div").length + 120;
  770. $(line).find("input").each(function() {
  771. $(this).attr("tabindex", tabindex++);
  772. });
  773. $(line).find("button").on('click', delParent);
  774. setOriginalsFromValues($("input", line));
  775. line.appendTo("#rpnTopics");
  776. }
  777. // -----------------------------------------------------------------------------
  778. // RFM69
  779. // -----------------------------------------------------------------------------
  780. //removeIf(!rfm69)
  781. function addMapping() {
  782. var template = $("#nodeTemplate .pure-g")[0];
  783. var line = $(template).clone();
  784. var tabindex = $("#mapping > div").length * 3 + 50;
  785. $(line).find("input").each(function() {
  786. $(this).attr("tabindex", tabindex++);
  787. });
  788. $(line).find("button").on('click', delParent);
  789. setOriginalsFromValues($("input", line));
  790. line.appendTo("#mapping");
  791. }
  792. //endRemoveIf(!rfm69)
  793. // -----------------------------------------------------------------------------
  794. // Wifi
  795. // -----------------------------------------------------------------------------
  796. function numNetworks() {
  797. return $("#networks > div").length;
  798. }
  799. function delNetwork() {
  800. var parent = $(this).parents(".pure-g");
  801. $(parent).remove();
  802. }
  803. function moreNetwork() {
  804. var parent = $(this).parents(".pure-g");
  805. $(".more", parent).toggle();
  806. }
  807. function addNetwork(network) {
  808. var number = numNetworks();
  809. if (number >= maxNetworks) {
  810. alert("Max number of networks reached");
  811. return null;
  812. }
  813. if (network === undefined) {
  814. network = {};
  815. }
  816. var tabindex = 200 + number * 10;
  817. var template = $("#networkTemplate").children();
  818. var line = $(template).clone();
  819. $(line).find("input").each(function() {
  820. $(this).attr("tabindex", tabindex);
  821. tabindex++;
  822. });
  823. $(".password-reveal", line).on("click", toggleVisiblePassword);
  824. $(line).find(".button-del-network").on("click", delNetwork);
  825. $(line).find(".button-more-network").on("click", moreNetwork);
  826. Object.entries(network).forEach(function(pair) {
  827. // XXX: UI deleting this network will only re-use stored values.
  828. var key = pair[0],
  829. val = pair[1];
  830. if (key === "stored") {
  831. $(line).find(".button-del-network").prop("disabled", val);
  832. return;
  833. }
  834. $("input[name='" + key + "']", line).val(val);
  835. });
  836. line.appendTo("#networks");
  837. return line;
  838. }
  839. // -----------------------------------------------------------------------------
  840. // Relays scheduler
  841. // -----------------------------------------------------------------------------
  842. function numSchedules() {
  843. return $("#schedules > div").length;
  844. }
  845. function maxSchedules() {
  846. var value = $("#schedules").attr("data-settings-max");
  847. return parseInt(value === undefined ? 0 : value, 10);
  848. }
  849. function delSchedule() {
  850. var parent = $(this).parents(".pure-g");
  851. $(parent).remove();
  852. }
  853. function moreSchedule() {
  854. var parent = $(this).parents(".pure-g");
  855. $("div.more", parent).toggle();
  856. }
  857. function addSchedule(values) {
  858. var schedules = numSchedules();
  859. if (schedules >= maxSchedules()) {
  860. alert("Max number of schedules reached");
  861. return null;
  862. }
  863. if (values === undefined) {
  864. values = {};
  865. }
  866. var tabindex = 200 + schedules * 10;
  867. var template = $("#scheduleTemplate").children();
  868. var line = $(template).clone();
  869. var type = "none";
  870. switch(values.schType) {
  871. case 1:
  872. type = "switch";
  873. break;
  874. case 2:
  875. type = "light";
  876. break;
  877. case 3:
  878. type = "curtain";
  879. break;
  880. }
  881. template = $("#" + type + "ActionTemplate").children();
  882. $(line).find("#schActionDiv").append(template.clone());
  883. $(line).find("input").each(function() {
  884. $(this).attr("tabindex", tabindex);
  885. tabindex++;
  886. });
  887. $(line).find(".button-del-schedule").on("click", delSchedule);
  888. $(line).find(".button-more-schedule").on("click", moreSchedule);
  889. var schUTC_id = "schUTC" + schedules;
  890. $(line).find("input[name='schUTC']").prop("id", schUTC_id).next().prop("for", schUTC_id);
  891. var schEnabled_id = "schEnabled" + schedules;
  892. $(line).find("input[name='schEnabled']").prop("id", schEnabled_id).next().prop("for", schEnabled_id);
  893. $(line).find("input[type='checkbox']").prop("checked", false);
  894. Object.entries(values).forEach(function(kv) {
  895. var key = kv[0], value = kv[1];
  896. $("input[name='" + key + "']", line).val(value);
  897. $("select[name='" + key + "']", line).prop("value", value);
  898. $("input[type='checkbox'][name='" + key + "']", line).prop("checked", value);
  899. });
  900. line.appendTo("#schedules");
  901. return line;
  902. }
  903. // -----------------------------------------------------------------------------
  904. // Relays
  905. // -----------------------------------------------------------------------------
  906. function initRelayFromSchema(id, relay, schema) {
  907. var result = fromSchema(relay, schema)
  908. if (!result.name.length) {
  909. result.name = "Switch #" + id;
  910. }
  911. return result;
  912. }
  913. function initRelays(data) {
  914. var current = $("#relays > div").length;
  915. if (current > 0) { return; }
  916. var schema = data.schema;
  917. var template = $("#relayTemplate .pure-g")[0];
  918. data["relays"].forEach(function(relay, id) {
  919. var _relay = initRelayFromSchema(id, relay, schema);
  920. var line = $(template).clone();
  921. $("span.relay-name", line)
  922. .text(_relay.name)
  923. .attr("data", id);
  924. $("input[type='checkbox']", line)
  925. .prop('checked', false)
  926. .prop('disabled', true)
  927. .attr("data", id)
  928. .prop("id", "relay" + id)
  929. .on("change", function (event) {
  930. var target= parseInt($(event.target).attr("data"), 10);
  931. var status = $(event.target).prop("checked");
  932. doToggle(target, status);
  933. });
  934. $("label.toggle", line)
  935. .prop("for", "relay" + id);
  936. line.appendTo("#relays");
  937. });
  938. }
  939. function updateRelays(data) {
  940. var size = data.size;
  941. for (var i=0; i<size; ++i) {
  942. var elem = $("input[name='relay'][data='" + i + "']");
  943. elem.prop("checked", data.status[i]);
  944. var lock = {
  945. 0: false,
  946. 1: !data.status[i],
  947. 2: data.status[i]
  948. };
  949. elem.prop("disabled", lock[data.lock[i]]); // RELAY_LOCK_DISABLED=0
  950. }
  951. }
  952. function createCheckboxes() {
  953. $("input[type='checkbox']").each(function() {
  954. if($(this).prop("name"))$(this).prop("id", $(this).prop("name"));
  955. $(this).parent().addClass("toggleWrapper");
  956. $(this).after('<label for="' + $(this).prop("name") + '" class="toggle"><span class="toggle__handler"></span></label>')
  957. });
  958. }
  959. function initRelayConfig(data) {
  960. var current = $("#relayConfig > legend").length; // there is a legend per relay
  961. if (current > 0) { return; }
  962. var template = $("#relayConfigTemplate").children();
  963. var schema = data.schema;
  964. data["relays"].forEach(function(relay, id) {
  965. var _relay = initRelayFromSchema(id, relay, schema);
  966. var line = $(template).clone();
  967. $("span.name", line).html(_relay.name);
  968. $("span.prov", line).html(_relay.prov);
  969. $("select[name='relayBoot']", line).val(_relay.boot);
  970. $("select[name='relayPulse']", line).val(_relay.pulse);
  971. $("input[name='relayTime']", line).val(_relay.pulse_time);
  972. if (schema.includes("sch_last")) {
  973. $("input[name='relayLastSch']", line)
  974. .prop("checked", _relay.sch_last)
  975. .attr("id", "relayLastSch" + id)
  976. .attr("name", "relayLastSch" + id)
  977. .next().attr("for","relayLastSch" + (id));
  978. }
  979. if (schema.includes("group")) {
  980. $("input[name='mqttGroup']", line).val(_relay.group);
  981. }
  982. if (schema.includes("group_sync")) {
  983. $("select[name='mqttGroupSync']", line).val(_relay.group_sync);
  984. }
  985. if (schema.includes("on_disc")) {
  986. $("select[name='relayOnDisc']", line).val(_relay.on_disc);
  987. }
  988. setOriginalsFromValues($("input,select", line));
  989. line.appendTo("#relayConfig");
  990. // Populate the relay SELECTs on the configuration panel
  991. $("select.isrelay").append(
  992. $("<option></option>")
  993. .attr("value", id)
  994. .text(name)
  995. );
  996. ++id;
  997. });
  998. }
  999. // -----------------------------------------------------------------------------
  1000. // Sensors & Magnitudes
  1001. // -----------------------------------------------------------------------------
  1002. //removeIf(!sensor)
  1003. function initMagnitudes(data) {
  1004. // check if already initialized (each magnitude is inside div.pure-g)
  1005. var done = $("#magnitudes > div").length;
  1006. if (done > 0) { return; }
  1007. var size = data.size;
  1008. // add templates
  1009. var template = $("#magnitudeTemplate").children();
  1010. for (var i=0; i<size; ++i) {
  1011. var magnitude = {
  1012. "name": MagnitudeNames[data.type[i]] + " #" + parseInt(data.index[i], 10),
  1013. "units": data.units[i],
  1014. "description": data.description[i]
  1015. };
  1016. Magnitudes.push(magnitude);
  1017. var line = $(template).clone();
  1018. $("label", line).html(magnitude.name);
  1019. $("input", line).attr("data", i);
  1020. $("div.sns-desc", line).html(magnitude.description);
  1021. $("div.sns-info", line).hide();
  1022. line.appendTo("#magnitudes");
  1023. }
  1024. }
  1025. //endRemoveIf(!sensor)
  1026. // -----------------------------------------------------------------------------
  1027. // Curtains
  1028. // -----------------------------------------------------------------------------
  1029. //removeIf(!curtain)
  1030. //Create the controls for one curtain. It is called when curtain is updated (so created the first time)
  1031. //Let this there as we plan to have more than one curtain per switch
  1032. function initCurtain(data) {
  1033. var current = $("#curtains > div").length;
  1034. if (current > 0) { return; }
  1035. // add curtain template (prepare multi switches)
  1036. var template = $("#curtainTemplate").children();
  1037. var line = $(template).clone();
  1038. // init curtain button
  1039. $(line).find(".button-curtain-open").on("click", function() {
  1040. sendAction("curtainAction", {button: 1});
  1041. $(this).css('background', 'red');
  1042. });
  1043. $(line).find(".button-curtain-pause").on("click", function() {
  1044. sendAction("curtainAction", {button: 0});
  1045. $(this).css('background', 'red');
  1046. });
  1047. $(line).find(".button-curtain-close").on("click", function() {
  1048. sendAction("curtainAction", {button: 2});
  1049. $(this).css('background', 'red');
  1050. });
  1051. line.appendTo("#curtains");
  1052. // init curtain slider
  1053. $("#curtainSet").on("change", function() {
  1054. var value = $(this).val();
  1055. var parent = $(this).parents(".pure-g");
  1056. $("span", parent).html(value);
  1057. sendAction("curtainAction", {position: value});
  1058. });
  1059. }
  1060. function initCurtainConfig(data) {
  1061. var current = $("#curtainConfig > legend").length; // there is a legend per relay
  1062. if (current > 0) { return; }
  1063. // Populate the curtain select
  1064. $("select.iscurtain").append(
  1065. $("<option></option>")
  1066. .attr("value", "0")
  1067. .text("Curtain #" + "0")
  1068. );
  1069. }
  1070. //endRemoveIf(!curtain)
  1071. // -----------------------------------------------------------------------------
  1072. // Lights
  1073. // -----------------------------------------------------------------------------
  1074. //removeIf(!light)
  1075. function colorToHsvString(color) {
  1076. var h = String(Math.round(color.hsv.h));
  1077. var s = String(Math.round(color.hsv.s));
  1078. var v = String(Math.round(color.hsv.v));
  1079. return h + "," + s + "," + v;
  1080. }
  1081. function hsvStringToColor(hsv) {
  1082. var parts = hsv.split(",");
  1083. return {
  1084. h: parseInt(parts[0]),
  1085. s: parseInt(parts[1]),
  1086. v: parseInt(parts[2])
  1087. };
  1088. }
  1089. function colorSlider(type) {
  1090. return {component: iro.ui.Slider, options: {sliderType: type}};
  1091. }
  1092. function colorWheel() {
  1093. return {component: iro.ui.Wheel, options: {}};
  1094. }
  1095. function colorBox() {
  1096. return {component: iro.ui.Box, options: {}};
  1097. }
  1098. function updateColor(mode, value) {
  1099. if (colorPicker) {
  1100. if (mode === "rgb") {
  1101. colorPicker.color.hexString = value;
  1102. } else if (mode === "hsv") {
  1103. colorPicker.color.hsv = hsvStringToColor(value);
  1104. }
  1105. return;
  1106. }
  1107. // TODO: useRGB -> ltWheel?
  1108. // TODO: always show wheel + sliders like before?
  1109. var layout = []
  1110. if (mode === "rgb") {
  1111. layout.push(colorWheel());
  1112. layout.push(colorSlider("value"));
  1113. } else if (mode === "hsv") {
  1114. layout.push(colorBox());
  1115. layout.push(colorSlider("hue"));
  1116. }
  1117. var options = {
  1118. color: (mode === "rgb") ? value : hsvStringToColor(value),
  1119. layout: layout
  1120. };
  1121. colorPicker = new iro.ColorPicker("#color", options);
  1122. colorPicker.on("input:change", function(color) {
  1123. if (mode === "rgb") {
  1124. sendAction("color", {rgb: color.hexString});
  1125. } else if (mode === "hsv") {
  1126. sendAction("color", {hsv: colorToHsvString(color)});
  1127. }
  1128. });
  1129. }
  1130. function initCCT() {
  1131. // check if already initialized
  1132. var done = $("#cct > div").length;
  1133. if (done > 0) { return; }
  1134. $("#miredsTemplate").children().clone().appendTo("#cct");
  1135. $("#mireds").on("change", function() {
  1136. var value = $(this).val();
  1137. var parent = $(this).parents(".pure-g");
  1138. $("span", parent).html(value);
  1139. sendAction("mireds", {mireds: value});
  1140. });
  1141. }
  1142. function initChannels(num) {
  1143. // check if already initialized
  1144. var done = $("#channels > div").length > 0;
  1145. if (done) { return; }
  1146. // calculate channels to create
  1147. var max = num;
  1148. if (colorPicker) {
  1149. max = num % 3;
  1150. if ((max > 0) & useWhite) {
  1151. max--;
  1152. if (useCCT) {
  1153. max--;
  1154. }
  1155. }
  1156. }
  1157. var start = num - max;
  1158. var onChannelSliderChange = function() {
  1159. var id = $(this).attr("data");
  1160. var value = $(this).val();
  1161. var parent = $(this).parents(".pure-g");
  1162. $("span", parent).html(value);
  1163. sendAction("channel", {id: id, value: value});
  1164. };
  1165. // add channel templates
  1166. var i = 0;
  1167. var template = $("#channelTemplate").children();
  1168. for (i=0; i<max; i++) {
  1169. var channel_id = start + i;
  1170. var line = $(template).clone();
  1171. $("span.slider", line).attr("data", channel_id);
  1172. $("input.slider", line).attr("data", channel_id).on("change", onChannelSliderChange);
  1173. $("label", line).html("Channel #" + channel_id);
  1174. line.appendTo("#channels");
  1175. }
  1176. // Init channel dropdowns
  1177. for (i=0; i<num; i++) {
  1178. $("select.islight").append(
  1179. $("<option></option>").attr("value",i).text("Channel #" + i));
  1180. }
  1181. // add brightness template
  1182. var template = $("#brightnessTemplate").children();
  1183. var line = $(template).clone();
  1184. line.appendTo("#channels");
  1185. // init bright slider
  1186. $("#brightness").on("change", function() {
  1187. var value = $(this).val();
  1188. var parent = $(this).parents(".pure-g");
  1189. $("span", parent).html(value);
  1190. sendAction("brightness", {value: value});
  1191. });
  1192. }
  1193. //endRemoveIf(!light)
  1194. // -----------------------------------------------------------------------------
  1195. // RFBridge
  1196. // -----------------------------------------------------------------------------
  1197. //removeIf(!rfbridge)
  1198. function rfbLearn() {
  1199. var parent = $(this).parents(".pure-g");
  1200. var input = $("input", parent);
  1201. sendAction("rfblearn", {id: input.attr("data-id"), status: input.attr("data-status")});
  1202. }
  1203. function rfbForget() {
  1204. var parent = $(this).parents(".pure-g");
  1205. var input = $("input", parent);
  1206. sendAction("rfbforget", {id: input.attr("data-id"), status: input.attr("data-status")});
  1207. }
  1208. function rfbSend() {
  1209. var parent = $(this).parents(".pure-g");
  1210. var input = $("input", parent);
  1211. sendAction("rfbsend", {id: input.attr("data-id"), status: input.attr("data-status"), data: input.val()});
  1212. }
  1213. function addRfbNode() {
  1214. var numNodes = $("#rfbNodes > legend").length;
  1215. var template = $("#rfbNodeTemplate").children();
  1216. var line = $(template).clone();
  1217. $("span", line).html(numNodes);
  1218. $(line).find("input").each(function() {
  1219. this.dataset["id"] = numNodes;
  1220. });
  1221. $(line).find(".button-rfb-learn").on("click", rfbLearn);
  1222. $(line).find(".button-rfb-forget").on("click", rfbForget);
  1223. $(line).find(".button-rfb-send").on("click", rfbSend);
  1224. line.appendTo("#rfbNodes");
  1225. return line;
  1226. }
  1227. //endRemoveIf(!rfbridge)
  1228. // -----------------------------------------------------------------------------
  1229. // LightFox
  1230. // -----------------------------------------------------------------------------
  1231. //removeIf(!lightfox)
  1232. function lightfoxLearn() {
  1233. sendAction("lightfoxLearn", {});
  1234. }
  1235. function lightfoxClear() {
  1236. sendAction("lightfoxClear", {});
  1237. }
  1238. function initLightfox(data, relayCount) {
  1239. var numNodes = data.length;
  1240. var template = $("#lightfoxNodeTemplate").children();
  1241. var i, j;
  1242. for (i=0; i<numNodes; i++) {
  1243. var $line = $(template).clone();
  1244. $line.find("label > span").text(data[i]["id"]);
  1245. $line.find("select").each(function() {
  1246. $(this).attr("name", "btnRelay" + data[i]["id"]);
  1247. for (j=0; j < relayCount; j++) {
  1248. $(this).append($("<option >").attr("value", j).text("Switch #" + j));
  1249. }
  1250. $(this).val(data[i]["relay"]);
  1251. status = !status;
  1252. });
  1253. setOriginalsFromValues($("input,select", $line));
  1254. $line.appendTo("#lightfoxNodes");
  1255. }
  1256. var $panel = $("#panel-lightfox")
  1257. $(".button-lightfox-learn").off("click").click(lightfoxLearn);
  1258. $(".button-lightfox-clear").off("click").click(lightfoxClear);
  1259. }
  1260. //endRemoveIf(!lightfox)
  1261. // -----------------------------------------------------------------------------
  1262. // Processing
  1263. // -----------------------------------------------------------------------------
  1264. function processData(data) {
  1265. if (debug) console.log(data);
  1266. // title
  1267. if ("app_name" in data) {
  1268. var title = data.app_name;
  1269. if ("app_version" in data) {
  1270. $("span[name=title]").html(data.app_version);
  1271. title = title + " " + data.app_version;
  1272. }
  1273. if ("hostname" in data) {
  1274. title = data.hostname + " - " + title;
  1275. }
  1276. document.title = title;
  1277. }
  1278. Object.keys(data).forEach(function(key) {
  1279. var i;
  1280. var value = data[key];
  1281. // ---------------------------------------------------------------------
  1282. // Web mode
  1283. // ---------------------------------------------------------------------
  1284. if ("webMode" === key) {
  1285. password = (1 === value);
  1286. $("#layout").toggle(!password);
  1287. $("#password").toggle(password);
  1288. }
  1289. // ---------------------------------------------------------------------
  1290. // Actions
  1291. // ---------------------------------------------------------------------
  1292. if ("action" === key) {
  1293. if ("reload" === data.action) { doReload(1000); }
  1294. return;
  1295. }
  1296. // ---------------------------------------------------------------------
  1297. // RFBridge
  1298. // ---------------------------------------------------------------------
  1299. //removeIf(!rfbridge)
  1300. if ("rfbCount" === key) {
  1301. for (i=0; i<data.rfbCount; i++) { addRfbNode(); }
  1302. return;
  1303. }
  1304. if ("rfb" === key) {
  1305. var rfb = data.rfb;
  1306. var size = rfb.size;
  1307. var start = rfb.start;
  1308. var processOn = ((rfb.on !== undefined) && (rfb.on.length > 0));
  1309. var processOff = ((rfb.off !== undefined) && (rfb.off.length > 0));
  1310. for (var i=0; i<size; ++i) {
  1311. if (processOn) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='1']").val(rfb.on[i]);
  1312. if (processOff) $("input[name='rfbcode'][data-id='" + (i + start) + "'][data-status='0']").val(rfb.off[i]);
  1313. }
  1314. return;
  1315. }
  1316. //endRemoveIf(!rfbridge)
  1317. // ---------------------------------------------------------------------
  1318. // LightFox
  1319. // ---------------------------------------------------------------------
  1320. //removeIf(!lightfox)
  1321. if ("lightfoxButtons" === key) {
  1322. initLightfox(data["lightfoxButtons"], data["lightfoxRelayCount"]);
  1323. return;
  1324. }
  1325. //endRemoveIf(!lightfox)
  1326. // ---------------------------------------------------------------------
  1327. // RFM69
  1328. // ---------------------------------------------------------------------
  1329. //removeIf(!rfm69)
  1330. if (key == "packet") {
  1331. var packet = data.packet;
  1332. var d = new Date();
  1333. packets.row.add([
  1334. d.toLocaleTimeString('en-US', { hour12: false }),
  1335. packet.senderID,
  1336. packet.packetID,
  1337. packet.targetID,
  1338. packet.key,
  1339. packet.value,
  1340. packet.rssi,
  1341. packet.duplicates,
  1342. packet.missing,
  1343. ]).draw(false);
  1344. return;
  1345. }
  1346. if (key == "mapping") {
  1347. for (var i in data.mapping) {
  1348. // add a new row
  1349. addMapping();
  1350. // get group
  1351. var line = $("#mapping .pure-g")[i];
  1352. // fill in the blanks
  1353. var mapping = data.mapping[i];
  1354. Object.keys(mapping).forEach(function(key) {
  1355. var id = "input[name=" + key + "]";
  1356. if ($(id, line).length) $(id, line).val(mapping[key]);
  1357. });
  1358. setOriginalsFromValues($("input", line));
  1359. }
  1360. return;
  1361. }
  1362. //endRemoveIf(!rfm69)
  1363. // ---------------------------------------------------------------------
  1364. // RPN Rules
  1365. // ---------------------------------------------------------------------
  1366. if (key == "rpnRules") {
  1367. for (var i in data.rpnRules) {
  1368. // add a new row
  1369. addRPNRule();
  1370. // get group
  1371. var line = $("#rpnRules .pure-g")[i];
  1372. // fill in the blanks
  1373. var rule = data.rpnRules[i];
  1374. $("input", line).val(rule);
  1375. setOriginalsFromValues($("input", line));
  1376. }
  1377. return;
  1378. }
  1379. if (key == "rpnTopics") {
  1380. for (var i in data.rpnTopics) {
  1381. // add a new row
  1382. addRPNTopic();
  1383. // get group
  1384. var line = $("#rpnTopics .pure-g")[i];
  1385. // fill in the blanks
  1386. var topic = data.rpnTopics[i];
  1387. var name = data.rpnNames[i];
  1388. $("input[name='rpnTopic']", line).val(topic);
  1389. $("input[name='rpnName']", line).val(name);
  1390. setOriginalsFromValues($("input", line));
  1391. }
  1392. return;
  1393. }
  1394. if (key == "rpnNames") return;
  1395. // ---------------------------------------------------------------------
  1396. // Curtains
  1397. // ---------------------------------------------------------------------
  1398. //removeIf(!curtain)
  1399. function applyCurtain(a, b) {
  1400. $("#curtainGetPicture").css('background', 'linear-gradient(' + a + ', black ' + b + '%, #a0d6ff ' + b + '%)');
  1401. }
  1402. if ("curtainState" === key) {
  1403. initCurtain();
  1404. switch(value.type) {
  1405. case '0': //Roller
  1406. default:
  1407. applyCurtain('180deg', value.get);
  1408. break;
  1409. case '1': //One side left to right
  1410. applyCurtain('90deg', value.get);
  1411. break;
  1412. case '2': //One side right to left
  1413. applyCurtain('270deg', value.get);
  1414. break;
  1415. case '3': //Two sides
  1416. $("#curtainGetPicture").css('background', 'linear-gradient(90deg, black ' + value.get/2 + '%, #a0d6ff ' + value.get/2 + '% ' + (100 - value.get/2) + '%, black ' + (100 - value.get/2) + '%)');
  1417. break;
  1418. }
  1419. $("#curtainSet").val(value.set);
  1420. if(!value.moving) {
  1421. $("button.curtain-button").css('background', 'rgb(66, 184, 221)');
  1422. } else {
  1423. if(!value.button)
  1424. $("button.button-curtain-pause").css('background', 'rgb(192, 0, 0)');
  1425. else if(value.button == 1) {
  1426. $("button.button-curtain-close").css('background', 'rgb(66, 184, 221)');
  1427. $("button.button-curtain-open").css('background', 'rgb(192, 0, 0)');
  1428. }
  1429. else if(value.button == 2) {
  1430. $("button.button-curtain-open").css('background', 'rgb(66, 184, 221)');
  1431. $("button.button-curtain-close").css('background', 'rgb(192, 0, 0)');
  1432. }
  1433. }
  1434. return;
  1435. }
  1436. //endRemoveIf(!curtain)
  1437. // ---------------------------------------------------------------------
  1438. // Lights
  1439. // ---------------------------------------------------------------------
  1440. //removeIf(!light)
  1441. if ("lightstate" === key) {
  1442. $("#color").toggle(value);
  1443. return;
  1444. }
  1445. if (("rgb" === key) || ("hsv" === key)) {
  1446. updateColor(key, value);
  1447. return;
  1448. }
  1449. if ("brightness" === key) {
  1450. $("#brightness").val(value);
  1451. $("span.brightness").html(value);
  1452. return;
  1453. }
  1454. if ("channels" === key) {
  1455. var len = value.length;
  1456. initChannels(len);
  1457. for (i in value) {
  1458. var ch = value[i];
  1459. $("input.slider[data=" + i + "]").val(ch);
  1460. $("span.slider[data=" + i + "]").html(ch);
  1461. }
  1462. return;
  1463. }
  1464. if ("mireds" === key) {
  1465. $("#mireds").attr("min", value["cold"]);
  1466. $("#mireds").attr("max", value["warm"]);
  1467. $("#mireds").val(value["value"]);
  1468. $("span.mireds").html(value["value"]);
  1469. return;
  1470. }
  1471. if ("useWhite" === key) {
  1472. useWhite = value;
  1473. }
  1474. if ("useCCT" === key) {
  1475. initCCT();
  1476. useCCT = value;
  1477. }
  1478. //endRemoveIf(!light)
  1479. // ---------------------------------------------------------------------
  1480. // Sensors & Magnitudes
  1481. // ---------------------------------------------------------------------
  1482. //removeIf(!sensor)
  1483. {
  1484. var position = key.indexOf("Correction");
  1485. if (position > 0 && position === key.length - 10) {
  1486. var template = $("#magnitudeCorrectionTemplate > div")[0];
  1487. var elem = $(template).clone();
  1488. var prefix = key.slice(0, position);
  1489. $("label", elem).html(MagnitudeNames[MagnitudePrefixTypes[prefix]]);
  1490. $("input", elem).attr("name", key).val(value);
  1491. setOriginalsFromValues($("input", elem));
  1492. elem.appendTo("#magnitude-corrections");
  1493. moduleVisible("magnitude-corrections");
  1494. return;
  1495. }
  1496. }
  1497. if ("snsErrors" === key) {
  1498. for (var index in value) {
  1499. var type = value[index][0];
  1500. var name = value[index][1];
  1501. MagnitudeErrors[type] = name;
  1502. }
  1503. return;
  1504. }
  1505. if ("snsMagnitudes" === key) {
  1506. for (var index in value) {
  1507. var type = value[index][0];
  1508. var prefix = value[index][1];
  1509. var name = value[index][2];
  1510. MagnitudeNames[type] = name;
  1511. MagnitudeTypePrefixes[type] = prefix;
  1512. MagnitudePrefixTypes[prefix] = type;
  1513. moduleVisible(prefix);
  1514. }
  1515. return;
  1516. }
  1517. if ("magnitudesConfig" === key) {
  1518. initMagnitudes(value);
  1519. return;
  1520. }
  1521. if ("magnitudes" === key) {
  1522. for (var i=0; i<value.size; ++i) {
  1523. var inputElem = $("input[name='magnitude'][data='" + i + "']");
  1524. var infoElem = inputElem.parent().parent().find("div.sns-info");
  1525. var error = value.error[i] || 0;
  1526. var text = (0 === error)
  1527. ? value.value[i] + Magnitudes[i].units
  1528. : MagnitudeErrors[error];
  1529. inputElem.val(text);
  1530. if (value.info !== undefined) {
  1531. var info = value.info[i] || 0;
  1532. infoElem.toggle(info != 0);
  1533. infoElem.text(info);
  1534. }
  1535. }
  1536. return;
  1537. }
  1538. if ("pzemVisible" === key) {
  1539. $("input[name='snsSave']").prop("disabled", true);
  1540. $("input[name='snsSave']")
  1541. .parent().parent().find(".hint")
  1542. .text("PZEM004 module saves the energy data on it's own")
  1543. return;
  1544. }
  1545. //endRemoveIf(!sensor)
  1546. // ---------------------------------------------------------------------
  1547. // WiFi
  1548. // ---------------------------------------------------------------------
  1549. if ("wifi" === key) {
  1550. maxNetworks = parseInt(value["max"], 10);
  1551. value["networks"].forEach(function(network) {
  1552. addNetwork(fromSchema(network, value.schema));
  1553. });
  1554. return;
  1555. }
  1556. if ("scanResult" === key) {
  1557. $("div.scan.loading").hide();
  1558. $("#button-wifi-scan").attr("disabled", false);
  1559. $("#scanResult").show();
  1560. }
  1561. // -----------------------------------------------------------------------------
  1562. // Home Assistant
  1563. // -----------------------------------------------------------------------------
  1564. if ("haConfig" === key) {
  1565. send("{}");
  1566. $("#haConfig")
  1567. .append(new Text(value))
  1568. .height($("#haConfig")[0].scrollHeight);
  1569. return;
  1570. }
  1571. // -----------------------------------------------------------------------------
  1572. // Relays scheduler
  1573. // -----------------------------------------------------------------------------
  1574. if ("schedules" === key) {
  1575. $("#schedules").attr("data-settings-max", value.max);
  1576. for (var i=0; i<value.size; ++i) {
  1577. // XXX: no
  1578. var sch_map = {};
  1579. Object.keys(value).forEach(function(key) {
  1580. if ("size" == key) return;
  1581. if ("max" == key) return;
  1582. sch_map[key] = value[key][i];
  1583. });
  1584. addSchedule(sch_map);
  1585. }
  1586. return;
  1587. }
  1588. // ---------------------------------------------------------------------
  1589. // Relays
  1590. // ---------------------------------------------------------------------
  1591. if ("relayConfig" === key) {
  1592. initRelays(value);
  1593. initRelayConfig(value);
  1594. return;
  1595. }
  1596. if ("relayState" === key) {
  1597. updateRelays(value);
  1598. return;
  1599. }
  1600. // ---------------------------------------------------------------------
  1601. // Curtain(s)
  1602. // ---------------------------------------------------------------------
  1603. //removeIf(!curtain)
  1604. // Relay configuration
  1605. if ("curtainConfig" === key) {
  1606. initCurtainConfig(value);
  1607. return;
  1608. }
  1609. //endRemoveIf(!curtain)
  1610. // ---------------------------------------------------------------------
  1611. // LEDs
  1612. // ---------------------------------------------------------------------
  1613. if ("led" === key) {
  1614. if($("#ledConfig > div").length > 0) return;
  1615. var schema = value["schema"];
  1616. value["list"].forEach(function(led_data, index) {
  1617. var line = $($("#ledConfigTemplate").children()).clone();
  1618. $("span.id", line).html(index);
  1619. $("select", line).attr("data", index);
  1620. $("input", line).attr("data", index);
  1621. var led = fromSchema(led_data, schema);
  1622. $("select[name='ledGPIO']", line).val(led.GPIO);
  1623. // XXX: checkbox implementation depends on unique id
  1624. // $("input[name='ledInv']", line).val(led.Inv);
  1625. $("select[name='ledMode']", line).val(led.Mode);
  1626. $("input[name='ledRelay']", line).val(led.Relay);
  1627. setOriginalsFromValues($("input,select", line));
  1628. line.appendTo("#ledConfig");
  1629. });
  1630. return;
  1631. }
  1632. // ---------------------------------------------------------------------
  1633. // Domoticz
  1634. // ---------------------------------------------------------------------
  1635. // Domoticz - Relays
  1636. if ("dczRelays" === key) {
  1637. createRelayList(value, "dczRelays", "dczRelayTemplate");
  1638. return;
  1639. }
  1640. // Domoticz - Magnitudes
  1641. //removeIf(!sensor)
  1642. if ("dczMagnitudes" === key) {
  1643. createMagnitudeList(value, "dczMagnitudes", "dczMagnitudeTemplate");
  1644. return;
  1645. }
  1646. //endRemoveIf(!sensor)
  1647. // ---------------------------------------------------------------------
  1648. // Thingspeak
  1649. // ---------------------------------------------------------------------
  1650. // Thingspeak - Relays
  1651. if ("tspkRelays" === key) {
  1652. createRelayList(value, "tspkRelays", "tspkRelayTemplate");
  1653. return;
  1654. }
  1655. // Thingspeak - Magnitudes
  1656. //removeIf(!sensor)
  1657. if ("tspkMagnitudes" === key) {
  1658. createMagnitudeList(value, "tspkMagnitudes", "tspkMagnitudeTemplate");
  1659. return;
  1660. }
  1661. //endRemoveIf(!sensor)
  1662. // ---------------------------------------------------------------------
  1663. // HTTP API
  1664. // ---------------------------------------------------------------------
  1665. // Auto generate an APIKey if none defined yet
  1666. if ("apiVisible" === key) {
  1667. if (data.apiKey === undefined || data.apiKey === "") {
  1668. generateAPIKey();
  1669. }
  1670. }
  1671. // ---------------------------------------------------------------------
  1672. // General
  1673. // ---------------------------------------------------------------------
  1674. // Messages
  1675. if ("message" === key) {
  1676. if (value == 8) {
  1677. configurationSaved = true;
  1678. }
  1679. window.alert(messages[value]);
  1680. return;
  1681. }
  1682. // Web log
  1683. if ("weblog" === key) {
  1684. send("{}");
  1685. var msg = value["msg"];
  1686. var pre = value["pre"];
  1687. for (var i=0; i < msg.length; ++i) {
  1688. if (pre[i]) {
  1689. $("#weblog").append(new Text(pre[i]));
  1690. }
  1691. $("#weblog").append(new Text(msg[i]));
  1692. }
  1693. followScroll("weblog");
  1694. return;
  1695. }
  1696. // Enable options
  1697. var position = key.indexOf("Visible");
  1698. if (position > 0 && position === key.length - 7) {
  1699. var module = key.slice(0,-7);
  1700. moduleVisible(module);
  1701. return;
  1702. }
  1703. if ("deviceip" === key) {
  1704. var a_href = $("span[name='" + key + "']").parent();
  1705. a_href.attr("href", "//" + value);
  1706. a_href.next().attr("href", "telnet://" + value);
  1707. }
  1708. if ("now" === key) {
  1709. now = value;
  1710. return;
  1711. }
  1712. if ("free_size" === key) {
  1713. free_size = parseInt(value, 10);
  1714. }
  1715. // Pre-process
  1716. if ("mqttStatus" === key) {
  1717. value = value ? "CONNECTED" : "NOT CONNECTED";
  1718. }
  1719. if ("ntpStatus" === key) {
  1720. value = value ? "SYNC'D" : "NOT SYNC'D";
  1721. }
  1722. if ("uptime" === key) {
  1723. ago = 0;
  1724. var uptime = parseInt(value, 10);
  1725. var seconds = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1726. var minutes = uptime % 60; uptime = parseInt(uptime / 60, 10);
  1727. var hours = uptime % 24; uptime = parseInt(uptime / 24, 10);
  1728. var days = uptime;
  1729. value = days + "d " + zeroPad(hours, 2) + "h " + zeroPad(minutes, 2) + "m " + zeroPad(seconds, 2) + "s";
  1730. }
  1731. //removeIf(!thermostat)
  1732. if ("tmpUnits" == key) {
  1733. $("span.tmpUnit").html(data[key] == 3 ? "ºF" : "ºC");
  1734. }
  1735. //endRemoveIf(!thermostat)
  1736. // ---------------------------------------------------------------------
  1737. // Matching
  1738. // ---------------------------------------------------------------------
  1739. var elems = [];
  1740. var pre;
  1741. var post;
  1742. // Look for INPUTs
  1743. var input = $("input[name='" + key + "']");
  1744. if (input.length > 0) {
  1745. if (input.attr("type") === "checkbox") {
  1746. input.prop("checked", value);
  1747. } else if (input.attr("type") === "radio") {
  1748. input.val([value]);
  1749. } else {
  1750. pre = input.attr("pre") || "";
  1751. post = input.attr("post") || "";
  1752. input.val(pre + value + post);
  1753. }
  1754. elems.push(input);
  1755. }
  1756. // Look for SPANs
  1757. var span = $("span[name='" + key + "']");
  1758. if (span.length > 0) {
  1759. if (Array.isArray(value)) {
  1760. value.forEach(function(elem) {
  1761. span.append(elem);
  1762. span.append('</br>');
  1763. elems.push(span);
  1764. });
  1765. } else {
  1766. pre = span.attr("pre") || "";
  1767. post = span.attr("post") || "";
  1768. span.html(pre + value + post);
  1769. elems.push(span);
  1770. }
  1771. }
  1772. // Look for SELECTs
  1773. var select = $("select[name='" + key + "']");
  1774. if (select.length > 0) {
  1775. select.val(value);
  1776. elems.push(select);
  1777. }
  1778. setOriginalsFromValues($(elems));
  1779. });
  1780. }
  1781. function hasChanged() {
  1782. var newValue, originalValue;
  1783. if ($(this).attr("type") === "checkbox") {
  1784. newValue = $(this).prop("checked");
  1785. originalValue = ($(this).attr("original") === "true");
  1786. } else {
  1787. newValue = $(this).val();
  1788. originalValue = $(this).attr("original");
  1789. }
  1790. var hasChanged = ("true" === $(this).attr("hasChanged"));
  1791. var action = $(this).attr("action");
  1792. if (typeof originalValue === "undefined") { return; }
  1793. if ("none" === action) { return; }
  1794. if (newValue !== originalValue) {
  1795. if (!hasChanged) {
  1796. ++numChanged;
  1797. if ("reconnect" === action) { ++numReconnect; }
  1798. if ("reboot" === action) { ++numReboot; }
  1799. if ("reload" === action) { ++numReload; }
  1800. }
  1801. $(this).attr("hasChanged", true);
  1802. } else {
  1803. if (hasChanged) {
  1804. --numChanged;
  1805. if ("reconnect" === action) { --numReconnect; }
  1806. if ("reboot" === action) { --numReboot; }
  1807. if ("reload" === action) { --numReload; }
  1808. }
  1809. $(this).attr("hasChanged", false);
  1810. }
  1811. }
  1812. // -----------------------------------------------------------------------------
  1813. // Init & connect
  1814. // -----------------------------------------------------------------------------
  1815. function initUrls(root) {
  1816. var paths = ["ws", "upgrade", "config", "auth"];
  1817. urls["root"] = root;
  1818. paths.forEach(function(path) {
  1819. urls[path] = new URL(path, root);
  1820. urls[path].protocol = root.protocol;
  1821. });
  1822. if (root.protocol == "https:") {
  1823. urls.ws.protocol = "wss:";
  1824. } else {
  1825. urls.ws.protocol = "ws:";
  1826. }
  1827. }
  1828. function connectToURL(url) {
  1829. initUrls(url);
  1830. fetch(urls.auth.href, {
  1831. 'method': 'GET',
  1832. 'cors': true,
  1833. 'credentials': 'same-origin'
  1834. }).then(function(response) {
  1835. // Nothing to do, reload page and retry
  1836. if (response.status != 200) {
  1837. doReload(5000);
  1838. return;
  1839. }
  1840. // update websock object
  1841. if (websock) { websock.close(); }
  1842. websock = new WebSocket(urls.ws.href);
  1843. websock.onmessage = function(evt) {
  1844. var data = getJson(evt.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"));
  1845. if (data) {
  1846. processData(data);
  1847. }
  1848. };
  1849. websock.onclose = function(evt) {
  1850. clearInterval(ws_pingpong);
  1851. if (window.confirm("Connection lost with the device, click OK to refresh the page")) {
  1852. $("#layout").toggle(false);
  1853. window.location.reload();
  1854. }
  1855. }
  1856. websock.onopen = function(evt) {
  1857. ws_pingpong = setInterval(function() { sendAction("ping", {}); }, 5000);
  1858. }
  1859. }).catch(function(error) {
  1860. console.log(error);
  1861. doReload(5000);
  1862. });
  1863. }
  1864. function connect(host) {
  1865. if (!host.startsWith("http:") && !host.startsWith("https:")) {
  1866. host = "http://" + host;
  1867. }
  1868. connectToURL(new URL(host));
  1869. }
  1870. function connectToCurrentURL() {
  1871. connectToURL(new URL(window.location));
  1872. }
  1873. $(function() {
  1874. initMessages();
  1875. createCheckboxes();
  1876. setInterval(function() { keepTime(); }, 1000);
  1877. $(".password-reveal").on("click", toggleVisiblePassword);
  1878. $("#menuLink").on("click", toggleMenu);
  1879. $(".pure-menu-link").on("click", showPanel);
  1880. $("progress").attr({ value: 0, max: 100 });
  1881. $("#button-wifi-scan").on("click", doScan);
  1882. $(".button-update").on("click", doUpdate);
  1883. $(".button-update-password").on("click", doUpdatePassword);
  1884. $(".button-generate-password").on("click", doGeneratePassword);
  1885. $(".button-reboot").on("click", doReboot);
  1886. $(".button-reconnect").on("click", doReconnect);
  1887. $(".button-ha-config").on("click", doHAConfig);
  1888. $(".button-dbgcmd").on("click", doDebugCommand);
  1889. $("input[name='dbgcmd']").enterKey(doDebugCommand);
  1890. $(".button-dbg-clear").on("click", doDebugClear);
  1891. $(".button-settings-backup").on("click", doBackup);
  1892. $(".button-settings-restore").on("click", doRestore);
  1893. $(".button-settings-factory").on("click", doFactoryReset);
  1894. $("#uploader").on("change", onFileUpload);
  1895. $(".button-upgrade").on("click", doUpgrade);
  1896. //removeIf(!garland)
  1897. $(".checkbox-garland-enable").on("change", function() {
  1898. sendAction("garland_switch", {status: $(this).prop("checked") ? 1 : 0});
  1899. });
  1900. $(".slider-garland-brightness").on("change", function() {
  1901. sendAction("garland_set_brightness", {brightness: $(this)[0].value});
  1902. });
  1903. $(".slider-garland-speed").on("change", function() {
  1904. sendAction("garland_set_speed", {speed: $(this)[0].value});
  1905. });
  1906. $(".button-garland-set-default").on("click", function() {
  1907. sendAction("garland_set_default", {});
  1908. });
  1909. //endRemoveIf(!garland)
  1910. //removeIf(!thermostat)
  1911. $(".button-thermostat-reset-counters").on('click', doResetThermostatCounters);
  1912. //endRemoveIf(!thermostat)
  1913. $(".button-apikey").on("click", generateAPIKey);
  1914. $(".button-upgrade-browse").on("click", function() {
  1915. $("input[name='upgrade']")[0].click();
  1916. return false;
  1917. });
  1918. $("input[name='upgrade']").change(function (){
  1919. var file = this.files[0];
  1920. $("input[name='filename']").val(file.name);
  1921. });
  1922. $(".button-add-network").on("click", function() {
  1923. $(".more", addNetwork()).toggle();
  1924. });
  1925. $(".button-add-switch-schedule").on("click", function() {
  1926. addSchedule({schType: 1, schSwitch: -1});
  1927. });
  1928. //removeIf(!light)
  1929. $(".button-add-light-schedule").on("click", function() {
  1930. addSchedule({schType: 2, schSwitch: -1});
  1931. });
  1932. //endRemoveIf(!light)
  1933. //removeIf(!curtain)
  1934. $(".button-add-curtain-schedule").on("click", function() {
  1935. addSchedule({schType: 3, schSwitch: -1});
  1936. });
  1937. //endRemoveIf(!curtain)
  1938. $(".button-add-rpnrule").on('click', addRPNRule);
  1939. $(".button-add-rpntopic").on('click', addRPNTopic);
  1940. $(".button-del-parent").on('click', delParent);
  1941. //removeIf(!rfm69)
  1942. $(".button-add-mapping").on('click', addMapping);
  1943. $(".button-clear-counts").on('click', doClearCounts);
  1944. $(".button-clear-messages").on('click', doClearMessages);
  1945. $(".button-clear-filters").on('click', doClearFilters);
  1946. $('#packets tbody').on('mousedown', 'td', doFilter);
  1947. packets = $('#packets').DataTable({
  1948. "paging": false
  1949. });
  1950. for (var i = 0; i < packets.columns()[0].length; i++) {
  1951. filters[i] = false;
  1952. }
  1953. //endRemoveIf(!rfm69)
  1954. $(".gpio-select").each(function(_, elem) {
  1955. initSelectGPIO(elem)
  1956. });
  1957. $(document).on("change", "input", hasChanged);
  1958. $(document).on("change", "select", hasChanged);
  1959. $("textarea").on("dblclick", function() { this.select(); });
  1960. resetOriginals();
  1961. $(".group-settings").each(function() {
  1962. groupSettingsObserver.observe(this, {childList: true});
  1963. });
  1964. // don't autoconnect when opening from filesystem
  1965. if (window.location.protocol === "file:") {
  1966. processData({"webMode": 0});
  1967. return;
  1968. }
  1969. // Check host param in query string
  1970. var search = new URLSearchParams(window.location.search),
  1971. host = search.get("host");
  1972. if (host !== null) {
  1973. connect(host);
  1974. } else {
  1975. connectToCurrentURL();
  1976. }
  1977. });