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.

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