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.

2452 lines
71 KiB

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