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.

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