Compare commits
	
		
			711 Commits
		
	
	
		
			v0.14.0-b1
			...
			v0.14.1-b3
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | 8fb5f0ef3c | ||
|   | cdc8640218 | ||
|   | 51b3d7cb4a | ||
|   | 3baff4e675 | ||
|   | 06911e7ad0 | ||
|   | 4e0f3e35db | ||
|   | 4f55be4f19 | ||
|   | e8b3c66c21 | ||
|   | 662870baf4 | ||
|   | e95629f827 | ||
|   | 010c3494fd | ||
|   | 5ebc345e95 | ||
|   | b743ca8eb1 | ||
|   | a3a5bffce4 | ||
|   | d1b80aa4d4 | ||
|   | 5f62b4a89d | ||
|   | 39e0a1fb9e | ||
|   | 72e864b013 | ||
|   | 5ab012163e | ||
|   | 1900686bc4 | ||
|   | 809a294f9d | ||
|   | 10faaaf531 | ||
|   | 7642c5a50d | ||
|   | 5c90a742ba | ||
|   | da488f76d2 | ||
|   | 6d28de77d1 | ||
|   | a8bd46c521 | ||
|   | 1ec3a74d4c | ||
|   | 082d1eea48 | ||
|   | d6735bed4f | ||
|   | dbe8554724 | ||
|   | 9f79e64678 | ||
|   | f513cae66e | ||
|   | cb95a7d418 | ||
|   | 84802d9065 | ||
|   | 90d696d826 | ||
|   | aeb9e2ad9f | ||
|   | 26ab1bfd4f | ||
|   | 7c108e5128 | ||
|   | 4873031c37 | ||
|   | b0d0bb7953 | ||
|   | f66b343edd | ||
|   | ff82d36e94 | ||
|   | c3e937f5e0 | ||
|   | 32e724e744 | ||
|   | 5fb891c495 | ||
|   | d56cefdc7a | ||
|   | 80c67d37c0 | ||
|   | 1e29d9463e | ||
|   | 75f6a53269 | ||
|   | 76a7f25083 | ||
|   | 16617660c3 | ||
|   | a83d9a075f | ||
|   | eca3fb1e19 | ||
|   | 44726c7411 | ||
|   | c340a1d47f | ||
|   | 7238ef4f55 | ||
|   | e67a210e95 | ||
|   | 51dfa9a247 | ||
|   | 7c121b8ba6 | ||
|   | 9db8d44654 | ||
|   | 1543862f3b | ||
|   | 5b7b34a9f0 | ||
|   | fb6271eecf | ||
|   | 031526b619 | ||
|   | 4f5816f42e | ||
|   | 555d0d3378 | ||
|   | e260b9473a | ||
|   | ccc56d446f | ||
|   | 284366e6bb | ||
|   | e5f6f8dfa7 | ||
|   | 96700fe3d1 | ||
|   | 34bed44a9b | ||
|   | d431aa4b59 | ||
|   | 9867227ccd | ||
|   | 0decf94c9c | ||
|   | 0ae78efd43 | ||
|   | 3eabefd3d6 | ||
|   | 7ff6a6e0e7 | ||
|   | 94dc611024 | ||
|   | 0b28107432 | ||
|   | fe717dad7f | ||
|   | 535bf4c848 | ||
|   | 1fc60b0682 | ||
|   | 302f1ee8e3 | ||
|   | 42aec56b8e | ||
|   | 199c00c59b | ||
|   | 107bb14555 | ||
|   | 5820792013 | ||
|   | 0e20248494 | ||
|   | 0d66bc49c2 | ||
|   | aca01044f4 | ||
|   | c7d399c122 | ||
|   | b6f43966ea | ||
|   | 1dab26bcbc | ||
|   | 36290c20aa | ||
|   | c33c7eb68e | ||
|   | 5da33afecd | ||
|   | 225fd0d05b | ||
|   | c43b4f9cf0 | ||
|   | 3581f4c87e | ||
|   | 7a4e0cc850 | ||
|   | ba49da75de | ||
|   | d95158003c | ||
|   | 418abc2b0a | ||
|   | 277f0346f2 | ||
|   | 6148cbb122 | ||
|   | 3847bfc41a | ||
|   | 783424dd26 | ||
|   | 7f6486c77d | ||
|   | 5dadf92a62 | ||
|   | 76821addd7 | ||
|   | a769c55c72 | ||
|   | 4245767357 | ||
|   | 74d196ad50 | ||
|   | 3c4649748d | ||
|   | 22985900a8 | ||
|   | 86300a8e3c | ||
|   | 32ab2ae201 | ||
|   | 23e4a2e28e | ||
|   | 40515e62ac | ||
|   | b56490650c | ||
|   | b5751795b5 | ||
|   | 43d6151506 | ||
|   | 8ccfb606c0 | ||
|   | 26e766ee19 | ||
|   | 1c3fdb73fb | ||
|   | 332be7edd6 | ||
|   | 7e6eb65950 | ||
|   | b0a56a431b | ||
|   | 166316e0c5 | ||
|   | 4194e66d81 | ||
|   | c9b9d86892 | ||
|   | f2d00e6e42 | ||
|   | acfc166a11 | ||
|   | 5eadbe7ecd | ||
|   | ea7e0c6204 | ||
|   | 2dcb126e6d | ||
|   | 438525e8ec | ||
|   | eb66a403d9 | ||
|   | 26ac612474 | ||
|   | 43613e3b10 | ||
|   | 555dd2e726 | ||
|   | 3260f46543 | ||
|   | f9de23402a | ||
|   | 9e155cf94a | ||
|   | 527e3d6cd0 | ||
|   | c7d45c28cf | ||
|   | 87cc3fd714 | ||
|   | 282d58a6fe | ||
|   | fc4ed1c50b | ||
|   | 9709ca331e | ||
|   | b4a9641c31 | ||
|   | 60c47cfca1 | ||
|   | 720abd4e04 | ||
|   | b4fe694d1b | ||
|   | c117785554 | ||
|   | e9723de6c3 | ||
|   | da0cf01eee | ||
|   | e40f266042 | ||
|   | 69fb15d3cb | ||
|   | 188956a4af | ||
|   | c7dd4a7f2b | ||
|   | 111f1729c9 | ||
|   | 164372b46a | ||
|   | 1af3794fed | ||
|   | 885f4ded0c | ||
|   | 9bb018d8d9 | ||
|   | 58187e00e6 | ||
|   | 5110a8c636 | ||
|   | ddbe883d47 | ||
|   | 945ac82b6a | ||
|   | 84148ad07a | ||
|   | 25553a28a1 | ||
|   | c2f5846a8e | ||
|   | 3f98e9451a | ||
|   | 6c72194346 | ||
|   | 822dd24756 | ||
|   | 262ed38429 | ||
|   | 5ff66ce4dd | ||
|   | ca73b8e0b8 | ||
|   | 2d49ace0e3 | ||
|   | d52f22044e | ||
|   | 2bf052aac9 | ||
|   | a79c9d5f4f | ||
|   | 6f9bcf1858 | ||
|   | d1b00ba95d | ||
|   | bb45bee7f8 | ||
|   | 246f0b21fd | ||
|   | 394443b6d1 | ||
|   | fc1dd2daac | ||
|   | ba1b6f321e | ||
|   | 06402cf1c6 | ||
|   | dfc33389d8 | ||
|   | 4e83752655 | ||
|   | 7e28718681 | ||
|   | bf452e922a | ||
|   | 4911a74cac | ||
|   | a2bda5a4db | ||
|   | 800abc605f | ||
|   | ac83b67632 | ||
|   | 00bc7dccb9 | ||
|   | 04aa9f0e61 | ||
|   | 353e97a4c1 | ||
|   | 7b28387bb4 | ||
|   | 1889fe23c5 | ||
|   | 9832fbe042 | ||
|   | 084070475d | ||
|   | cb42ca8765 | ||
|   | 45d7e66488 | ||
|   | 93a1616933 | ||
|   | 9a87a2ff0d | ||
|   | bdff05feaf | ||
|   | 937e3d0b94 | ||
|   | 8503aba583 | ||
|   | bb8223d4ff | ||
|   | af3c8f66f7 | ||
|   | 3097a1b17e | ||
|   | 54b80f74b2 | ||
|   | 9a78d28cd7 | ||
|   | 5df197e814 | ||
|   | 5fe09e9787 | ||
|   | 1ed817932b | ||
|   | 0ccadb246f | ||
| ![dependabot[bot]](/assets/img/avatar_default.png)  | b67235a7e5 | ||
|   | 93853613bd | ||
|   | 1ecb4fedcc | ||
|   | c8fdf3731a | ||
|   | f8e766ffc0 | ||
|   | 050489dd80 | ||
|   | 2db966ba47 | ||
|   | aa54d65f63 | ||
|   | 37dc17ae15 | ||
|   | cd6b3d7dee | ||
|   | aec0bc5029 | ||
|   | e010e67717 | ||
|   | 44197d91c6 | ||
|   | e3ee48b52e | ||
|   | 8ccf349458 | ||
|   | 2fce15db94 | ||
|   | 0cf50e8000 | ||
|   | 5b9630cf46 | ||
|   | 7dcbb409a9 | ||
|   | 286e057fae | ||
|   | 7d4fe341f1 | ||
|   | 76acb7bb58 | ||
|   | 5ef7cd7bdd | ||
|   | ebb4628e66 | ||
|   | 0928060c75 | ||
|   | d8f9a9a03c | ||
|   | abfb8bbc34 | ||
|   | 82e01f7b17 | ||
| ![dependabot[bot]](/assets/img/avatar_default.png)  | a97609e920 | ||
|   | f1e1bd41b9 | ||
|   | 57d35858d8 | ||
|   | 0b956c66c1 | ||
|   | b1dfa1db61 | ||
|   | cb579ecc62 | ||
|   | ae235aa58c | ||
|   | 6302056182 | ||
|   | 5e20abd7f1 | ||
|   | 72a72dbc88 | ||
|   | 4766666913 | ||
|   | fa6070c680 | ||
|   | 6267d11e51 | ||
|   | 822298ab66 | ||
|   | 2ad3ab7f0d | ||
|   | f437fd6cd6 | ||
|   | 42b247756a | ||
|   | fbbf2d5eb3 | ||
|   | 788a276616 | ||
|   | 196779ffb6 | ||
|   | 59a144baed | ||
|   | ad825b80b0 | ||
|   | 45a0061660 | ||
|   | 8831c76fb4 | ||
|   | 66616e1cab | ||
|   | fa281a0df0 | ||
|   | d48a96599f | ||
|   | 7de7ef8e8c | ||
|   | 406a254523 | ||
|   | eabd6f60ef | ||
|   | e416d06aa9 | ||
|   | 65e073e6b8 | ||
|   | 45ac0d5dc6 | ||
|   | c9ef034ab8 | ||
|   | c89f38f4f8 | ||
|   | 858b57d77a | ||
|   | 9b87892036 | ||
|   | 272f96b405 | ||
|   | 3e519001a3 | ||
|   | f442aad962 | ||
|   | fa9b151c36 | ||
|   | 481bd6f57a | ||
|   | f015227fc8 | ||
|   | 61ba16b779 | ||
|   | f6e86bfcf8 | ||
|   | 498dd76730 | ||
|   | ebd909dfe7 | ||
|   | 067ed1258b | ||
|   | ef3c72a24f | ||
|   | b257f476c9 | ||
|   | d3af2be79a | ||
|   | 94aeb19245 | ||
|   | e4ee392c27 | ||
|   | cf48ad06ed | ||
|   | 63df85f7f9 | ||
|   | b29611509e | ||
|   | dd1cf0ec56 | ||
|   | c04c73bbd7 | ||
|   | 0d287283d4 | ||
|   | 4ea5723b7f | ||
|   | ea964124d6 | ||
|   | 75244853c1 | ||
|   | c361c34b16 | ||
|   | 264b3a785b | ||
|   | bb15e1d8ac | ||
|   | 68860ae866 | ||
|   | 61637f12c7 | ||
|   | 7538649e81 | ||
|   | 31efbe915e | ||
|   | 9e69627626 | ||
|   | dd9da2853a | ||
|   | b4f08fa8d5 | ||
|   | 670461c66f | ||
|   | f6092b9128 | ||
|   | a690cb36ff | ||
|   | 5ca8f4a3aa | ||
|   | ba6e2f0a54 | ||
|   | 149f4e38a0 | ||
|   | b5ee170726 | ||
|   | 04961880fe | ||
|   | e22e8ffa0e | ||
|   | d18d800947 | ||
|   | 3ca58ee65f | ||
|   | 21387b9a83 | ||
|   | ccb0d491ed | ||
|   | daa3200713 | ||
|   | fec2d1f7ee | ||
|   | eb8e95723c | ||
|   | 999bec19f1 | ||
|   | dfb8de2349 | ||
|   | 59f1cdcc82 | ||
|   | 3eb8be6239 | ||
|   | 7dfc4a651d | ||
|   | 189d145393 | ||
|   | 26bec11d76 | ||
|   | 1e7071bff3 | ||
|   | 92390d1d59 | ||
|   | b9b072119b | ||
|   | b6d9fd8030 | ||
|   | d383bc93c7 | ||
|   | af88c68fca | ||
|   | 24537c4fdc | ||
|   | 130f495fb6 | ||
|   | 9d22a06969 | ||
|   | e3783e0236 | ||
|   | a5161eb7f1 | ||
|   | 82e448de7c | ||
|   | 680afe972e | ||
|   | 69ab2ce402 | ||
|   | 4374930065 | ||
|   | 9f3520cba5 | ||
|   | d20cdc099d | ||
|   | 926e9ff3de | ||
|   | 70c277d8a1 | ||
|   | 0a5aac724a | ||
|   | bb91d5495f | ||
|   | 995d94c124 | ||
|   | ee7036f13d | ||
|   | 5a8a8dc292 | ||
|   | 7d84de6690 | ||
| ![dependabot[bot]](/assets/img/avatar_default.png)  | 3520f9e9c2 | ||
|   | b2df7981a9 | ||
|   | 9831e7bc3b | ||
|   | 90e37439e5 | ||
|   | 65f2490e89 | ||
|   | c14a921e5a | ||
|   | 2bc8ffefce | ||
|   | b88d8c85cb | ||
|   | 693f52d984 | ||
|   | 56a3bff42e | ||
|   | bffeec1615 | ||
|   | e4a9f115cb | ||
|   | a717238f76 | ||
|   | 4a567ab97c | ||
|   | 90431b662b | ||
|   | 1c8f349a62 | ||
|   | 217004c70c | ||
|   | a75608628e | ||
|   | 33130f39ee | ||
|   | cae43e97cd | ||
|   | cdfc0f6b71 | ||
|   | bf6a18a414 | ||
|   | 16b66afa7a | ||
|   | 9e446210fb | ||
|   | b0118d2d57 | ||
|   | bc90309dd6 | ||
|   | 52c4093fb0 | ||
|   | b47c12cbee | ||
|   | fb14bc6016 | ||
|   | cd6862b1a7 | ||
|   | 3d9160f2fa | ||
|   | 157a5d9902 | ||
|   | f4972e2be2 | ||
|   | 85c8e6ba42 | ||
|   | 8e79bd8785 | ||
|   | 1ace7ce254 | ||
|   | a00be5b60c | ||
|   | aabe8d1d5e | ||
|   | 3da086438b | ||
|   | c257c86387 | ||
|   | ff3ae14c29 | ||
|   | cd82a34392 | ||
|   | baacd55910 | ||
|   | 511b7c4d92 | ||
|   | f38851b7c6 | ||
|   | 432c5837f0 | ||
|   | cc599f544a | ||
|   | e886c85134 | ||
|   | 05eb716b85 | ||
|   | 61eb7b0a6a | ||
|   | f0dade5856 | ||
|   | 8567f6b13c | ||
|   | b740316918 | ||
|   | 2119d08543 | ||
|   | 599ff66522 | ||
|   | 6d2eb04ada | ||
|   | 0aea75edb7 | ||
|   | 2ca8231ab4 | ||
|   | e00116551c | ||
|   | 4d55e05b07 | ||
|   | 9ff3f85432 | ||
|   | 65c584aeda | ||
|   | 2540a2dfd9 | ||
|   | 70e9187bcb | ||
|   | 5e2fa13471 | ||
|   | 4f8610f895 | ||
|   | 95f9e97af8 | ||
|   | 695b073080 | ||
|   | 3a28935bfe | ||
|   | 468ed1a9ce | ||
|   | a6052d7900 | ||
|   | e42836b07f | ||
|   | 16373919d4 | ||
|   | 92f9c908f6 | ||
|   | 480e1e17c8 | ||
|   | 274f5f2f1f | ||
|   | 02d4f9cbba | ||
|   | d10daf0991 | ||
|   | 8c9656b799 | ||
|   | 396ea3d0ee | ||
|   | 3efee4a855 | ||
|   | ece6759fa7 | ||
|   | 246d945f39 | ||
|   | 4a3bc486d0 | ||
|   | 996d041581 | ||
|   | d48e4adcd4 | ||
|   | 7f84b7ab83 | ||
|   | 3e26bd6a17 | ||
|   | e964c62907 | ||
|   | fbb4965263 | ||
|   | 88139d95a7 | ||
|   | 5875b1988b | ||
|   | 2a2091595b | ||
|   | d77883dd7a | ||
|   | adea7dadec | ||
|   | cf4ce2dc08 | ||
|   | e74dfb2ba6 | ||
|   | aaea9ff018 | ||
|   | 206b88eba2 | ||
|   | 8f5373f034 | ||
|   | dfa0a16487 | ||
|   | 8b9f6f49ef | ||
|   | bcac978810 | ||
|   | d17a41f7f1 | ||
|   | 503f71f004 | ||
|   | 4543288ea7 | ||
|   | 9307105b3f | ||
|   | 567daf9946 | ||
|   | 558b22c36a | ||
|   | f076dddfe3 | ||
|   | af44730418 | ||
|   | 4ec1140cb4 | ||
|   | 2a5d20058f | ||
|   | 51f38e0a76 | ||
|   | 54eb42d658 | ||
|   | a7a6f4cec6 | ||
|   | 3968a8e0dc | ||
|   | 9e8ff27a7f | ||
|   | 7dd3d2b040 | ||
|   | 13678cb8d5 | ||
|   | 890aa6f9ac | ||
|   | 646cf44b83 | ||
|   | bf789ca97b | ||
|   | 9b90ff10f4 | ||
|   | 0cc719a823 | ||
|   | 4cd026dfe9 | ||
|   | 3120b49dba | ||
|   | fb1999c474 | ||
|   | 2c37961f7b | ||
|   | 1abc863f82 | ||
|   | c9be03c0bc | ||
|   | fd89209233 | ||
|   | 2e362fbb64 | ||
|   | 11b687cdc2 | ||
|   | 747c920420 | ||
|   | cac51737cb | ||
|   | 7789379914 | ||
|   | 08e2bfe9a2 | ||
|   | 56a854ec88 | ||
|   | de4ff4e58d | ||
|   | 991c2afedb | ||
|   | cded92662f | ||
|   | 2c3fa0fd8f | ||
|   | ec08432f92 | ||
|   | 1bab4d6937 | ||
|   | d1fed11d0d | ||
|   | e96053e268 | ||
|   | 9b98cbb894 | ||
|   | 349578fb6e | ||
|   | 7c186e4fcc | ||
|   | a4fcbb9f67 | ||
|   | 763b64cc57 | ||
|   | d57e6c5bf2 | ||
|   | 80711cc00a | ||
|   | 8b61b9ebfe | ||
|   | e00e778bce | ||
|   | 81e70925c4 | ||
|   | ddd32bd600 | ||
|   | 2713573b9b | ||
|   | cf2e8bbc0b | ||
|   | bc56c1a0e1 | ||
|   | bfbf7af411 | ||
|   | c151221d12 | ||
|   | b8489724ef | ||
|   | 7a2f556682 | ||
|   | 92d883db87 | ||
|   | cb931d7af0 | ||
|   | 6b54b57cb9 | ||
|   | 1ca4348ca0 | ||
|   | 3ca7006e3a | ||
|   | 339d2a7bf3 | ||
|   | 0d3debf9b9 | ||
|   | 7f74a4f4b5 | ||
|   | 220718cb58 | ||
| ![dependabot[bot]](/assets/img/avatar_default.png)  | be2acbd3eb | ||
|   | 9249c74b7b | ||
|   | 2b87817ba2 | ||
|   | 883c0f9dfe | ||
|   | 3ffc58d442 | ||
|   | 1bb4b0156f | ||
|   | 92d2be3f5e | ||
|   | a7cded21f7 | ||
|   | 74156b7ed8 | ||
|   | 821f320347 | ||
|   | eee9274098 | ||
|   | 8dd1f89225 | ||
|   | f2459ea904 | ||
|   | e51f7bfbff | ||
|   | e2215ced34 | ||
|   | b14c8e82a0 | ||
|   | e7d50d2614 | ||
|   | bca92883d2 | ||
| ![dependabot[bot]](/assets/img/avatar_default.png)  | ed865e38de | ||
|   | dec45109d3 | ||
|   | 48c267c5c1 | ||
|   | c041d39cab | ||
|   | 52c18e77ae | ||
|   | 52a189cdd2 | ||
|   | dca8a47da8 | ||
|   | 6be9317fd7 | ||
|   | bee99ca8d0 | ||
|   | 48dc89cf13 | ||
|   | fc7f609234 | ||
|   | 0bed9b3c2e | ||
|   | 31fa73518b | ||
|   | c6fd11157a | ||
|   | ca73a57de7 | ||
|   | 38a545af92 | ||
|   | b91b340afd | ||
|   | 8e7b1c97df | ||
|   | c9c55fe0c9 | ||
|   | d553160d65 | ||
|   | b8a4df2f50 | ||
|   | 36edbf6ea9 | ||
|   | f966535ea9 | ||
|   | 07cc26a144 | ||
|   | 178c4d15b7 | ||
|   | b0b68c695c | ||
|   | 219a3658d6 | ||
|   | d2310fc2ea | ||
|   | 3fe0ccd934 | ||
|   | f902ebadcc | ||
|   | 57323af167 | ||
|   | 20b0b5fc8e | ||
|   | bb72b8cc93 | ||
|   | fec5516da9 | ||
|   | ec9a092751 | ||
|   | c692cc6a70 | ||
|   | 2b8d8d4e9c | ||
|   | 2ae8032ace | ||
|   | c4416584de | ||
|   | 86d8b49113 | ||
|   | 7a5d870f67 | ||
|   | b43459232a | ||
|   | e2b4e60c9e | ||
|   | 17543535e3 | ||
|   | 901ce23cd2 | ||
|   | 1b52d8065e | ||
|   | c6db901051 | ||
|   | 39edb1ad37 | ||
|   | a397aa188c | ||
|   | dd08751f3f | ||
|   | ef6a9184ba | ||
|   | 575fb6fc60 | ||
|   | 4147d6c67e | ||
|   | 115c17ab90 | ||
|   | d892c7290c | ||
|   | 63d8a902d5 | ||
|   | 43152fcf19 | ||
|   | 1f135f1fa5 | ||
|   | c71d378eab | ||
|   | 6fa5689aaf | ||
|   | d78bef72ea | ||
|   | e410de9552 | ||
|   | 8dc262b415 | ||
|   | 7fa494815f | ||
|   | 929bb70e5a | ||
|   | 36fb262fa0 | ||
|   | b8cc783583 | ||
|   | 67b3d383e4 | ||
|   | 9144ccac6b | ||
|   | 04020d5ae2 | ||
|   | de4f1d09af | ||
|   | 27d7f5f190 | ||
|   | c43c4c42c8 | ||
|   | 613283f656 | ||
|   | 506b6b51ce | ||
|   | c7eccfb714 | ||
|   | 98be19b29f | ||
|   | 66406d86c1 | ||
|   | 35832b07b9 | ||
|   | 357683cbb9 | ||
|   | 15bc6159f9 | ||
|   | 7cdafa76a5 | ||
|   | e84b0c91f8 | ||
|   | cecffee3d3 | ||
|   | d039a40d7c | ||
|   | 90463d8613 | ||
|   | 90c965a6ba | ||
|   | e961691645 | ||
|   | 6270d2408f | ||
|   | 7ef1842237 | ||
|   | faf616cbea | ||
|   | 4a09e18d9a | ||
|   | 983aca515d | ||
|   | eb184d3c68 | ||
|   | 187ecf511f | ||
|   | 0ab35a3ca3 | ||
|   | 8e208bc76d | ||
|   | 1b4d92007e | ||
|   | 4101d7664d | ||
|   | e128c3094a | ||
|   | 95869eeb70 | ||
|   | d977bbd61c | ||
|   | a16a6211e2 | ||
|   | a75013e43e | ||
|   | 1e157e95b6 | ||
|   | 04dbfcd0e6 | ||
|   | 73440e2287 | ||
|   | ee4459691f | ||
|   | 379c6045b9 | ||
|   | 00d0ddb4b5 | ||
|   | be08c01be6 | ||
|   | fb6abe34df | ||
|   | b0d107f916 | ||
|   | 6d1ff7c3f3 | ||
|   | 6f67132f4b | ||
|   | 859d21162c | ||
|   | c739a7ea2f | ||
|   | 7e48875fd4 | ||
|   | 474e86306f | ||
|   | b436a660f1 | ||
|   | d36460e30b | ||
|   | 22b2503839 | ||
|   | 4322d195d3 | ||
|   | 4ecad65926 | ||
|   | f12025b86e | ||
|   | 5cfea54b06 | ||
|   | c24b75953a | ||
|   | f3d52f4932 | ||
|   | ea6d339b9c | ||
|   | 0a0ced3e8e | ||
|   | c51dbae8b6 | ||
|   | f38747aa28 | ||
|   | bd721c1310 | ||
|   | 507e198b70 | ||
|   | 5c721ee435 | ||
|   | 8c5f9b4501 | ||
|   | 87fa14b281 | ||
|   | 043947fdcb | ||
|   | ae7eedf523 | ||
|   | 84628bd9fc | ||
|   | 56a74bc54c | ||
|   | a20358b61b | ||
|   | 341d9d1697 | ||
|   | 9cee424383 | ||
|   | 37cb51cfd6 | ||
|   | 84b7bfb989 | ||
|   | 04d17e4839 | 
							
								
								
									
										21
									
								
								.github/workflows/wled-ci.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -8,21 +8,23 @@ jobs: | ||||
|     name: Gather Environments | ||||
|     runs-on: ubuntu-latest | ||||
|     steps: | ||||
|     - uses: actions/checkout@v2 | ||||
|     - uses: actions/checkout@v3 | ||||
|     - name: Cache pip | ||||
|       uses: actions/cache@v2 | ||||
|       uses: actions/cache@v3 | ||||
|       with: | ||||
|         path: ~/.cache/pip | ||||
|         key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} | ||||
|         restore-keys: | | ||||
|           ${{ runner.os }}-pip- | ||||
|     - uses: actions/setup-python@v2 | ||||
|     - uses: actions/setup-python@v4 | ||||
|       with: | ||||
|         python-version: '3.9' | ||||
|     - name: Install PlatformIO | ||||
|       run: pip install -r requirements.txt | ||||
|     - name: Get default environments | ||||
|       id: envs | ||||
|       run: | | ||||
|         echo "::set-output name=environments::$(pio project config --json-output | jq -cr '.[0][1][0][1]')" | ||||
|         echo "environments=$(pio project config --json-output | jq -cr '.[0][1][0][1]')" >> $GITHUB_OUTPUT | ||||
|     outputs: | ||||
|       environments: ${{ steps.envs.outputs.environments }} | ||||
|  | ||||
| @@ -32,24 +34,27 @@ jobs: | ||||
|     runs-on: ubuntu-latest | ||||
|     needs: get_default_envs | ||||
|     strategy: | ||||
|       fail-fast: false | ||||
|       matrix: | ||||
|         environment: ${{ fromJSON(needs.get_default_envs.outputs.environments) }} | ||||
|     steps: | ||||
|     - uses: actions/checkout@v2 | ||||
|     - uses: actions/checkout@v3 | ||||
|     - name: Cache pip | ||||
|       uses: actions/cache@v2 | ||||
|       uses: actions/cache@v3 | ||||
|       with: | ||||
|         path: ~/.cache/pip | ||||
|         key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} | ||||
|         restore-keys: | | ||||
|           ${{ runner.os }}-pip- | ||||
|     - name: Cache PlatformIO | ||||
|       uses: actions/cache@v2 | ||||
|       uses: actions/cache@v3 | ||||
|       with: | ||||
|         path: ~/.platformio | ||||
|         key: ${{ runner.os }}-${{ hashFiles('**/lockfiles') }} | ||||
|     - name: Set up Python | ||||
|       uses: actions/setup-python@v2 | ||||
|       uses: actions/setup-python@v4 | ||||
|       with: | ||||
|           python-version: '3.9' | ||||
|     - name: Install PlatformIO | ||||
|       run: pip install -r requirements.txt | ||||
|     - name: Build firmware | ||||
|   | ||||
							
								
								
									
										32
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -1,20 +1,24 @@ | ||||
| .pio | ||||
| .cache | ||||
| .clang-format | ||||
| .direnv | ||||
| .DS_Store | ||||
| .gitignore | ||||
| .idea | ||||
| .pio | ||||
| .pioenvs | ||||
| .piolibdeps | ||||
| .vscode | ||||
| /wled00/Release | ||||
| /wled00/extLibs | ||||
| /platformio_override.ini | ||||
| /wled00/my_config.h | ||||
| /build_output | ||||
| .DS_Store | ||||
| .gitignore | ||||
| .clang-format | ||||
| node_modules | ||||
| .idea | ||||
| .direnv | ||||
| wled-update.sh | ||||
|  | ||||
| esp01-update.sh | ||||
| platformio_override.ini | ||||
| replace_fs.py | ||||
| wled-update.sh | ||||
|  | ||||
| /build_output/ | ||||
| /node_modules/ | ||||
|  | ||||
| /wled00/extLibs | ||||
| /wled00/LittleFS | ||||
| replace_fs.py | ||||
| /wled00/my_config.h | ||||
| /wled00/Release | ||||
| /wled00/wled00.ino.cpp | ||||
|   | ||||
							
								
								
									
										238
									
								
								CHANGELOG.md
									
									
									
									
									
								
							
							
						
						| @@ -1,11 +1,241 @@ | ||||
| ## WLED changelog | ||||
|  | ||||
| #### Build 2401060 | ||||
| -   Version bump: 0.14.1-b3 | ||||
| -   Global JSON buffer guarding (#3648 by @willmmiles, resolves #3641, #3312, #3367, #3637, #3646, #3447) | ||||
| -   Fix for #3632 | ||||
| -   Custom palette editor mobile UI enhancement (#3617 by @imeszaros) | ||||
| -   changelog update | ||||
|  | ||||
| #### Build 2312290 | ||||
| -   Fix for #3622, #3613, #3609 | ||||
| -   Various tweaks and fixes | ||||
| -   changelog update | ||||
|  | ||||
| #### Build 2312230 | ||||
| -   Version bump: 0.14.1-b2 | ||||
| -   Fix for Pixel Magic button | ||||
| -   Fix for #2922 (option to force WiFi PHY mode to G on ESP8266) | ||||
| -   Fix for #3601, #3400 (incorrect sunrise/sunset, #3612 by @softhack007) | ||||
|  | ||||
| #### Build 2312180 | ||||
| -   Bugfixes (#3593, #3490, #3573, #3517, #3561, #3555, #3541, #3536, #3515, #3522, #3533, #3508) | ||||
| -   Various other internal cleanups and optimisations | ||||
|  | ||||
| #### Build 2311160 | ||||
| -   Version bump: 0.14.1-b1 | ||||
| -   Bugfixes (#3526, #3502, #3496, #3484, #3487, #3445, #3466, #3296, #3382, #3312) | ||||
| -   New feature: Sort presets by ID | ||||
| -   New usermod: LDR sensor (#3490 by @JeffWDH) | ||||
| -   Effect: Twinklefox & Tinklecat metadata fix | ||||
| -   Effect: separate #HH and #MM for Scrolling Text (#3480) | ||||
| -   SSDR usermod enhancements (#3368) | ||||
| -   PWM fan usermod enhancements (#3414) | ||||
|  | ||||
| #### Build 2310010, build 2310130 | ||||
| -   Release of WLED version 0.14.0 "Hoshi" | ||||
| -   Bugfixes for #3400, #3403, #3405 | ||||
| -   minor HTML optimizations | ||||
| -   audioreactive: bugfix for UDP sound sync (partly initialized packets) | ||||
|  | ||||
| #### Build 2309240 | ||||
| -   Release of WLED beta version 0.14.0-b6 "Hoshi" | ||||
| -   Effect bugfixes and improvements (Meteor, Meteor Smooth, Scrolling Text) | ||||
| -   audioreactive: bugfixes for ES8388 and ES7243 init; minor improvements for analog inputs | ||||
|  | ||||
| #### Build 2309100 | ||||
| -   Release of WLED beta version 0.14.0-b5 "Hoshi" | ||||
| -   New standard esp32 build with audioreactive | ||||
| -   Effect blending bugfixes, and minor optimizations | ||||
|  | ||||
| #### Build 2309050 | ||||
| -   Effect blending (#3311) (finally effect transitions!) | ||||
|     *WARNING*: May not work well with ESP8266, with plenty of segments or usermods (low RAM condition)!!! | ||||
| -   Added receive and send sync groups to JSON API (#3317) (you can change sync groups using preset) | ||||
| -   Internal temperature usermod (#3246) | ||||
| -   MQTT server and topic length overrides (#3354) (new build flags) | ||||
| -   Animated Staircase usermod enhancement (#3348) (on/off toggle/relay control) | ||||
| -   Added local time info to Info page (#3351) | ||||
| -   New effect: Rolling Balls (a.k.a. linear bounce) (#1039) | ||||
| -   Various bug fixes and enhancements. | ||||
|  | ||||
| #### Build 2308110 | ||||
| -   Release of WLED beta version 0.14.0-b4 "Hoshi" | ||||
| -   Reset effect data immediately upon mode change | ||||
|  | ||||
| #### Build 2308030 | ||||
| -   Improved random palette handling and blending | ||||
| -   Soap bugfix | ||||
| -   Fix ESP-NOW crash with AP mode Always | ||||
|  | ||||
| #### Build 2307180 | ||||
| -   Bus-level global buffering (#3280) | ||||
| -   Removed per-segment LED buffer (SEGMENT.leds) | ||||
| -   various fixes and improvements (ESP variants platform 5.3.0, effect optimizations, /json/cfg pin allocation) | ||||
|  | ||||
| #### Build 2307130 | ||||
| -   larger `oappend()` stack buffer (3.5k) for ESP32 | ||||
| -   Preset cycle bugfix (#3262) | ||||
| -   Rotary encoder ALT fix for large LED count (#3276) | ||||
| -   effect updates (2D Plasmaball), `blur()` speedup | ||||
| -   On/Off toggle from nodes view (may show unknown device type on older versions) (#3291) | ||||
| -   various fixes and improvements (ABL, crashes when changing presets with different segments) | ||||
|  | ||||
| #### Build 2306270 | ||||
| -   ESP-NOW remote support (#3237) | ||||
| -   Pixel Magic tool (display pixel art) (#3249) | ||||
| -   Websocket (peek) fallback when connection cannot be established, WS retries (#3267) | ||||
| -   Add WiFi network scan RPC command to Improv Serial (#3271) | ||||
| -   Longer (custom option available) segment name for ESP32 | ||||
| -   various fixes and improvements | ||||
|  | ||||
| #### Build 2306210 | ||||
| -   0.14.0-b3 release | ||||
| -   respect global I2C in all usermods (no local initialization of I2C bus) | ||||
| -   Multi relay usermod compile-time enabled option (-D MULTI_RELAY_ENABLED=true|false) | ||||
|  | ||||
| #### Build 2306180 | ||||
| -   Added client-side option for applying effect defaults from metadata | ||||
| -   Improved ESP8266 stability by reducing WebSocket response resends | ||||
| -   Updated ESP8266 core to 3.1.2 | ||||
|  | ||||
| #### Build 2306141 | ||||
| -   Lissajous improvements | ||||
| -   Scrolling Text improvements (leading 0) | ||||
|  | ||||
| #### Build 2306140 | ||||
| -   Add settings PIN (un)locking to JSON post API | ||||
|  | ||||
| #### Build 2306130 | ||||
| -   Bumped version to 0.14-b3 (beta 3) | ||||
| -   added pin dropdowns in LED preferences (not for LED pins) and usermods | ||||
| -   introduced (unused ATM) NeoGammaWLEDMethod class | ||||
| -   Reverse proxy support | ||||
| -   PCF8754 support for Rotary encoder (requires wiring INT pin to ESP GPIO) | ||||
| -   Rely on global I2C pins for usermods (breaking change) | ||||
| -   various fixes and enhancements | ||||
|  | ||||
| #### Build 2306020 | ||||
| -   Support for segment sets (PR #3171) | ||||
| -   Reduce sound simulation modes to 2 to facilitate segment sets | ||||
| -   Trigger button immediately on press if all configured presets are the same (PR #3226) | ||||
| -   Changes for allowing Alexa to change light color to White when auto-calculating from RGB (PR #3211) | ||||
|  | ||||
| #### Build 2305280 | ||||
| -   DDP protocol update (#3193) | ||||
| -   added PCF8574 I2C port expander support for Multi relay usermod | ||||
| -   MQTT multipacket (fragmented) message fix | ||||
| -   added option to retain MQTT brightness and color messages | ||||
| -   new ethernet board: @srg74 Ethernet Shield | ||||
| -   new 2D effects: Soap (#3184) & Octopus & Waving cell (credit @St3P40 https://github.com/80Stepko08) | ||||
| -   various fixes and enhancements | ||||
|  | ||||
| #### Build 2305090 | ||||
| -   new ethernet board: @Wladi ABC! WLED Eth | ||||
| -   Battery usermod voltage calculation (#3116) | ||||
| -   custom palette editor (#3164) | ||||
| -   improvements in Dancing Shadows and Tartan effects | ||||
| -   UCS389x support | ||||
| -   switched to NeoPixelBus 2.7.5 (replaced NeoPixelBrightnessBus with NeoPixelBusLg) | ||||
| -   SPI bus clock selection (for LEDs) (#3173) | ||||
| -   DMX mode preset fix (#3134) | ||||
| -   iOS fix for scroll (#3182) | ||||
| -   Wordclock "Norddeutsch" fix (#3161) | ||||
| -   various fixes and enhancements | ||||
|  | ||||
| #### Build 2304090 | ||||
| -   updated Arduino ESP8266 core to 4.1.0 (newer compiler) | ||||
| -   updated NeoPixelBus to 2.7.3 (with support for UCS890x chipset) | ||||
| -   better support for ESP32-C3, ESP32-S2 and ESP32-S3 (Arduino ESP32 core 5.2.0) | ||||
| -   iPad/tablet with 1024 pixels width in landscape orientation PC mode support (#3153) | ||||
| -   fix for Pixel Art Converter (#3155) | ||||
|  | ||||
| #### Build 2303240 | ||||
| -   Peek scaling of large 2D matrices | ||||
| -   Added 0D (1 pixel) metadata for effects & enhance 0D (analog strip) UI handling | ||||
| -   Added ability to disable ADAlight (-D WLED_DISABLE_ADALIGHT) | ||||
| -   Fixed APA102 output on Ethernet enabled controllers | ||||
| -   Added ArtNet virtual/network output (#3121) | ||||
| -   Klipper usermod (#3106) | ||||
| -   Remove DST from CST timezone | ||||
| -   various fixes and enhancements | ||||
|  | ||||
| #### Build 2302180 | ||||
|  | ||||
| -   Removed Blynk support (servers shut down on 31st Dec 2022) | ||||
| -   Added `ledgap.json` to complement ledmaps for 2D matrices | ||||
| -   Added support for white addressable strips (#3073) | ||||
| -   Ability to use SHT temperature usermod with PWM fan usermod | ||||
| -   Added `onStateChange()` callback to usermods (#3081) | ||||
| -   Refactored `bus_manager` [internal] | ||||
| -   Dual 1D & 2D mode (add 1D strip after the matrix) | ||||
| -   Removed 1D -> 2D mapping for individual pixel control | ||||
| -   effect tweak: Fireworks 1D | ||||
| -   various bugfixes | ||||
|  | ||||
| #### Build 2301240 | ||||
|  | ||||
| -   Version bump to v0.14.0-b2 "Hoshi" | ||||
| -   PixelArt converter (convert any image to pixel art and display it on a matrix) (PR #3042) | ||||
| -   various effect updates and optimisations | ||||
|     -   added Overlay option to some effects (allows overlapping segments) | ||||
|     -   added gradient text on Scrolling Text | ||||
|     -   added #DDMM, #MMDD & #HHMM date and time options for Scrolling Text effect (PR #2990) | ||||
|     -   deprecated: Dynamic Smooth, Dissolve Rnd, Solid Glitter | ||||
|     -   optimised & enhanced loading of default values | ||||
|     -   new effect: Distortion Waves (2D) | ||||
|     -   2D support for Ripple effect | ||||
|     -   slower minimum speed for Railway effect | ||||
| -   DMX effect mode & segment controls (PR #2891) | ||||
| -   Optimisations for conditional compiles (further reduction of code size) | ||||
| -   better UX with effect sliders (PR #3012) | ||||
| -   enhanced support for ESP32 variants: C3, S2 & S3 | ||||
| -   usermod enhancements (PIR, Temperature, Battery (PR #2975), Analog Clock (PR #2993)) | ||||
| -   new usermod SHT (PR #2963) | ||||
| -   2D matrix set up with gaps or irregular panels (breaking change!) (PR #2892) | ||||
| -   palette blending/transitions | ||||
| -   random palette smooth changes | ||||
| -   hex color notations in custom palettes | ||||
| -   allow more virtual buses | ||||
| -   plethora of bugfixes | ||||
|  | ||||
| ### WLED release 0.14.0-b1 | ||||
|  | ||||
| #### Build 2212222 | ||||
|  | ||||
| -   Version bump to v0.14.0-b1 "Hoshi" | ||||
| -   Full changelog TBD | ||||
| -   2D matrix support (including mapping 1D effects to 2D and 2D peek) | ||||
| -   [internal] completely rewritten Segment & WS2812FX handling code | ||||
| -   [internal] ability to add custom effects via usermods | ||||
| -   [internal] set of 2D drawing functions | ||||
| -   transitions on every segment (including ESP8266) | ||||
| -   enhanced old and new 2D effects (metadata: default values) | ||||
| -   custom palettes (up to 10; upload palette0.json, palette1.json, ...) | ||||
| -   custom effect sliders and options, quick filters | ||||
| -   global I2C and SPI GPIO allocation (for usermods) | ||||
| -   usermod settings page enhancements (dropdown & info) | ||||
| -   asynchronous preset loading (and added "pd" JSON API call for direct preset apply) | ||||
| -   new usermod Boblight (PR #2917) | ||||
| -   new usermod PWM Outputs (PR #2912) | ||||
| -   new usermod Audioreactive | ||||
| -   new usermod Word Clock Matrix (PR #2743) | ||||
| -   new usermod Ping Pong Clock (PR #2746) | ||||
| -   new usermod ADS1115 (PR #2752) | ||||
| -   new usermod Analog Clock (PR #2736) | ||||
| -   various usermod enhancements and updates | ||||
| -   allow disabling pull-up resistors on buttons | ||||
| -   SD card support (PR #2877) | ||||
| -   enhanced HTTP API to support custom effect sliders & options (X1, X2, X3, M1, M2, M3) | ||||
| -   multiple UDP sync message retries (PR #2830) | ||||
| -   network debug printer (PR #2870) | ||||
| -   automatic UI PC mode on large displays | ||||
| -   removed support for upgrading from pre-0.10 (EEPROM) | ||||
| -   support for setting GPIO level when LEDs are off (RMT idle level, ESP32 only) (PR #2478) | ||||
| -   Pakistan time-zone (PKT) | ||||
| -   ArtPoll support | ||||
| -   TM1829 LED support | ||||
| -   experimental support for ESP32 S2, S3 and C3 | ||||
| -   general improvements and bugfixes | ||||
|  | ||||
| ### WLED release 0.13.3 | ||||
|  | ||||
| @@ -224,7 +454,7 @@ | ||||
|  | ||||
| -   Added application level pong websockets reply (#2139) | ||||
| -   Use AsyncTCP 1.0.3 as it mitigates the flickering issue from 0.13.0-b2 | ||||
| -   Fixed transition manually updated in preset overriden by field value | ||||
| -   Fixed transition manually updated in preset overridden by field value | ||||
|  | ||||
| #### Build 2108050 | ||||
|  | ||||
| @@ -753,7 +983,7 @@ | ||||
|  | ||||
| #### Build 2011040 | ||||
|  | ||||
| -   Inversed Rain direction (fixes #1147) | ||||
| -   Inverted Rain direction (fixes #1147) | ||||
|  | ||||
| #### Build 2011010 | ||||
|  | ||||
| @@ -964,7 +1194,7 @@ | ||||
|  | ||||
| -   Added module info page to web UI | ||||
| -   Added realtime override functionality to web UI | ||||
| -   Added individial segment power and brightness to web UI | ||||
| -   Added individual segment power and brightness to web UI | ||||
| -   Added feature to one-click select single segment only by tapping segment name | ||||
| -   Removed palette jumping to default if color is changed | ||||
|  | ||||
|   | ||||
							
								
								
									
										729
									
								
								package-lock.json
									
									
									
										generated
									
									
									
								
							
							
						
						| @@ -1,6 +1,6 @@ | ||||
| { | ||||
|   "name": "wled", | ||||
|   "version": "0.14.0-b1", | ||||
|   "version": "0.14.1-b3", | ||||
|   "description": "Tools for WLED project", | ||||
|   "main": "tools/cdata.js", | ||||
|   "directories": { | ||||
| @@ -25,7 +25,7 @@ | ||||
|     "clean-css": "^4.2.3", | ||||
|     "html-minifier-terser": "^5.1.1", | ||||
|     "inliner": "^1.13.1", | ||||
|     "nodemon": "^2.0.4", | ||||
|     "nodemon": "^2.0.20", | ||||
|     "zlib": "^1.0.5" | ||||
|   } | ||||
| } | ||||
|   | ||||
							
								
								
									
										356
									
								
								platformio.ini
									
									
									
									
									
								
							
							
						
						| @@ -9,11 +9,15 @@ | ||||
| # (use `platformio_override.ini` when building for your own board; see `platformio_override.ini.sample` for an example) | ||||
| # ------------------------------------------------------------------------------ | ||||
|  | ||||
| # Release / CI binaries | ||||
| default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, esp32s2_saola, esp32c3, esp32s3dev_8MB | ||||
| # CI binaries | ||||
| ; default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth # ESP32 variant builds are temporarily excluded from CI due to toolchain issues on the GitHub Actions Linux environment | ||||
| default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, esp32dev_audioreactive, lolin_s2_mini, esp32c3dev, esp32s3dev_8MB, esp32s3dev_8MB_PSRAM_opi | ||||
|  | ||||
| # Release binaries | ||||
| ; default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, lolin_s2_mini, esp32c3dev, esp32s3dev_8MB | ||||
|  | ||||
| # Build everything | ||||
| ; default_envs = esp32dev, esp8285_4CH_MagicHome, codm-controller-0.6-rev2, codm-controller-0.6, esp32s2_saola, d1_mini_5CH_Shojo_PCB, d1_mini, sp501e, nodemcuv2, esp32_eth, anavi_miracle_controller, esp07, esp01_1m_full, m5atom, h803wf, d1_mini_ota, heltec_wifi_kit_8, esp8285_H801, d1_mini_debug, wemos_shield_esp32, elekstube_ips | ||||
| ; default_envs = esp32dev, esp8285_4CH_MagicHome, codm-controller-0_6-rev2, codm-controller-0_6, esp32s2_saola, d1_mini_5CH_Shojo_PCB, d1_mini, sp501e, nodemcuv2, esp32_eth, anavi_miracle_controller, esp07, esp01_1m_full, m5atom, h803wf, d1_mini_ota, heltec_wifi_kit_8, esp8285_H801, d1_mini_debug, wemos_shield_esp32, elekstube_ips | ||||
|  | ||||
| # Single binaries (uncomment your board) | ||||
| ; default_envs = elekstube_ips | ||||
| @@ -36,6 +40,9 @@ default_envs = nodemcuv2, esp8266_2m, esp01_1m_full, esp32dev, esp32_eth, esp32s | ||||
| ; default_envs = esp32dev_qio80 | ||||
| ; default_envs = esp32_eth_ota1mapp | ||||
| ; default_envs = esp32s2_saola | ||||
| ; default_envs = esp32c3dev | ||||
| ; default_envs = lolin_s2_mini | ||||
| ; default_envs = esp32s3dev_16MB_PSRAM_opi | ||||
|  | ||||
| src_dir  = ./wled00 | ||||
| data_dir = ./wled00/data | ||||
| @@ -55,26 +62,39 @@ arduino_core_2_6_3 = espressif8266@2.3.3 | ||||
| arduino_core_2_7_4 = espressif8266@2.6.2 | ||||
| arduino_core_3_0_0 = espressif8266@3.0.0 | ||||
| arduino_core_3_2_0 = espressif8266@3.2.0 | ||||
| arduino_core_4_1_0 = espressif8266@4.1.0 | ||||
| arduino_core_3_1_2 = espressif8266@4.2.0 | ||||
|  | ||||
| # Development platforms | ||||
| arduino_core_develop = https://github.com/platformio/platform-espressif8266#develop | ||||
| arduino_core_git = https://github.com/platformio/platform-espressif8266#feature/stage | ||||
|  | ||||
| # Platform to use for ESP8266 | ||||
| platform_wled_default = ${common.arduino_core_3_2_0} | ||||
| platform_wled_default = ${common.arduino_core_3_1_2} | ||||
| # We use 2.7.4.7 for all, includes PWM flicker fix and Wstring optimization | ||||
| platform_packages = tasmota/framework-arduinoespressif8266 @ 3.20704.7 | ||||
|                     platformio/toolchain-xtensa @ ~2.40802.200502 | ||||
|                     platformio/tool-esptool @ ~1.413.0 | ||||
|                     platformio/tool-esptoolpy @ ~1.30000.0 | ||||
| #platform_packages = tasmota/framework-arduinoespressif8266 @ 3.20704.7 | ||||
| platform_packages = platformio/framework-arduinoespressif8266 | ||||
|                     platformio/toolchain-xtensa @ ~2.100300.220621 #2.40802.200502 | ||||
|                     platformio/tool-esptool #@ ~1.413.0 | ||||
|                     platformio/tool-esptoolpy #@ ~1.30000.0 | ||||
|  | ||||
| ## previous platform for 8266, in case of problems with the new one | ||||
| ## you'll need  makuna/NeoPixelBus@ 2.6.9 for arduino_core_3_2_0, which does not support Ucs890x | ||||
| ;; platform_wled_default = ${common.arduino_core_3_2_0} | ||||
| ;; platform_packages = tasmota/framework-arduinoespressif8266 @ 3.20704.7 | ||||
| ;;                    platformio/toolchain-xtensa @ ~2.40802.200502 | ||||
| ;;                    platformio/tool-esptool @ ~1.413.0 | ||||
| ;;                    platformio/tool-esptoolpy @ ~1.30000.0 | ||||
|  | ||||
| # ------------------------------------------------------------------------------ | ||||
| # FLAGS: DEBUG | ||||
| # | ||||
| # esp8266 : see https://docs.platformio.org/en/latest/platforms/espressif8266.html#debug-level | ||||
| # esp32   : see https://docs.platformio.org/en/latest/platforms/espressif32.html#debug-level | ||||
| # ------------------------------------------------------------------------------ | ||||
| debug_flags = -D DEBUG=1 -D WLED_DEBUG -DDEBUG_ESP_WIFI -DDEBUG_ESP_HTTP_CLIENT -DDEBUG_ESP_HTTP_UPDATE -DDEBUG_ESP_HTTP_SERVER -DDEBUG_ESP_UPDATER -DDEBUG_ESP_OTA -DDEBUG_TLS_MEM | ||||
| #if needed (for memleaks etc) also add; -DDEBUG_ESP_OOM -include "umm_malloc/umm_malloc_cfg.h" | ||||
| #-DDEBUG_ESP_CORE is not working right now | ||||
| debug_flags = -D DEBUG=1 -D WLED_DEBUG | ||||
|   -DDEBUG_ESP_WIFI -DDEBUG_ESP_HTTP_CLIENT -DDEBUG_ESP_HTTP_UPDATE -DDEBUG_ESP_HTTP_SERVER -DDEBUG_ESP_UPDATER -DDEBUG_ESP_OTA -DDEBUG_TLS_MEM ;; for esp8266 | ||||
|   # if needed (for memleaks etc) also add; -DDEBUG_ESP_OOM -include "umm_malloc/umm_malloc_cfg.h" | ||||
|   # -DDEBUG_ESP_CORE is not working right now | ||||
|  | ||||
| # ------------------------------------------------------------------------------ | ||||
| # FLAGS: ldscript (available ldscripts at https://github.com/esp8266/Arduino/tree/master/tools/sdk/ld) | ||||
| @@ -99,11 +119,13 @@ debug_flags = -D DEBUG=1 -D WLED_DEBUG -DDEBUG_ESP_WIFI -DDEBUG_ESP_HTTP_CLIENT | ||||
| #  This reduces the OTA size with ~45KB, so it's especially useful on low memory boards (512k/1m). | ||||
| # ------------------------------------------------------------------------------ | ||||
| build_flags = | ||||
|   -Wno-attributes | ||||
|   -DMQTT_MAX_PACKET_SIZE=1024 | ||||
|   -DSECURE_CLIENT=SECURE_CLIENT_BEARSSL | ||||
|   -DBEARSSL_SSL_BASIC | ||||
|   -D CORE_DEBUG_LEVEL=0 | ||||
|   -D NDEBUG | ||||
|   -Wno-attributes ;; silence warnings about unknown attribute 'maybe_unused' in NeoPixelBus | ||||
|   #build_flags for the IRremoteESP8266 library (enabled decoders have to appear here) | ||||
|   -D _IR_ENABLE_DEFAULT_=false | ||||
|   -D DECODE_HASH=true | ||||
| @@ -111,7 +133,7 @@ build_flags = | ||||
|   -D DECODE_SONY=true | ||||
|   -D DECODE_SAMSUNG=true | ||||
|   -D DECODE_LG=true | ||||
|   ; -Dregister= # remove warnings in C++17 due to use of deprecated register keyword by the FastLED library | ||||
|   ;-Dregister= # remove warnings in C++17 due to use of deprecated register keyword by the FastLED library ;; warning: this breaks framework code on ESP32-C3 and ESP32-S2 | ||||
|   -DWLED_USE_MY_CONFIG | ||||
|   ; -D USERMOD_SENSORSTOMQTT | ||||
|   #For ADS1115 sensor uncomment following | ||||
| @@ -121,6 +143,7 @@ build_unflags = | ||||
|  | ||||
| build_flags_esp8266 = ${common.build_flags}  ${esp8266.build_flags} | ||||
| build_flags_esp32   = ${common.build_flags}  ${esp32.build_flags} | ||||
| build_flags_esp32_V4= ${common.build_flags}  ${esp32_idf_V4.build_flags} | ||||
|  | ||||
| ldscript_1m128k = eagle.flash.1m128.ld | ||||
| ldscript_2m512k = eagle.flash.2m512.ld | ||||
| @@ -150,24 +173,23 @@ upload_speed = 115200 | ||||
| # LIBRARIES: required dependencies | ||||
| #   Please note that we don't always use the latest version of a library. | ||||
| # | ||||
| #   The following libraries have been included (and some of them changd) in the source: | ||||
| #     ArduinoJson@5.13.5, Blynk@0.5.4(changed), E131@1.0.0(changed), Time@1.5, Timezone@1.2.1 | ||||
| #   The following libraries have been included (and some of them changed) in the source: | ||||
| #     ArduinoJson@5.13.5, E131@1.0.0(changed), Time@1.5, Timezone@1.2.1 | ||||
| # ------------------------------------------------------------------------------ | ||||
| lib_compat_mode = strict | ||||
| lib_deps = | ||||
|     fastled/FastLED @ 3.5.0 | ||||
|     fastled/FastLED @ 3.6.0 | ||||
|     IRremoteESP8266 @ 2.8.2 | ||||
|     makuna/NeoPixelBus @ 2.7.5 | ||||
|     https://github.com/Aircoookie/ESPAsyncWebServer.git @ ~2.0.7 | ||||
|   #For use of the TTGO T-Display ESP32 Module with integrated TFT display uncomment the following line | ||||
|     #TFT_eSPI | ||||
|   #For use SSD1306 OLED display uncomment following | ||||
|     #U8g2@~2.28.8 | ||||
|     #U8g2@~2.32.10 | ||||
|   #For Dallas sensor uncomment following 2 lines | ||||
|     #OneWire@~2.3.5 | ||||
|     #milesburton/DallasTemperature@^3.9.0 | ||||
|   #For compatible OLED display uncomment following | ||||
|     #U8g2 #@ ~2.33.15 | ||||
|   #For Dallas sensor uncomment following | ||||
|     #OneWire @ ~2.3.7 | ||||
|   #For BME280 sensor uncomment following | ||||
|     #BME280@~3.0.0 | ||||
|     #BME280 @ ~3.0.0 | ||||
|     ; adafruit/Adafruit BMP280 Library @ 2.1.0 | ||||
|     ; adafruit/Adafruit CCS811 Library @ 1.0.4 | ||||
|     ; adafruit/Adafruit Si7021 Library @ 1.4.0 | ||||
| @@ -182,69 +204,95 @@ build_flags = | ||||
|   -DESP8266 | ||||
|   -DFP_IN_IROM | ||||
|   ;-Wno-deprecated-declarations | ||||
|   ;-Wno-register | ||||
| 	;-Wno-misleading-indentation | ||||
| ; NONOSDK22x_190703 = 2.2.2-dev(38a443e) | ||||
|   ;-Wno-register  ;; leaves some warnings when compiling C files: command-line option '-Wno-register' is valid for C++/ObjC++ but not for C | ||||
|   ;-Dregister= # remove warnings in C++17 due to use of deprecated register keyword by the FastLED library ;; warning: this can be dangerous | ||||
|   -Wno-misleading-indentation | ||||
|   ; NONOSDK22x_190703 = 2.2.2-dev(38a443e) | ||||
|   -DPIO_FRAMEWORK_ARDUINO_ESPRESSIF_SDK22x_190703 | ||||
| ; lwIP 2 - Higher Bandwidth no Features | ||||
| ;  -DPIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH_LOW_FLASH | ||||
| ; lwIP 1.4 - Higher Bandwidth (Aircoookie has) | ||||
|    -DPIO_FRAMEWORK_ARDUINO_LWIP_HIGHER_BANDWIDTH | ||||
| ; VTABLES in Flash | ||||
|   ; lwIP 2 - Higher Bandwidth no Features | ||||
|   ;  -DPIO_FRAMEWORK_ARDUINO_LWIP2_HIGHER_BANDWIDTH_LOW_FLASH | ||||
|   ; lwIP 1.4 - Higher Bandwidth (Aircoookie has) | ||||
|   -DPIO_FRAMEWORK_ARDUINO_LWIP_HIGHER_BANDWIDTH | ||||
|   ; VTABLES in Flash | ||||
|   -DVTABLES_IN_FLASH | ||||
| ; restrict to minimal mime-types | ||||
|   ; restrict to minimal mime-types | ||||
|   -DMIMETYPE_MINIMAL | ||||
|   ; other special-purpose framework flags (see https://docs.platformio.org/en/latest/platforms/espressif8266.html) | ||||
|   -D PIO_FRAMEWORK_ARDUINO_MMU_CACHE16_IRAM48 ;; in case of linker errors like "section `.text1' will not fit in region `iram1_0_seg'" | ||||
|   ; -D PIO_FRAMEWORK_ARDUINO_MMU_CACHE16_IRAM48_SECHEAP_SHARED ;; (experimental) adds some extra heap, but may cause slowdown | ||||
|  | ||||
| lib_deps =  | ||||
|   ${env.lib_deps} | ||||
| lib_deps = | ||||
|   #https://github.com/lorol/LITTLEFS.git | ||||
|   ESPAsyncTCP @ 1.2.2 | ||||
|   ESPAsyncUDP | ||||
|   makuna/NeoPixelBus @ 2.6.9 | ||||
|   ${env.lib_deps} | ||||
|  | ||||
| [esp32] | ||||
| #platform = https://github.com/tasmota/platform-espressif32/releases/download/v2.0.2.3/platform-espressif32-2.0.2.3.zip | ||||
| platform = espressif32@3.5.0 | ||||
|  | ||||
| platform_packages = framework-arduinoespressif32 @ https://github.com/Aircoookie/arduino-esp32.git#1.0.6.4 | ||||
|  | ||||
| build_flags = -g | ||||
|   -DARDUINO_ARCH_ESP32 | ||||
|   #-DCONFIG_LITTLEFS_FOR_IDF_3_2 | ||||
|   -D CONFIG_ASYNC_TCP_USE_WDT=0 | ||||
| #use LITTLEFS library by lorol in ESP32 core 1.x.x instead of built-in in 2.x.x | ||||
|   #use LITTLEFS library by lorol in ESP32 core 1.x.x instead of built-in in 2.x.x | ||||
|   -D LOROL_LITTLEFS | ||||
|   ; -DARDUINO_USB_CDC_ON_BOOT=0 ;; this flag is mandatory for "classic ESP32" when builing with arduino-esp32 >=2.0.3 | ||||
|  | ||||
|   ; -DARDUINO_USB_CDC_ON_BOOT=0 ;; this flag is mandatory for "classic ESP32" when building with arduino-esp32 >=2.0.3 | ||||
| default_partitions = tools/WLED_ESP32_4MB_1MB_FS.csv | ||||
|  | ||||
| lib_deps = | ||||
|   ${env.lib_deps} | ||||
|   https://github.com/lorol/LITTLEFS.git | ||||
|   makuna/NeoPixelBus @ 2.6.9 | ||||
|   https://github.com/pbolduc/AsyncTCP.git @ 1.2.0 | ||||
|   ${env.lib_deps} | ||||
| # additional build flags for audioreactive | ||||
| AR_build_flags = -D USERMOD_AUDIOREACTIVE -D UM_AUDIOREACTIVE_USE_NEW_FFT | ||||
| AR_lib_deps = https://github.com/kosme/arduinoFFT#develop @ ^1.9.2 | ||||
|  | ||||
| [esp32_idf_V4] | ||||
| ;; experimental build environment for ESP32 using ESP-IDF 4.4.x / arduino-esp32 v2.0.5 | ||||
| ;; very similar to the normal ESP32 flags, but omitting Lorol LittleFS, as littlefs is included in the new framework already. | ||||
| ;; | ||||
| ;; please note that you can NOT update existing ESP32 installs with a "V4" build. Also updating by OTA will not work properly. | ||||
| ;; You need to completely erase your device (esptool erase_flash) first, then install the "V4" build from VSCode+platformio. | ||||
| platform = espressif32@5.3.0 | ||||
| platform_packages = | ||||
| build_flags = -g | ||||
|   -Wshadow=compatible-local ;; emit warning in case a local variable "shadows" another local one | ||||
|   -DARDUINO_ARCH_ESP32 -DESP32 | ||||
|   #-DCONFIG_LITTLEFS_FOR_IDF_3_2 | ||||
|   -D CONFIG_ASYNC_TCP_USE_WDT=0 | ||||
|   -DARDUINO_USB_CDC_ON_BOOT=0 ;; this flag is mandatory for "classic ESP32" when building with arduino-esp32 >=2.0.3 | ||||
| default_partitions = tools/WLED_ESP32_4MB_1MB_FS.csv | ||||
| lib_deps = | ||||
|   https://github.com/pbolduc/AsyncTCP.git @ 1.2.0 | ||||
|   ${env.lib_deps} | ||||
|  | ||||
| [esp32s2] | ||||
| ;; generic definitions for all ESP32-S2 boards | ||||
| platform = espressif32@5.3.0 | ||||
| platform_packages = | ||||
| build_flags = -g | ||||
|   -DARDUINO_ARCH_ESP32 | ||||
|   -DARDUINO_ARCH_ESP32S2 | ||||
|   -DCONFIG_IDF_TARGET_ESP32S2 | ||||
|   -DCONFIG_IDF_TARGET_ESP32S2=1 | ||||
|   -D CONFIG_ASYNC_TCP_USE_WDT=0 | ||||
|   -DARDUINO_USB_MSC_ON_BOOT=0 -DARDUINO_USB_DFU_ON_BOOT=0 | ||||
|   -DCO | ||||
|   -DARDUINO_USB_MODE=0 ;; this flag is mandatory for ESP32-S2 ! | ||||
|   ;; please make sure that the following flags are properly set (to 0 or 1) by your board.json, or included in your custom platformio_override.ini entry: | ||||
|   ;; ARDUINO_USB_CDC_ON_BOOT, ARDUINO_USB_MSC_ON_BOOT, ARDUINO_USB_DFU_ON_BOOT | ||||
|   ;; ARDUINO_USB_CDC_ON_BOOT | ||||
|  | ||||
| lib_deps = | ||||
|   ${env.lib_deps} | ||||
|   makuna/NeoPixelBus @ 2.6.9 | ||||
|   https://github.com/pbolduc/AsyncTCP.git @ 1.2.0 | ||||
|   ${env.lib_deps} | ||||
|  | ||||
| [esp32c3] | ||||
| ;; generic definitions for all ESP32-C3 boards | ||||
| platform = espressif32@5.3.0 | ||||
| platform_packages = | ||||
| build_flags = -g | ||||
|   -DARDUINO_ARCH_ESP32 | ||||
|   -DARDUINO_ARCH_ESP32C3 | ||||
|   -DCONFIG_IDF_TARGET_ESP32C3 | ||||
|   -DCONFIG_IDF_TARGET_ESP32C3=1 | ||||
|   -D CONFIG_ASYNC_TCP_USE_WDT=0 | ||||
|   -DCO | ||||
|   -DARDUINO_USB_MODE=1 ;; this flag is mandatory for ESP32-C3 | ||||
| @@ -252,27 +300,27 @@ build_flags = -g | ||||
|   ;; ARDUINO_USB_CDC_ON_BOOT | ||||
|  | ||||
| lib_deps = | ||||
|   ${env.lib_deps} | ||||
|   makuna/NeoPixelBus @ 2.6.9 | ||||
|   https://github.com/pbolduc/AsyncTCP.git @ 1.2.0 | ||||
|   ${env.lib_deps} | ||||
|  | ||||
| [esp32s3] | ||||
| ;; generic definitions for all ESP32-S3 boards | ||||
| platform = espressif32@5.3.0 | ||||
| platform_packages = | ||||
| build_flags = -g | ||||
|   -DESP32 | ||||
|   -DARDUINO_ARCH_ESP32 | ||||
|   -DARDUINO_ARCH_ESP32S3 | ||||
|   -DCONFIG_IDF_TARGET_ESP32S3 | ||||
|   -DCONFIG_IDF_TARGET_ESP32S3=1 | ||||
|   -D CONFIG_ASYNC_TCP_USE_WDT=0 | ||||
|   -DARDUINO_USB_MSC_ON_BOOT=0 -DARDUINO_DFU_ON_BOOT=0 | ||||
|   -DCO | ||||
|   ;; please make sure that the following flags are properly set (to 0 or 1) by your board.json, or included in your custom platformio_override.ini entry: | ||||
|   ;; ARDUINO_USB_MODE, ARDUINO_USB_CDC_ON_BOOT, ARDUINO_USB_MSC_ON_BOOT, ARDUINO_USB_DFU_ON_BOOT | ||||
|   ;; ARDUINO_USB_MODE, ARDUINO_USB_CDC_ON_BOOT | ||||
|  | ||||
| lib_deps = | ||||
|   ${env.lib_deps} | ||||
|   ;; NeoPixelBus 2.7.1 is the first that has official support for ESP32-S3 | ||||
|   makuna/NeoPixelBus @ ~2.7.1 | ||||
|   https://github.com/pbolduc/AsyncTCP.git @ 1.2.0 | ||||
|   ${env.lib_deps} | ||||
|  | ||||
|  | ||||
| # ------------------------------------------------------------------------------ | ||||
| @@ -285,7 +333,7 @@ platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| board_build.ldscript = ${common.ldscript_4m1m} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D WLED_DISABLE_BLYNK #-DWLED_DISABLE_2D | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 #-DWLED_DISABLE_2D | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
| monitor_filters = esp8266_exception_decoder | ||||
|  | ||||
| @@ -295,7 +343,7 @@ platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| board_build.ldscript = ${common.ldscript_2m512k} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP02 -D WLED_DISABLE_BLYNK | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP02 | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
| [env:esp01_1m_full] | ||||
| @@ -304,7 +352,8 @@ platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| board_build.ldscript = ${common.ldscript_1m128k} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP01 -D WLED_DISABLE_OTA -D WLED_DISABLE_BLYNK | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP01 -D WLED_DISABLE_OTA | ||||
|   ; -D WLED_USE_UNREAL_MATH ;; may cause wrong sunset/sunrise times, but saves 7064 bytes FLASH and 975 bytes RAM | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
| [env:esp07] | ||||
| @@ -350,30 +399,60 @@ board = esp32dev | ||||
| platform = ${esp32.platform} | ||||
| platform_packages = ${esp32.platform_packages} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32 -D WLED_DISABLE_BLYNK #-D WLED_DISABLE_BROWNOUT_DET | ||||
| build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32 #-D WLED_DISABLE_BROWNOUT_DET | ||||
| lib_deps = ${esp32.lib_deps} | ||||
| monitor_filters = esp32_exception_decoder | ||||
| board_build.partitions = ${esp32.default_partitions} | ||||
|  | ||||
| [env:esp32dev_audioreactive] | ||||
| board = esp32dev | ||||
| platform = ${esp32.platform} | ||||
| platform_packages = ${esp32.platform_packages} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32_audioreactive #-D WLED_DISABLE_BROWNOUT_DET | ||||
|   ${esp32.AR_build_flags} | ||||
| lib_deps = ${esp32.lib_deps} | ||||
|   ${esp32.AR_lib_deps} | ||||
| monitor_filters = esp32_exception_decoder | ||||
| board_build.partitions = ${esp32.default_partitions} | ||||
| ; board_build.f_flash = 80000000L | ||||
| ; board_build.flash_mode = dio | ||||
|  | ||||
| [env:esp32dev_qio80] | ||||
| board = esp32dev | ||||
| platform = ${esp32.platform} | ||||
| platform_packages = ${esp32.platform_packages} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32_qio80 -D WLED_DISABLE_BLYNK #-D WLED_DISABLE_BROWNOUT_DET | ||||
| build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32_qio80 #-D WLED_DISABLE_BROWNOUT_DET | ||||
| lib_deps = ${esp32.lib_deps} | ||||
| monitor_filters = esp32_exception_decoder | ||||
| board_build.partitions = ${esp32.default_partitions} | ||||
| board_build.f_flash = 80000000L | ||||
| board_build.flash_mode = qio | ||||
|  | ||||
| [env:esp32dev_V4_dio80] | ||||
| ;; experimental ESP32 env using ESP-IDF V4.4.x | ||||
| ;; Warning: this build environment is not stable!! | ||||
| ;; please erase your device before installing. | ||||
| board = esp32dev | ||||
| platform = ${esp32_idf_V4.platform} | ||||
| platform_packages = ${esp32_idf_V4.platform_packages} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags}  ${esp32_idf_V4.build_flags} -D WLED_RELEASE_NAME=ESP32_V4_qio80 #-D WLED_DISABLE_BROWNOUT_DET | ||||
| lib_deps = ${esp32_idf_V4.lib_deps} | ||||
| monitor_filters = esp32_exception_decoder | ||||
| board_build.partitions = ${esp32_idf_V4.default_partitions} | ||||
| board_build.f_flash = 80000000L | ||||
| board_build.flash_mode = dio | ||||
|  | ||||
| [env:esp32_eth] | ||||
| board = esp32-poe | ||||
| platform = ${esp32.platform} | ||||
| platform_packages = ${esp32.platform_packages} | ||||
| upload_speed = 921600 | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32_Ethernet -D RLYPIN=-1 -D WLED_USE_ETHERNET -D BTNPIN=-1 -D WLED_DISABLE_BLYNK | ||||
| build_flags = ${common.build_flags_esp32} -D WLED_RELEASE_NAME=ESP32_Ethernet -D RLYPIN=-1 -D WLED_USE_ETHERNET -D BTNPIN=-1 | ||||
|   -D WLED_DISABLE_ESPNOW ;; ESP-NOW requires wifi, may crash with ethernet only | ||||
| lib_deps = ${esp32.lib_deps} | ||||
| board_build.partitions = ${esp32.default_partitions} | ||||
|  | ||||
| @@ -387,16 +466,22 @@ board_build.flash_mode = qio | ||||
| upload_speed = 460800 | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags} ${esp32s2.build_flags} #-D WLED_RELEASE_NAME=S2_saola | ||||
|   ;-DLOLIN_WIFI_FIX ;; try this in case Wifi does not work | ||||
|   -DARDUINO_USB_CDC_ON_BOOT=1 | ||||
| lib_deps = ${esp32s2.lib_deps} | ||||
|  | ||||
| [env:esp32c3] | ||||
| platform = espressif32@5.1.1 | ||||
| [env:esp32c3dev] | ||||
| extends = esp32c3 | ||||
| platform = ${esp32c3.platform} | ||||
| platform_packages = ${esp32c3.platform_packages} | ||||
| framework = arduino | ||||
| board = esp32-c3-devkitm-1 | ||||
| board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv | ||||
| build_flags = ${common.build_flags} ${esp32c3.build_flags} #-D WLED_RELEASE_NAME=ESP32-C3 | ||||
| build_flags = ${common.build_flags} ${esp32c3.build_flags} -D WLED_RELEASE_NAME=ESP32-C3 | ||||
|   -D WLED_WATCHDOG_TIMEOUT=0 | ||||
|   ; -DARDUINO_USB_CDC_ON_BOOT=1 ;; for virtual USB | ||||
|   -DLOLIN_WIFI_FIX ; seems to work much better with this | ||||
|   -DARDUINO_USB_CDC_ON_BOOT=1 ;; for virtual CDC USB | ||||
|   ;-DARDUINO_USB_CDC_ON_BOOT=0   ;; for serial-to-USB chip | ||||
| upload_speed = 460800 | ||||
| build_unflags = ${common.build_unflags} | ||||
| lib_deps = ${esp32c3.lib_deps} | ||||
| @@ -404,14 +489,14 @@ lib_deps = ${esp32c3.lib_deps} | ||||
| [env:esp32s3dev_8MB] | ||||
| ;; ESP32-S3-DevKitC-1 development board, with 8MB FLASH, no PSRAM (flash_mode: qio) | ||||
| board = esp32-s3-devkitc-1 | ||||
| platform = espressif32@5.1.1 | ||||
| platform_packages = | ||||
| platform = ${esp32s3.platform} | ||||
| platform_packages = ${esp32s3.platform_packages} | ||||
| upload_speed = 921600 ; or  460800 | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags =  ${common.build_flags} ${esp32s3.build_flags}  | ||||
| build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=ESP32-S3_8MB | ||||
|   -D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0 | ||||
|   -D ARDUINO_USB_CDC_ON_BOOT=0 -D ARDUINO_USB_MSC_ON_BOOT=0 -D ARDUINO_DFU_ON_BOOT=0 -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip | ||||
|   ;-D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MSC_ON_BOOT=0 -D ARDUINO_DFU_ON_BOOT=0 ; -D ARDUINO_USB_MODE=0 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB") | ||||
|   -D ARDUINO_USB_CDC_ON_BOOT=0  ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip | ||||
|   ;-D ARDUINO_USB_CDC_ON_BOOT=1 ;; -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB") | ||||
|   ;-D WLED_DEBUG | ||||
| lib_deps = ${esp32s3.lib_deps} | ||||
| board_build.partitions = tools/WLED_ESP32_8MB.csv | ||||
| @@ -420,18 +505,18 @@ board_build.flash_mode = qio | ||||
| ; board_build.flash_mode = dio   ;; try this if you have problems at startup | ||||
| monitor_filters = esp32_exception_decoder | ||||
|  | ||||
| [env:esp32s3dev_8MB_PSRAM] | ||||
| ;; ESP32-TinyS3 development board, with 8MB FLASH and 8MB PSRAM (memory_type: qio_opi, qio_qspi, or opi_opi) | ||||
| ;board = um_tinys3 ;    -> needs workaround from https://github.com/Aircoookie/WLED/pull/2905#issuecomment-1328049860 | ||||
| ;board = esp32s3box   ; -> error: 'esp32_adc2gpio' was not declared in this scope | ||||
| board = esp32-s3-devkitc-1 ; -> compiles, but does not support PSRAM | ||||
| platform = espressif32 @ ~5.2.0 | ||||
| platform_packages =  | ||||
| [env:esp32s3dev_8MB_PSRAM_opi] | ||||
| ;; ESP32-S3 development board, with 8MB FLASH and >= 8MB PSRAM (memory_type: qio_opi) | ||||
| board = esp32-s3-devkitc-1 ;; generic dev board; the next line adds PSRAM support | ||||
| board_build.arduino.memory_type = qio_opi     ;; use with PSRAM: 8MB or 16MB | ||||
| platform = ${esp32s3.platform} | ||||
| platform_packages = ${esp32s3.platform_packages} | ||||
| upload_speed = 921600 | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags =  ${common.build_flags} ${esp32s3.build_flags}  | ||||
| build_flags = ${common.build_flags} ${esp32s3.build_flags} | ||||
|   -D CONFIG_LITTLEFS_FOR_IDF_3_2 -D WLED_WATCHDOG_TIMEOUT=0 | ||||
|   -D ARDUINO_USB_MODE=1 -D ARDUINO_USB_MSC_ON_BOOT=0 ; -D ARDUINO_USB_CDC_ON_BOOT=0 | ||||
|   ;-D ARDUINO_USB_CDC_ON_BOOT=0  ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip | ||||
|   -D ARDUINO_USB_CDC_ON_BOOT=1 -D ARDUINO_USB_MODE=1      ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB") | ||||
|   ; -D WLED_RELEASE_NAME=ESP32-S3_PSRAM | ||||
|   -D WLED_USE_PSRAM -DBOARD_HAS_PSRAM ; tells WLED that PSRAM shall be used | ||||
| lib_deps = ${esp32s3.lib_deps} | ||||
| @@ -440,6 +525,18 @@ board_build.f_flash = 80000000L | ||||
| board_build.flash_mode = qio | ||||
| monitor_filters = esp32_exception_decoder | ||||
|  | ||||
| [env:esp32s3dev_16MB_PSRAM_opi] | ||||
| extends = env:esp32s3dev_8MB_PSRAM_opi | ||||
| board_build.partitions = tools/WLED_ESP32_16MB.csv | ||||
| board_upload.flash_size = 16MB | ||||
|  | ||||
| [env:esp32s3dev_8MB_PSRAM_qspi] | ||||
| ;; ESP32-TinyS3 development board, with 8MB FLASH and PSRAM (memory_type: qio_qspi) | ||||
| extends = env:esp32s3dev_8MB_PSRAM_opi | ||||
| ;board = um_tinys3 ;    -> needs workaround from https://github.com/Aircoookie/WLED/pull/2905#issuecomment-1328049860 | ||||
| board = esp32-s3-devkitc-1 ;; generic dev board; the next line adds PSRAM support | ||||
| board_build.arduino.memory_type = qio_qspi ;; use with PSRAM: 2MB or  4MB | ||||
|  | ||||
| [env:esp8285_4CH_MagicHome] | ||||
| board = esp8285 | ||||
| platform = ${common.platform_wled_default} | ||||
| @@ -503,14 +600,19 @@ build_flags = ${common.build_flags_esp8266} -D LEDPIN=12 -D IRPIN=-1 -D RLYPIN=2 | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
| [env:lolin_s2_mini] | ||||
| platform = espressif32@5.1.1 | ||||
| platform = ${esp32s2.platform} | ||||
| platform_packages = ${esp32s2.platform_packages} | ||||
| board = lolin_s2_mini | ||||
| board_build.partitions = tools/WLED_ESP32_4MB_1MB_FS.csv | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags} ${esp32s2.build_flags} #-D WLED_RELEASE_NAME=LolinS2 | ||||
| build_unflags = ${common.build_unflags} #-DARDUINO_USB_CDC_ON_BOOT=1 | ||||
| build_flags = ${common.build_flags} ${esp32s2.build_flags} -D WLED_RELEASE_NAME=ESP32-S2 | ||||
|   -DBOARD_HAS_PSRAM | ||||
|   -D ARDUINO_USB_CDC_ON_BOOT | ||||
|   -DARDUINO_USB_CDC_ON_BOOT=1 # try disabling and enabling unflag above in case of board-specific issues, will disable Serial | ||||
|   -DARDUINO_USB_MSC_ON_BOOT=0 | ||||
|   -DARDUINO_USB_DFU_ON_BOOT=0 | ||||
|   -DLOLIN_WIFI_FIX ; seems to work much better with this | ||||
|   -D WLED_USE_PSRAM | ||||
|   ; -D WLED_USE_UNREAL_MATH ;; may cause wrong sunset/sunrise times, but saves 6792 bytes FLASH | ||||
|   -D WLED_WATCHDOG_TIMEOUT=0 | ||||
|   -D CONFIG_ASYNC_TCP_USE_WDT=0 | ||||
|   -D LEDPIN=16 | ||||
| @@ -529,9 +631,30 @@ lib_deps = ${esp32s2.lib_deps} | ||||
| # custom board configurations | ||||
| # ------------------------------------------------------------------------------ | ||||
|  | ||||
| [env:esp32c3dev_2MB] | ||||
| ;; for ESP32-C3 boards with 2MB flash (instead of 4MB). | ||||
| ;; this board need a specific partition file. OTA not possible. | ||||
| extends = esp32c3 | ||||
| platform = ${esp32c3.platform} | ||||
| platform_packages = ${esp32c3.platform_packages} | ||||
| board = esp32-c3-devkitm-1 | ||||
| build_flags = ${common.build_flags} ${esp32c3.build_flags} #-D WLED_RELEASE_NAME=ESP32-C3 | ||||
|   -D WLED_WATCHDOG_TIMEOUT=0 | ||||
|   -D WLED_DISABLE_OTA | ||||
|   ; -DARDUINO_USB_CDC_ON_BOOT=1 ;; for virtual CDC USB | ||||
|   -DARDUINO_USB_CDC_ON_BOOT=0   ;; for serial-to-USB chip | ||||
| build_unflags = ${common.build_unflags} | ||||
| upload_speed = 115200 | ||||
| lib_deps = ${esp32c3.lib_deps} | ||||
| board_build.partitions = tools/WLED_ESP32_2MB_noOTA.csv | ||||
| board_build.flash_mode = dio | ||||
| board_upload.flash_size = 2MB | ||||
| board_upload.maximum_size = 2097152 | ||||
|  | ||||
| [env:wemos_shield_esp32] | ||||
| board = esp32dev | ||||
| platform = espressif32@3.2 | ||||
| platform = ${esp32.platform} | ||||
| platform_packages = ${esp32.platform_packages} | ||||
| upload_speed = 460800 | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp32} | ||||
| @@ -539,7 +662,7 @@ build_flags = ${common.build_flags_esp32} | ||||
|   -D RLYPIN=19 | ||||
|   -D BTNPIN=17 | ||||
|   -D IRPIN=18 | ||||
|   -D UWLED_USE_MY_CONFIG | ||||
|   -U WLED_USE_MY_CONFIG | ||||
|   -D USERMOD_DALLASTEMPERATURE | ||||
|   -D USERMOD_FOUR_LINE_DISPLAY | ||||
|   -D TEMPERATURE_PIN=23 | ||||
| @@ -556,7 +679,8 @@ board = esp32dev | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp32} -D LEDPIN=27 -D BTNPIN=39 | ||||
| lib_deps = ${esp32.lib_deps} | ||||
| platform = espressif32@3.2 | ||||
| platform = ${esp32.platform} | ||||
| platform_packages = ${esp32.platform_packages} | ||||
| board_build.partitions = ${esp32.default_partitions} | ||||
|  | ||||
| [env:sp501e] | ||||
| @@ -573,20 +697,58 @@ board_build.ldscript = ${common.ldscript_2m512k} | ||||
| build_flags = ${common.build_flags_esp8266} -D LEDPIN=3 -D BTNPIN=2 -D IRPIN=5 -D WLED_MAX_BUTTONS=3 | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
| [env:athom7w] | ||||
| board = esp_wroom_02 | ||||
| [env:Athom_RGBCW]        ;7w and 5w(GU10) bulbs | ||||
| board = esp8285 | ||||
| platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| board_build.ldscript = ${common.ldscript_2m512k} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_MAX_CCT_BLEND=0 -D BTNPIN=-1 -D IRPIN=-1 -D WLED_DISABLE_INFRARED | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=-1 -D RLYPIN=-1 -D DATA_PINS=4,12,14,13,5 | ||||
|                                             -D DEFAULT_LED_TYPE=TYPE_ANALOG_5CH -D WLED_DISABLE_INFRARED -D WLED_MAX_CCT_BLEND=0 | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
| [env:athom15w] | ||||
| board = esp_wroom_02 | ||||
|  | ||||
| [env:Athom_15w_RGBCW]        ;15w bulb | ||||
| board = esp8285 | ||||
| platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| board_build.ldscript = ${common.ldscript_2m512k} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_USE_IC_CCT -D BTNPIN=-1 -D IRPIN=-1 -D WLED_DISABLE_INFRARED | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=-1 -D RLYPIN=-1 -D DATA_PINS=4,12,14,5,13 | ||||
|                                             -D DEFAULT_LED_TYPE=TYPE_ANALOG_5CH -D WLED_DISABLE_INFRARED -D WLED_MAX_CCT_BLEND=0 -D WLED_USE_IC_CCT | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
|  | ||||
| [env:Athom_3Pin_Controller]        ;small controller with only data | ||||
| board = esp8285 | ||||
| platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| board_build.ldscript = ${common.ldscript_2m512k} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=0 -D RLYPIN=-1 -D LEDPIN=1 -D WLED_DISABLE_INFRARED | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
|  | ||||
| [env:Athom_4Pin_Controller]       ; With clock and data interface | ||||
| board = esp8285 | ||||
| platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| board_build.ldscript = ${common.ldscript_2m512k} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=0 -D RLYPIN=12 -D LEDPIN=1 -D WLED_DISABLE_INFRARED | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
|  | ||||
| [env:Athom_5Pin_Controller]      ;Analog light strip controller | ||||
| board = esp8285 | ||||
| platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| board_build.ldscript = ${common.ldscript_2m512k} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} -D WLED_RELEASE_NAME=ESP8266 -D BTNPIN=0 -D RLYPIN=-1 DATA_PINS=4,12,14,13 -D WLED_DISABLE_INFRARED | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
|  | ||||
| [env:MY9291] | ||||
| board = esp01_1m | ||||
| platform = ${common.platform_wled_default} | ||||
| @@ -598,10 +760,10 @@ lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
| # ------------------------------------------------------------------------------ | ||||
| # codm pixel controller board configurations | ||||
| # codm-controller-0.6 can also be used for the TYWE3S controller | ||||
| # codm-controller-0_6 can also be used for the TYWE3S controller | ||||
| # ------------------------------------------------------------------------------ | ||||
|  | ||||
| [env:codm-controller-0.6] | ||||
| [env:codm-controller-0_6] | ||||
| board = esp_wroom_02 | ||||
| platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| @@ -610,7 +772,7 @@ build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp8266} | ||||
| lib_deps = ${esp8266.lib_deps} | ||||
|  | ||||
| [env:codm-controller-0.6-rev2] | ||||
| [env:codm-controller-0_6-rev2] | ||||
| board = esp_wroom_02 | ||||
| platform = ${common.platform_wled_default} | ||||
| platform_packages = ${common.platform_packages} | ||||
| @@ -624,7 +786,8 @@ lib_deps = ${esp8266.lib_deps} | ||||
| # ------------------------------------------------------------------------------ | ||||
| [env:elekstube_ips] | ||||
| board = esp32dev | ||||
| platform = espressif32@3.2 | ||||
| platform = ${esp32.platform} | ||||
| platform_packages = ${esp32.platform_packages} | ||||
| upload_speed = 921600 | ||||
| build_flags = ${common.build_flags_esp32} -D WLED_DISABLE_BROWNOUT_DET -D WLED_DISABLE_INFRARED | ||||
|   -D USERMOD_RTC | ||||
| @@ -632,7 +795,6 @@ build_flags = ${common.build_flags_esp32} -D WLED_DISABLE_BROWNOUT_DET -D WLED_D | ||||
|   -D LEDPIN=12 | ||||
|   -D RLYPIN=27 | ||||
|   -D BTNPIN=34 | ||||
|   -D WLED_DISABLE_BLYNK | ||||
|   -D DEFAULT_LED_COUNT=6 | ||||
|   # Display config | ||||
|   -D ST7789_DRIVER | ||||
|   | ||||
| @@ -26,7 +26,6 @@ build_flags = ${common.build_flags_esp8266} | ||||
| ; disable specific features | ||||
| ;  -D WLED_DISABLE_OTA | ||||
| ;  -D WLED_DISABLE_ALEXA | ||||
| ;  -D WLED_DISABLE_BLYNK | ||||
| ;  -D WLED_DISABLE_HUESYNC | ||||
| ;  -D WLED_DISABLE_INFRARED | ||||
| ;  -D WLED_DISABLE_WEBSOCKETS | ||||
|   | ||||
| @@ -3,7 +3,7 @@ | ||||
|   <a href="https://github.com/Aircoookie/WLED/releases"><img src="https://img.shields.io/github/release/Aircoookie/WLED.svg?style=flat-square"></a> | ||||
|   <a href="https://raw.githubusercontent.com/Aircoookie/WLED/master/LICENSE"><img src="https://img.shields.io/github/license/Aircoookie/wled?color=blue&style=flat-square"></a> | ||||
|   <a href="https://wled.discourse.group"><img src="https://img.shields.io/discourse/topics?colorB=blue&label=forum&server=https%3A%2F%2Fwled.discourse.group%2F&style=flat-square"></a> | ||||
|   <a href="https://discord.gg/KuqP7NE"><img src="https://img.shields.io/discord/473448917040758787.svg?colorB=blue&label=discord&style=flat-square"></a> | ||||
|   <a href="https://discord.gg/QAh7wJHrRM"><img src="https://img.shields.io/discord/473448917040758787.svg?colorB=blue&label=discord&style=flat-square"></a> | ||||
|   <a href="https://kno.wled.ge"><img src="https://img.shields.io/badge/quick_start-wiki-blue.svg?style=flat-square"></a> | ||||
|   <a href="https://github.com/Aircoookie/WLED-App"><img src="https://img.shields.io/badge/app-wled-blue.svg?style=flat-square"></a> | ||||
|   <a href="https://gitpod.io/#https://github.com/Aircoookie/WLED"><img src="https://img.shields.io/badge/Gitpod-ready--to--code-blue?style=flat-square&logo=gitpod"></a> | ||||
| @@ -26,7 +26,7 @@ A fast and feature-rich implementation of an ESP8266/ESP32 webserver to control | ||||
| - Up to 250 user presets to save and load colors/effects easily, supports cycling through them.   | ||||
| - Presets can be used to automatically execute API calls   | ||||
| - Nightlight function (gradually dims down)   | ||||
| - Full OTA software updatability (HTTP + ArduinoOTA), password protectable   | ||||
| - Full OTA software updateability (HTTP + ArduinoOTA), password protectable   | ||||
| - Configurable analog clock (Cronixie, 7-segment and EleksTube IPS clock support via usermods)  | ||||
| - Configurable Auto Brightness limit for safe operation   | ||||
| - Filesystem-based config for easier backup of presets and settings   | ||||
| @@ -34,8 +34,7 @@ A fast and feature-rich implementation of an ESP8266/ESP32 webserver to control | ||||
| ## 💡 Supported light control interfaces | ||||
| - WLED app for [Android](https://play.google.com/store/apps/details?id=com.aircoookie.WLED) and [iOS](https://apps.apple.com/us/app/wled/id1475695033) | ||||
| - JSON and HTTP request APIs   | ||||
| - MQTT   | ||||
| - Blynk IoT   | ||||
| - MQTT    | ||||
| - E1.31, Art-Net, DDP and TPM2.net | ||||
| - [diyHue](https://github.com/diyhue/diyHue) (Wled is supported by diyHue, including Hue Sync Entertainment under udp. Thanks to [Gregory Mallios](https://github.com/gmallios)) | ||||
| - [Hyperion](https://github.com/hyperion-project/hyperion.ng) | ||||
| @@ -67,7 +66,7 @@ Credits [here](https://kno.wled.ge/about/contributors/)! | ||||
|  | ||||
| Join the Discord server to discuss everything about WLED! | ||||
|  | ||||
| <a href="https://discord.gg/KuqP7NE"><img src="https://discordapp.com/api/guilds/473448917040758787/widget.png?style=banner2" width="25%"></a> | ||||
| <a href="https://discord.gg/QAh7wJHrRM"><img src="https://discordapp.com/api/guilds/473448917040758787/widget.png?style=banner2" width="25%"></a> | ||||
|  | ||||
| Check out the WLED [Discourse forum](https://wled.discourse.group)!   | ||||
|  | ||||
|   | ||||
| @@ -4,63 +4,55 @@ | ||||
| # | ||||
| #    pip-compile | ||||
| # | ||||
| aiofiles==0.8.0 | ||||
| aiofiles==22.1.0 | ||||
|     # via platformio | ||||
| ajsonrpc==1.2.0 | ||||
|     # via platformio | ||||
| anyio==3.6.1 | ||||
| anyio==3.6.2 | ||||
|     # via starlette | ||||
| async-timeout==4.0.2 | ||||
|     # via zeroconf | ||||
| bottle==0.12.23 | ||||
| bottle==0.12.25 | ||||
|     # via platformio | ||||
| certifi==2022.12.7 | ||||
| certifi==2023.7.22 | ||||
|     # via requests | ||||
| charset-normalizer==2.1.1 | ||||
| charset-normalizer==3.1.0 | ||||
|     # via requests | ||||
| click==8.1.3 | ||||
|     # via | ||||
|     #   platformio | ||||
|     #   uvicorn | ||||
| colorama==0.4.5 | ||||
| colorama==0.4.6 | ||||
|     # via platformio | ||||
| h11==0.13.0 | ||||
| h11==0.14.0 | ||||
|     # via | ||||
|     #   uvicorn | ||||
|     #   wsproto | ||||
| idna==3.3 | ||||
| idna==3.4 | ||||
|     # via | ||||
|     #   anyio | ||||
|     #   requests | ||||
| ifaddr==0.2.0 | ||||
|     # via zeroconf | ||||
| marshmallow==3.17.0 | ||||
| marshmallow==3.19.0 | ||||
|     # via platformio | ||||
| packaging==21.3 | ||||
| packaging==23.1 | ||||
|     # via marshmallow | ||||
| platformio==6.1.4 | ||||
| platformio==6.1.6 | ||||
|     # via -r requirements.in | ||||
| pyelftools==0.29 | ||||
|     # via platformio | ||||
| pyparsing==3.0.9 | ||||
|     # via packaging | ||||
| pyserial==3.5 | ||||
|     # via platformio | ||||
| requests==2.28.1 | ||||
| requests==2.31.0 | ||||
|     # via platformio | ||||
| semantic-version==2.10.0 | ||||
|     # via platformio | ||||
| sniffio==1.2.0 | ||||
| sniffio==1.3.0 | ||||
|     # via anyio | ||||
| starlette==0.20.4 | ||||
| starlette==0.23.1 | ||||
|     # via platformio | ||||
| tabulate==0.8.10 | ||||
| tabulate==0.9.0 | ||||
|     # via platformio | ||||
| urllib3==1.26.11 | ||||
| urllib3==1.26.15 | ||||
|     # via requests | ||||
| uvicorn==0.18.2 | ||||
| uvicorn==0.20.0 | ||||
|     # via platformio | ||||
| wsproto==1.1.0 | ||||
|     # via platformio | ||||
| zeroconf==0.39.0 | ||||
| wsproto==1.2.0 | ||||
|     # via platformio | ||||
|   | ||||
							
								
								
									
										8
									
								
								tools/WLED_ESP32_16MB_9MB_FS.csv
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,8 @@ | ||||
| # Name,   Type, SubType, Offset,  Size, Flags | ||||
| nvs,      data, nvs,     0x9000,  0x5000, | ||||
| otadata,  data, ota,     0xe000,  0x2000, | ||||
| app0,     app,  ota_0,   0x10000, 0x300000, | ||||
| app1,     app,  ota_1,   0x310000,0x300000, | ||||
| spiffs,   data, spiffs,  0x610000,0x9E0000, | ||||
| coredump, data, coredump,,64K | ||||
| # to create/use ffat, see https://github.com/marcmerlin/esp32_fatfsimage | ||||
| 
 | 
							
								
								
									
										5
									
								
								tools/WLED_ESP32_2MB_noOTA.csv
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,5 @@ | ||||
| # Name,   Type, SubType, Offset,  Size, Flags | ||||
| nvs,      data, nvs,     0x9000,    20K, | ||||
| otadata,  data, ota,     0xe000,    8K, | ||||
| app0,     app,  ota_0,   0x10000,   1536K, | ||||
| spiffs,   data, spiffs,  0x190000,  384K, | ||||
| 
 | 
| @@ -3,4 +3,5 @@ nvs,      data, nvs,     0x9000,  0x5000, | ||||
| otadata,  data, ota,     0xe000,  0x2000, | ||||
| app0,     app,  ota_0,   0x10000, 0x200000, | ||||
| app1,     app,  ota_1,   0x210000,0x200000, | ||||
| spiffs,   data, spiffs,  0x410000,0x3F0000, | ||||
| spiffs,   data, spiffs,  0x410000,0x3E0000, | ||||
| coredump, data, coredump,,64K | ||||
|   | ||||
| 
 | 
| @@ -220,6 +220,9 @@ function writeChunks(srcDir, specs, resultFile) { | ||||
|  | ||||
| writeHtmlGzipped("wled00/data/index.htm", "wled00/html_ui.h", 'index'); | ||||
| writeHtmlGzipped("wled00/data/simple.htm", "wled00/html_simple.h", 'simple'); | ||||
| writeHtmlGzipped("wled00/data/pixart/pixart.htm", "wled00/html_pixart.h", 'pixart'); | ||||
| writeHtmlGzipped("wled00/data/cpal/cpal.htm", "wled00/html_cpal.h", 'cpal'); | ||||
| writeHtmlGzipped("wled00/data/pxmagic/pxmagic.htm", "wled00/html_pxmagic.h", 'pxmagic'); | ||||
| /* | ||||
| writeChunks( | ||||
|   "wled00/data", | ||||
| @@ -387,12 +390,6 @@ const char PAGE_dmxmap[] PROGMEM = R"=====()====="; | ||||
|       method: "gzip", | ||||
|       filter: "html-minify", | ||||
|     }, | ||||
|     { | ||||
|       file: "liveviewws.htm", | ||||
|       name: "PAGE_liveviewws", | ||||
|       method: "gzip", | ||||
|       filter: "html-minify", | ||||
|     }, | ||||
|     { | ||||
|       file: "liveviewws2D.htm", | ||||
|       name: "PAGE_liveviewws2D", | ||||
|   | ||||
| @@ -56,7 +56,7 @@ private: | ||||
|  | ||||
|     // runtime | ||||
|     bool     initDone         = false; | ||||
|     uint32_t lastOverlayDraw  = 0;  | ||||
|     uint32_t lastOverlayDraw  = 0; | ||||
|  | ||||
|     void validateAndUpdate() { | ||||
|         mainSegment.validateAndUpdate(); | ||||
| @@ -110,9 +110,9 @@ private: | ||||
|  | ||||
|     static inline uint32_t qadd32(uint32_t c1, uint32_t c2) { | ||||
|         return RGBW32( | ||||
|             qadd8(R(c1), R(c2)),  | ||||
|             qadd8(G(c1), G(c2)),  | ||||
|             qadd8(B(c1), B(c2)),  | ||||
|             qadd8(R(c1), R(c2)), | ||||
|             qadd8(G(c1), G(c2)), | ||||
|             qadd8(B(c1), B(c2)), | ||||
|             qadd8(W(c1), W(c2)) | ||||
|         ); | ||||
|     } | ||||
| @@ -166,7 +166,7 @@ public: | ||||
|         double secondP = second(localTime) / 60.0; | ||||
|         double minuteP = minute(localTime) / 60.0; | ||||
|         double hourP = (hour(localTime) % 12) / 12.0 + minuteP / 12.0; | ||||
|          | ||||
|  | ||||
|         if (hourMarksEnabled)         { | ||||
|             for (int Led = 0; Led <= 55; Led = Led + 5) | ||||
|             { | ||||
| @@ -174,7 +174,7 @@ public: | ||||
|                 setPixelColor(hourmarkled, hourMarkColor); | ||||
|             } | ||||
|         } | ||||
|          | ||||
|  | ||||
|         if (secondsEnabled) { | ||||
|             int16_t secondLed = adjustToSegment(secondP, secondsSegment); | ||||
|  | ||||
| @@ -203,45 +203,45 @@ public: | ||||
|     void addToConfig(JsonObject& root) override { | ||||
|         validateAndUpdate(); | ||||
|  | ||||
|         JsonObject top = root.createNestedObject("Analog Clock"); | ||||
|         top["Overlay Enabled"]               = enabled; | ||||
|         top["First LED (Main Ring)"]         = mainSegment.firstLed; | ||||
|         top["Last LED (Main Ring)"]          = mainSegment.lastLed; | ||||
|         top["Center/12h LED (Main Ring)"]    = mainSegment.centerLed; | ||||
|         top["Hour Marks Enabled"]            = hourMarksEnabled; | ||||
|         top["Hour Mark Color (RRGGBB)"]      = colorToHexString(hourMarkColor); | ||||
|         top["Hour Color (RRGGBB)"]           = colorToHexString(hourColor); | ||||
|         top["Minute Color (RRGGBB)"]         = colorToHexString(minuteColor); | ||||
|         top["Show Seconds"]                  = secondsEnabled; | ||||
|         top["First LED (Seconds Ring)"]      = secondsSegment.firstLed; | ||||
|         top["Last LED (Seconds Ring)"]       = secondsSegment.lastLed; | ||||
|         top["Center/12h LED (Seconds Ring)"] = secondsSegment.centerLed; | ||||
|         top["Second Color (RRGGBB)"]         = colorToHexString(secondColor); | ||||
|         top["Seconds Effect (0-1)"]          = secondsEffect; | ||||
|         top["Blend Colors"]                  = blendColors; | ||||
|         JsonObject top = root.createNestedObject(F("Analog Clock")); | ||||
|         top[F("Overlay Enabled")]               = enabled; | ||||
|         top[F("First LED (Main Ring)")]         = mainSegment.firstLed; | ||||
|         top[F("Last LED (Main Ring)")]          = mainSegment.lastLed; | ||||
|         top[F("Center/12h LED (Main Ring)")]    = mainSegment.centerLed; | ||||
|         top[F("Hour Marks Enabled")]            = hourMarksEnabled; | ||||
|         top[F("Hour Mark Color (RRGGBB)")]      = colorToHexString(hourMarkColor); | ||||
|         top[F("Hour Color (RRGGBB)")]           = colorToHexString(hourColor); | ||||
|         top[F("Minute Color (RRGGBB)")]         = colorToHexString(minuteColor); | ||||
|         top[F("Show Seconds")]                  = secondsEnabled; | ||||
|         top[F("First LED (Seconds Ring)")]      = secondsSegment.firstLed; | ||||
|         top[F("Last LED (Seconds Ring)")]       = secondsSegment.lastLed; | ||||
|         top[F("Center/12h LED (Seconds Ring)")] = secondsSegment.centerLed; | ||||
|         top[F("Second Color (RRGGBB)")]         = colorToHexString(secondColor); | ||||
|         top[F("Seconds Effect (0-1)")]          = secondsEffect; | ||||
|         top[F("Blend Colors")]                  = blendColors; | ||||
|     } | ||||
|  | ||||
|     bool readFromConfig(JsonObject& root) override { | ||||
|         JsonObject top = root["Analog Clock"]; | ||||
|         JsonObject top = root[F("Analog Clock")]; | ||||
|  | ||||
|         bool configComplete = !top.isNull(); | ||||
|  | ||||
|         String color; | ||||
|         configComplete &= getJsonValue(top["Overlay Enabled"], enabled, false); | ||||
|         configComplete &= getJsonValue(top["First LED (Main Ring)"], mainSegment.firstLed, 0); | ||||
|         configComplete &= getJsonValue(top["Last LED (Main Ring)"], mainSegment.lastLed, 59); | ||||
|         configComplete &= getJsonValue(top["Center/12h LED (Main Ring)"], mainSegment.centerLed, 0); | ||||
|         configComplete &= getJsonValue(top["Hour marks Enabled"], hourMarksEnabled, false); | ||||
|         configComplete &= getJsonValue(top["Hour mark Color (RRGGBB)"], color, "FF0000") && hexStringToColor(color, hourMarkColor, 0x0000FF); | ||||
|         configComplete &= getJsonValue(top["Hour Color (RRGGBB)"], color, "0000FF") && hexStringToColor(color, hourColor, 0x0000FF); | ||||
|         configComplete &= getJsonValue(top["Minute Color (RRGGBB)"], color, "00FF00") && hexStringToColor(color, minuteColor, 0x00FF00); | ||||
|         configComplete &= getJsonValue(top["Show Seconds"], secondsEnabled, true); | ||||
|         configComplete &= getJsonValue(top["First LED (Seconds Ring)"], secondsSegment.firstLed, 0); | ||||
|         configComplete &= getJsonValue(top["Last LED (Seconds Ring)"], secondsSegment.lastLed, 59); | ||||
|         configComplete &= getJsonValue(top["Center/12h LED (Seconds Ring)"], secondsSegment.centerLed, 0); | ||||
|         configComplete &= getJsonValue(top["Second Color (RRGGBB)"], color, "FF0000") && hexStringToColor(color, secondColor, 0xFF0000); | ||||
|         configComplete &= getJsonValue(top["Seconds Effect (0-1)"], secondsEffect, 0); | ||||
|         configComplete &= getJsonValue(top["Blend Colors"], blendColors, true); | ||||
|         configComplete &= getJsonValue(top[F("Overlay Enabled")], enabled, false); | ||||
|         configComplete &= getJsonValue(top[F("First LED (Main Ring)")], mainSegment.firstLed, 0); | ||||
|         configComplete &= getJsonValue(top[F("Last LED (Main Ring)")], mainSegment.lastLed, 59); | ||||
|         configComplete &= getJsonValue(top[F("Center/12h LED (Main Ring)")], mainSegment.centerLed, 0); | ||||
|         configComplete &= getJsonValue(top[F("Hour Marks Enabled")], hourMarksEnabled, false); | ||||
|         configComplete &= getJsonValue(top[F("Hour Mark Color (RRGGBB)")], color, F("161616")) && hexStringToColor(color, hourMarkColor, 0x161616); | ||||
|         configComplete &= getJsonValue(top[F("Hour Color (RRGGBB)")], color, F("0000FF")) && hexStringToColor(color, hourColor, 0x0000FF); | ||||
|         configComplete &= getJsonValue(top[F("Minute Color (RRGGBB)")], color, F("00FF00")) && hexStringToColor(color, minuteColor, 0x00FF00); | ||||
|         configComplete &= getJsonValue(top[F("Show Seconds")], secondsEnabled, true); | ||||
|         configComplete &= getJsonValue(top[F("First LED (Seconds Ring)")], secondsSegment.firstLed, 0); | ||||
|         configComplete &= getJsonValue(top[F("Last LED (Seconds Ring)")], secondsSegment.lastLed, 59); | ||||
|         configComplete &= getJsonValue(top[F("Center/12h LED (Seconds Ring)")], secondsSegment.centerLed, 0); | ||||
|         configComplete &= getJsonValue(top[F("Second Color (RRGGBB)")], color, F("FF0000")) && hexStringToColor(color, secondColor, 0xFF0000); | ||||
|         configComplete &= getJsonValue(top[F("Seconds Effect (0-1)")], secondsEffect, 0); | ||||
|         configComplete &= getJsonValue(top[F("Blend Colors")], blendColors, true); | ||||
|  | ||||
|         if (initDone) { | ||||
|             validateAndUpdate(); | ||||
| @@ -253,4 +253,4 @@ public: | ||||
|     uint16_t getId() override { | ||||
|         return USERMOD_ID_ANALOG_CLOCK; | ||||
|     } | ||||
| }; | ||||
| }; | ||||
|   | ||||
| @@ -25,6 +25,7 @@ class Animated_Staircase : public Usermod { | ||||
|     bool useUSSensorBottom         = false; // using PIR or UltraSound sensor? | ||||
|     unsigned int topMaxDist        = 50;    // default maximum measured distance in cm, top | ||||
|     unsigned int bottomMaxDist     = 50;    // default maximum measured distance in cm, bottom | ||||
|     bool togglePower               = false; // toggle power on/off with staircase on/off | ||||
|  | ||||
|     /* runtime variables */ | ||||
|     bool initDone = false; | ||||
| @@ -90,14 +91,17 @@ class Animated_Staircase : public Usermod { | ||||
|     static const char _bottomEcho_pin[]; | ||||
|     static const char _topEchoCm[]; | ||||
|     static const char _bottomEchoCm[]; | ||||
|      | ||||
|     static const char _togglePower[]; | ||||
|  | ||||
|     void publishMqtt(bool bottom, const char* state) { | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|       //Check if MQTT Connected, otherwise it will crash the 8266 | ||||
|       if (WLED_MQTT_CONNECTED){ | ||||
|         char subuf[64]; | ||||
|         sprintf_P(subuf, PSTR("%s/motion/%d"), mqttDeviceTopic, (int)bottom); | ||||
|         mqtt->publish(subuf, 0, false, state); | ||||
|       } | ||||
| #endif | ||||
|     } | ||||
|  | ||||
|     void updateSegments() { | ||||
| @@ -129,7 +133,7 @@ class Animated_Staircase : public Usermod { | ||||
|     *            received within this time, an object is detected | ||||
|     *            and the function will return true. | ||||
|     * | ||||
|     * The speed of sound is 343 meters per second at 20 degress Celcius. | ||||
|     * The speed of sound is 343 meters per second at 20 degrees Celsius. | ||||
|     * Since the sound has to travel back and forth, the detection | ||||
|     * distance for the sensor in cm is (0.0343 * maxTimeUs) / 2. | ||||
|     * | ||||
| @@ -194,6 +198,7 @@ class Animated_Staircase : public Usermod { | ||||
|           if (on) { | ||||
|             lastSensor = topSensorRead; | ||||
|           } else { | ||||
|             if (togglePower && onIndex == offIndex && offMode) toggleOnOff(); // toggle power on if off | ||||
|             // If the bottom sensor triggered, we need to swipe up, ON | ||||
|             swipe = bottomSensorRead; | ||||
|  | ||||
| @@ -247,11 +252,14 @@ class Animated_Staircase : public Usermod { | ||||
|             offIndex = MAX(onIndex, offIndex - 1); | ||||
|           } | ||||
|         } | ||||
|         if (oldOn != onIndex || oldOff != offIndex) updateSegments(); // reduce the number of updates to necessary ones | ||||
|         if (oldOn != onIndex || oldOff != offIndex) { | ||||
|           updateSegments(); // reduce the number of updates to necessary ones | ||||
|           if (togglePower && onIndex == offIndex && !offMode && !on) toggleOnOff();  // toggle power off for all segments off | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     // send sesnor values to JSON API | ||||
|     // send sensor values to JSON API | ||||
|     void writeSensorsToJson(JsonObject& staircase) { | ||||
|       staircase[F("top-sensor")]    = topSensorRead; | ||||
|       staircase[F("bottom-sensor")] = bottomSensorRead; | ||||
| @@ -289,10 +297,11 @@ class Animated_Staircase : public Usermod { | ||||
|         offIndex = maxSegmentId = strip.getLastActiveSegmentId() + 1; | ||||
|  | ||||
|         // shorten the strip transition time to be equal or shorter than segment delay | ||||
|         transitionDelayTemp = transitionDelay = segment_delay_ms; | ||||
|         strip.setTransition(segment_delay_ms/100); | ||||
|         transitionDelay = segment_delay_ms; | ||||
|         strip.setTransition(segment_delay_ms); | ||||
|         strip.trigger(); | ||||
|       } else { | ||||
|         if (togglePower && !on && offMode) toggleOnOff(); // toggle power on if off | ||||
|         // Restore segment options | ||||
|         for (int i = 0; i <= strip.getLastActiveSegmentId(); i++) { | ||||
|           Segment &seg = strip.getSegment(i); | ||||
| @@ -300,7 +309,7 @@ class Animated_Staircase : public Usermod { | ||||
|           seg.setOption(SEG_OPTION_ON, true); | ||||
|         } | ||||
|         strip.trigger();  // force strip update | ||||
|         stateChanged = true;  // inform external dvices/UI of change | ||||
|         stateChanged = true;  // inform external devices/UI of change | ||||
|         colorUpdated(CALL_MODE_DIRECT_CHANGE); | ||||
|         DEBUG_PRINTLN(F("Animated Staircase disabled.")); | ||||
|       } | ||||
| @@ -345,6 +354,7 @@ class Animated_Staircase : public Usermod { | ||||
|  | ||||
|     uint16_t getId() { return USERMOD_ID_ANIMATED_STAIRCASE; } | ||||
|  | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|     /** | ||||
|      * handling of MQTT message | ||||
|      * topic only contains stripped topic (part after /wled/MAC) | ||||
| @@ -382,6 +392,7 @@ class Animated_Staircase : public Usermod { | ||||
|         mqtt->subscribe(subuf, 0); | ||||
|       } | ||||
|     } | ||||
| #endif | ||||
|  | ||||
|     void addToJsonState(JsonObject& root) { | ||||
|       JsonObject staircase = root[FPSTR(_name)]; | ||||
| @@ -440,6 +451,7 @@ class Animated_Staircase : public Usermod { | ||||
|       staircase[FPSTR(_bottomEcho_pin)]            = useUSSensorBottom ? bottomEchoPin : -1; | ||||
|       staircase[FPSTR(_topEchoCm)]                 = topMaxDist; | ||||
|       staircase[FPSTR(_bottomEchoCm)]              = bottomMaxDist; | ||||
|       staircase[FPSTR(_togglePower)]               = togglePower; | ||||
|       DEBUG_PRINTLN(F("Staircase config saved.")); | ||||
|     } | ||||
|  | ||||
| @@ -480,10 +492,12 @@ class Animated_Staircase : public Usermod { | ||||
|       bottomEchoPin         = top[FPSTR(_bottomEcho_pin)] | bottomEchoPin; | ||||
|  | ||||
|       topMaxDist    = top[FPSTR(_topEchoCm)] | topMaxDist; | ||||
|       topMaxDist    = min(150,max(30,(int)topMaxDist));     // max distnace ~1.5m (a lag of 9ms may be expected) | ||||
|       topMaxDist    = min(150,max(30,(int)topMaxDist));     // max distance ~1.5m (a lag of 9ms may be expected) | ||||
|       bottomMaxDist = top[FPSTR(_bottomEchoCm)] | bottomMaxDist; | ||||
|       bottomMaxDist = min(150,max(30,(int)bottomMaxDist));  // max distance ~1.5m (a lag of 9ms may be expected) | ||||
|  | ||||
|       togglePower = top[FPSTR(_togglePower)] | togglePower;  // staircase toggles power on/off | ||||
|  | ||||
|       DEBUG_PRINT(FPSTR(_name)); | ||||
|       if (!initDone) { | ||||
|         // first run: reading from cfg.json | ||||
| @@ -507,7 +521,7 @@ class Animated_Staircase : public Usermod { | ||||
|         if (changed) setup(); | ||||
|       } | ||||
|       // use "return !top["newestParameter"].isNull();" when updating Usermod with new features | ||||
|       return true; | ||||
|       return !top[FPSTR(_togglePower)].isNull(); | ||||
|     } | ||||
|  | ||||
|     /* | ||||
| @@ -547,3 +561,4 @@ const char Animated_Staircase::_bottomPIRorTrigger_pin[]    PROGMEM = "bottomPIR | ||||
| const char Animated_Staircase::_bottomEcho_pin[]            PROGMEM = "bottomEcho_pin"; | ||||
| const char Animated_Staircase::_topEchoCm[]                 PROGMEM = "top-dist-cm"; | ||||
| const char Animated_Staircase::_bottomEchoCm[]              PROGMEM = "bottom-dist-cm"; | ||||
| const char Animated_Staircase::_togglePower[]               PROGMEM = "toggle-on-off"; | ||||
|   | ||||
| @@ -11,7 +11,7 @@ The Animated Staircase can be controlled by the WLED API. Change settings such a | ||||
| speed, on/off time and distance by sending an HTTP request, see below. | ||||
|  | ||||
| ## WLED integration | ||||
| To include this usermod in your WLED setup, you have to be able to [compile WLED from source](https://github.com/Aircoookie/WLED/wiki/Compiling-WLED). | ||||
| To include this usermod in your WLED setup, you have to be able to [compile WLED from source](https://kno.wled.ge/advanced/compiling-wled/). | ||||
|  | ||||
| Before compiling, you have to make the following modifications: | ||||
|  | ||||
| @@ -38,7 +38,7 @@ Maximum distance for ultrasonic sensor can be configured as the time needed for | ||||
| You _may_ need to use 10k pull-down resistors on the selected PIR pins, depending on the sensor. | ||||
|  | ||||
| ## WLED configuration | ||||
| 1. In the WLED UI, confgure a segment for each step. The lowest step of the stairs is the  | ||||
| 1. In the WLED UI, configure a segment for each step. The lowest step of the stairs is the  | ||||
|    lowest segment id.  | ||||
| 2. Save your segments into a preset.  | ||||
| 3. Ideally, add the preset in the config > LED setup menu to the "apply  | ||||
| @@ -91,7 +91,7 @@ To enable the usermod again, use `"enabled":true`. | ||||
| Alternatively you can use _Usermod_ Settings page where you can change other parameters as well. | ||||
|  | ||||
| ### Changing animation parameters and detection range of the ultrasonic HC-SR04 sensor | ||||
| Using _Usermod_ Settings page you can define different usermod parameters, includng sensor pins, delay between segment activation etc. | ||||
| Using _Usermod_ Settings page you can define different usermod parameters, including sensor pins, delay between segment activation etc. | ||||
|  | ||||
| When an ultrasonic sensor is enabled you can enter maximum detection distance in centimeters separately for top and bottom sensors. | ||||
|  | ||||
|   | ||||
| @@ -9,7 +9,7 @@ The luminance is displayed in both the Info section of the web UI, as well as pu | ||||
|   - This must be added under `lib_deps` in your `platformio.ini` (or `platformio_override.ini`). | ||||
| - Data is published over MQTT - make sure you've enabled the MQTT sync interface. | ||||
|  | ||||
| ## Compiliation | ||||
| ## Compilation | ||||
|  | ||||
| To enable, compile with `USERMOD_BH1750` defined  (e.g. in `platformio_override.ini`) | ||||
| ```ini | ||||
|   | ||||
| @@ -1,10 +1,13 @@ | ||||
| // force the compiler to show a warning to confirm that this file is included | ||||
| #warning **** Included USERMOD_BH1750 **** | ||||
|  | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
| #include <Wire.h> | ||||
| #include <BH1750.h> | ||||
|  | ||||
| // the max frequency to check photoresistor, 10 seconds | ||||
| @@ -22,7 +25,7 @@ | ||||
| #define USERMOD_BH1750_FIRST_MEASUREMENT_AT 10000 | ||||
| #endif | ||||
|  | ||||
| // only report if differance grater than offset value | ||||
| // only report if difference grater than offset value | ||||
| #ifndef USERMOD_BH1750_OFFSET_VALUE | ||||
| #define USERMOD_BH1750_OFFSET_VALUE 1 | ||||
| #endif | ||||
| @@ -52,15 +55,6 @@ private: | ||||
|   static const char _offset[]; | ||||
|   static const char _HomeAssistantDiscovery[]; | ||||
|  | ||||
|   // set the default pins based on the architecture, these get overridden by Usermod menu settings | ||||
|   #ifdef ARDUINO_ARCH_ESP32 // ESP32 boards | ||||
|     #define HW_PIN_SCL 22 | ||||
|     #define HW_PIN_SDA 21 | ||||
|   #else // ESP8266 boards | ||||
|     #define HW_PIN_SCL 5 | ||||
|     #define HW_PIN_SDA 4 | ||||
|   #endif | ||||
|   int8_t ioPin[2] = {HW_PIN_SCL, HW_PIN_SDA};        // I2C pins: SCL, SDA...defaults to Arch hardware pins but overridden at setup() | ||||
|   bool initDone = false; | ||||
|   bool sensorFound = false; | ||||
|  | ||||
| @@ -119,14 +113,7 @@ private: | ||||
| public: | ||||
|   void setup() | ||||
|   { | ||||
|     bool HW_Pins_Used = (ioPin[0]==HW_PIN_SCL && ioPin[1]==HW_PIN_SDA); // note whether architecture-based hardware SCL/SDA pins used | ||||
|     PinOwner po = PinOwner::UM_BH1750; // defaults to being pinowner for SCL/SDA pins | ||||
|     PinManagerPinType pins[2] = { { ioPin[0], true }, { ioPin[1], true } };  // allocate pins | ||||
|     if (HW_Pins_Used) po = PinOwner::HW_I2C; // allow multiple allocations of HW I2C bus pins | ||||
|     if (!pinManager.allocateMultiplePins(pins, 2, po)) return; | ||||
|      | ||||
|     Wire.begin(ioPin[1], ioPin[0]); | ||||
|  | ||||
|     if (i2c_scl<0 || i2c_sda<0) { enabled = false; return; } | ||||
|     sensorFound = lightMeter.begin(); | ||||
|     initDone = true; | ||||
|   } | ||||
| @@ -156,6 +143,7 @@ public: | ||||
|     { | ||||
|       lastLux = lux; | ||||
|       lastSend = millis(); | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|       if (WLED_MQTT_CONNECTED) | ||||
|       { | ||||
|         if (!mqttInitialized) | ||||
| @@ -170,6 +158,7 @@ public: | ||||
|       { | ||||
|         DEBUG_PRINTLN(F("Missing MQTT connection. Not publishing data")); | ||||
|       } | ||||
| #endif | ||||
|     } | ||||
|   } | ||||
|  | ||||
| @@ -184,7 +173,9 @@ public: | ||||
|       user = root.createNestedObject(F("u")); | ||||
|  | ||||
|     JsonArray lux_json = user.createNestedArray(F("Luminance")); | ||||
|     if (!sensorFound) { | ||||
|     if (!enabled) { | ||||
|       lux_json.add(F("disabled")); | ||||
|     } else if (!sensorFound) { | ||||
|         // if no sensor  | ||||
|         lux_json.add(F("BH1750 ")); | ||||
|         lux_json.add(F("Not Found")); | ||||
| @@ -210,9 +201,6 @@ public: | ||||
|     top[FPSTR(_minReadInterval)] = minReadingInterval; | ||||
|     top[FPSTR(_HomeAssistantDiscovery)] = HomeAssistantDiscovery; | ||||
|     top[FPSTR(_offset)] = offset; | ||||
|     JsonArray io_pin = top.createNestedArray(F("pin")); | ||||
|     for (byte i=0; i<2; i++) io_pin.add(ioPin[i]); | ||||
|     top[F("help4Pins")] = F("SCL,SDA"); // help for Settings page | ||||
|  | ||||
|     DEBUG_PRINTLN(F("BH1750 config saved.")); | ||||
|   } | ||||
| @@ -220,8 +208,6 @@ public: | ||||
|   // called before setup() to populate properties from values stored in cfg.json | ||||
|   bool readFromConfig(JsonObject &root) | ||||
|   { | ||||
|     int8_t newPin[2]; for (byte i=0; i<2; i++) newPin[i] = ioPin[i]; // prepare to note changed pins | ||||
|  | ||||
|     // we look for JSON object. | ||||
|     JsonObject top = root[FPSTR(_name)]; | ||||
|     if (top.isNull()) | ||||
| @@ -238,27 +224,12 @@ public: | ||||
|     configComplete &= getJsonValue(top[FPSTR(_minReadInterval)], minReadingInterval, 500); //ms | ||||
|     configComplete &= getJsonValue(top[FPSTR(_HomeAssistantDiscovery)], HomeAssistantDiscovery, false); | ||||
|     configComplete &= getJsonValue(top[FPSTR(_offset)], offset, 1); | ||||
|     for (byte i=0; i<2; i++) configComplete &= getJsonValue(top[F("pin")][i], newPin[i], ioPin[i]); | ||||
|  | ||||
|     DEBUG_PRINT(FPSTR(_name)); | ||||
|     if (!initDone) { | ||||
|       // first run: reading from cfg.json | ||||
|       for (byte i=0; i<2; i++) ioPin[i] = newPin[i]; | ||||
|       DEBUG_PRINTLN(F(" config loaded.")); | ||||
|     } else { | ||||
|       DEBUG_PRINTLN(F(" config (re)loaded.")); | ||||
|       // changing parameters from settings page | ||||
|       bool pinsChanged = false; | ||||
|       for (byte i=0; i<2; i++) if (ioPin[i] != newPin[i]) { pinsChanged = true; break; } // check if any pins changed | ||||
|       if (pinsChanged) { //if pins changed, deallocate old pins and allocate new ones | ||||
|         PinOwner po = PinOwner::UM_BH1750; | ||||
|         if (ioPin[0]==HW_PIN_SCL && ioPin[1]==HW_PIN_SDA) po = PinOwner::HW_I2C;  // allow multiple allocations of HW I2C bus pins | ||||
|         pinManager.deallocateMultiplePins((const uint8_t *)ioPin, 2, po);  // deallocate pins | ||||
|         for (byte i=0; i<2; i++) ioPin[i] = newPin[i]; | ||||
|         setup(); | ||||
|       } | ||||
|       // use "return !top["newestParameter"].isNull();" when updating Usermod with new features | ||||
|       return !top[F("pin")].isNull(); | ||||
|     } | ||||
|  | ||||
|     return configComplete; | ||||
|   | ||||
| @@ -1,11 +1,14 @@ | ||||
| // force the compiler to show a warning to confirm that this file is included | ||||
| #warning **** Included USERMOD_BME280 version 2.0 **** | ||||
|  | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
| #include <Arduino.h> | ||||
| #include <Wire.h> | ||||
| #include <BME280I2C.h>               // BME280 sensor | ||||
| #include <EnvironmentCalculations.h> // BME280 extended measurements | ||||
|  | ||||
| @@ -28,9 +31,8 @@ private: | ||||
|  | ||||
|   // set the default pins based on the architecture, these get overridden by Usermod menu settings | ||||
|   #ifdef ESP8266 | ||||
|     //uint8_t RST_PIN = 16; // Uncoment for Heltec WiFi-Kit-8 | ||||
|     //uint8_t RST_PIN = 16; // Un-comment for Heltec WiFi-Kit-8 | ||||
|   #endif | ||||
|   int8_t ioPin[2] = {i2c_scl, i2c_sda};   // I2C pins: SCL, SDA...defaults to Arch hardware pins but overridden at setup() | ||||
|   bool initDone = false; | ||||
|  | ||||
|   // BME280 sensor settings | ||||
| @@ -76,7 +78,7 @@ private: | ||||
|   static const char _name[]; | ||||
|   static const char _enabled[]; | ||||
|  | ||||
|   // Read the BME280/BMP280 Sensor (which one runs depends on whether Celsius or Farenheit being set in Usermod Menu) | ||||
|   // Read the BME280/BMP280 Sensor (which one runs depends on whether Celsius or Fahrenheit being set in Usermod Menu) | ||||
|   void UpdateBME280Data(int SensorType) | ||||
|   { | ||||
|     float _temperature, _humidity, _pressure; | ||||
| @@ -182,14 +184,8 @@ private: | ||||
| public: | ||||
|   void setup() | ||||
|   { | ||||
|     bool HW_Pins_Used = (ioPin[0]==i2c_scl && ioPin[1]==i2c_sda); // note whether architecture-based hardware SCL/SDA pins used | ||||
|     PinOwner po = PinOwner::UM_BME280; // defaults to being pinowner for SCL/SDA pins | ||||
|     PinManagerPinType pins[2] = { { ioPin[0], true }, { ioPin[1], true } };  // allocate pins | ||||
|     if (HW_Pins_Used) po = PinOwner::HW_I2C; // allow multiple allocations of HW I2C bus pins | ||||
|     if (!pinManager.allocateMultiplePins(pins, 2, po)) { sensorType=0; return; } | ||||
|     if (i2c_scl<0 || i2c_sda<0) { enabled = false; sensorType = 0; return; } | ||||
|      | ||||
|     Wire.begin(ioPin[1], ioPin[0]); | ||||
|  | ||||
|     if (!bme.begin()) | ||||
|     { | ||||
|       sensorType = 0; | ||||
| @@ -411,9 +407,6 @@ public: | ||||
|     top[F("PublishAlways")] = PublishAlways; | ||||
|     top[F("UseCelsius")] = UseCelsius; | ||||
|     top[F("HomeAssistantDiscovery")] = HomeAssistantDiscovery; | ||||
|     JsonArray io_pin = top.createNestedArray(F("pin")); | ||||
|     for (byte i=0; i<2; i++) io_pin.add(ioPin[i]); | ||||
|     top[F("help4Pins")] = F("SCL,SDA"); // help for Settings page | ||||
|     DEBUG_PRINTLN(F("BME280 config saved.")); | ||||
|   } | ||||
|  | ||||
| @@ -423,8 +416,6 @@ public: | ||||
|     // default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor | ||||
|     // setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) | ||||
|  | ||||
|     int8_t newPin[2]; for (byte i=0; i<2; i++) newPin[i] = ioPin[i]; // prepare to note changed pins | ||||
|  | ||||
|     JsonObject top = root[FPSTR(_name)]; | ||||
|     if (top.isNull()) { | ||||
|       DEBUG_PRINT(F(_name)); | ||||
| @@ -443,27 +434,14 @@ public: | ||||
|     configComplete &= getJsonValue(top[F("PublishAlways")], PublishAlways, false); | ||||
|     configComplete &= getJsonValue(top[F("UseCelsius")], UseCelsius, true); | ||||
|     configComplete &= getJsonValue(top[F("HomeAssistantDiscovery")], HomeAssistantDiscovery, false); | ||||
|     for (byte i=0; i<2; i++) configComplete &= getJsonValue(top[F("pin")][i], newPin[i], ioPin[i]); | ||||
|  | ||||
|     DEBUG_PRINT(FPSTR(_name)); | ||||
|     if (!initDone) { | ||||
|       // first run: reading from cfg.json | ||||
|       for (byte i=0; i<2; i++) ioPin[i] = newPin[i]; | ||||
|       DEBUG_PRINTLN(F(" config loaded.")); | ||||
|     } else { | ||||
|       DEBUG_PRINTLN(F(" config (re)loaded.")); | ||||
|       // changing parameters from settings page | ||||
|       bool pinsChanged = false; | ||||
|       for (byte i=0; i<2; i++) if (ioPin[i] != newPin[i]) { pinsChanged = true; break; } // check if any pins changed | ||||
|       if (pinsChanged) { //if pins changed, deallocate old pins and allocate new ones | ||||
|         PinOwner po = PinOwner::UM_BME280; | ||||
|         if (ioPin[0]==i2c_scl && ioPin[1]==i2c_sda) po = PinOwner::HW_I2C;  // allow multiple allocations of HW I2C bus pins | ||||
|         pinManager.deallocateMultiplePins((const uint8_t *)ioPin, 2, po);  // deallocate pins | ||||
|         for (byte i=0; i<2; i++) ioPin[i] = newPin[i]; | ||||
|         setup(); | ||||
|       } | ||||
|       // use "return !top["newestParameter"].isNull();" when updating Usermod with new features | ||||
|       return !top[F("pin")].isNull(); | ||||
|     } | ||||
|  | ||||
|     return configComplete; | ||||
|   | ||||
| Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 48 KiB | 
| Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 46 KiB | 
							
								
								
									
										
											BIN
										
									
								
								usermods/Battery/assets/battery_info_screen.png
									
									
									
									
									
										Normal file
									
								
							
							
						
						| After Width: | Height: | Size: 122 KiB | 
							
								
								
									
										
											BIN
										
									
								
								usermods/Battery/assets/battery_usermod_logo.png
									
									
									
									
									
										Normal file
									
								
							
							
						
						| After Width: | Height: | Size: 23 KiB | 
							
								
								
									
										81
									
								
								usermods/Battery/battery_defaults.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,81 @@ | ||||
| // pin defaults | ||||
| // for the esp32 it is best to use the ADC1: GPIO32 - GPIO39 | ||||
| // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html | ||||
| #ifndef USERMOD_BATTERY_MEASUREMENT_PIN | ||||
|   #ifdef ARDUINO_ARCH_ESP32 | ||||
|     #define USERMOD_BATTERY_MEASUREMENT_PIN 35 | ||||
|   #else //ESP8266 boards | ||||
|     #define USERMOD_BATTERY_MEASUREMENT_PIN A0 | ||||
|   #endif | ||||
| #endif | ||||
|  | ||||
| // the frequency to check the battery, 30 sec | ||||
| #ifndef USERMOD_BATTERY_MEASUREMENT_INTERVAL | ||||
|   #define USERMOD_BATTERY_MEASUREMENT_INTERVAL 30000 | ||||
| #endif | ||||
|  | ||||
| // default for 18650 battery | ||||
| // https://batterybro.com/blogs/18650-wholesale-battery-reviews/18852515-when-to-recycle-18650-batteries-and-how-to-start-a-collection-center-in-your-vape-shop | ||||
| // Discharge voltage: 2.5 volt + .1 for personal safety | ||||
| #ifndef USERMOD_BATTERY_MIN_VOLTAGE | ||||
|   #ifdef USERMOD_BATTERY_USE_LIPO | ||||
|     // LiPo "1S" Batteries should not be dischared below 3V !! | ||||
|     #define USERMOD_BATTERY_MIN_VOLTAGE 3.2f | ||||
|   #else | ||||
|     #define USERMOD_BATTERY_MIN_VOLTAGE 2.6f | ||||
|   #endif | ||||
| #endif | ||||
|  | ||||
| //the default ratio for the voltage divider | ||||
| #ifndef USERMOD_BATTERY_VOLTAGE_MULTIPLIER | ||||
|   #ifdef ARDUINO_ARCH_ESP32 | ||||
|     #define USERMOD_BATTERY_VOLTAGE_MULTIPLIER 2.0f | ||||
|   #else //ESP8266 boards | ||||
|     #define USERMOD_BATTERY_VOLTAGE_MULTIPLIER 4.2f | ||||
|   #endif | ||||
| #endif | ||||
|  | ||||
| #ifndef USERMOD_BATTERY_MAX_VOLTAGE | ||||
|   #define USERMOD_BATTERY_MAX_VOLTAGE 4.2f | ||||
| #endif | ||||
|  | ||||
| // a common capacity for single 18650 battery cells is between 2500 and 3600 mAh | ||||
| #ifndef USERMOD_BATTERY_TOTAL_CAPACITY | ||||
|   #define USERMOD_BATTERY_TOTAL_CAPACITY 3100 | ||||
| #endif | ||||
|  | ||||
| // offset or calibration value to fine tune the calculated voltage | ||||
| #ifndef USERMOD_BATTERY_CALIBRATION | ||||
|   #define USERMOD_BATTERY_CALIBRATION 0 | ||||
| #endif | ||||
|  | ||||
| // calculate remaining time / the time that is left before the battery runs out of power | ||||
| // #ifndef USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED | ||||
| //   #define USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED false | ||||
| // #endif | ||||
|  | ||||
| // auto-off feature | ||||
| #ifndef USERMOD_BATTERY_AUTO_OFF_ENABLED | ||||
|   #define USERMOD_BATTERY_AUTO_OFF_ENABLED true | ||||
| #endif | ||||
|  | ||||
| #ifndef USERMOD_BATTERY_AUTO_OFF_THRESHOLD | ||||
|   #define USERMOD_BATTERY_AUTO_OFF_THRESHOLD 10 | ||||
| #endif | ||||
|  | ||||
| // low power indication feature | ||||
| #ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED | ||||
|   #define USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED true | ||||
| #endif | ||||
|  | ||||
| #ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET | ||||
|   #define USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET 0 | ||||
| #endif | ||||
|  | ||||
| #ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD | ||||
|   #define USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD 20 | ||||
| #endif | ||||
|  | ||||
| #ifndef USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION | ||||
|   #define USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION 5 | ||||
| #endif | ||||
							
								
								
									
										112
									
								
								usermods/Battery/readme.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,112 @@ | ||||
| <p align="center"> | ||||
|   <img width="700" src="assets/battery_usermod_logo.png"> | ||||
| </p> | ||||
|  | ||||
| # Welcome to the battery usermod! 🔋 | ||||
|  | ||||
| Enables battery level monitoring of your project. | ||||
|  | ||||
| For this to work, the positive side of the (18650) battery must be connected to pin `A0` of the d1 mini/esp8266 with a 100k Ohm resistor (see [Useful Links](#useful-links)). | ||||
|  | ||||
| If you have an ESP32 board, connect the positive side of the battery to ADC1 (GPIO32 - GPIO39) | ||||
|  | ||||
| <p align="center"> | ||||
|   <img width="500" src="assets/battery_info_screen.png"> | ||||
| </p> | ||||
|  | ||||
| ## ⚙️ Features | ||||
|  | ||||
| - 💯 Displays current battery voltage  | ||||
| - 🚥 Displays battery level | ||||
| - 🚫 Auto-off with configurable Threshold | ||||
| - 🚨 Low power indicator with many configuration possibilities | ||||
|  | ||||
| ## 🎈 Installation | ||||
|  | ||||
| define `USERMOD_BATTERY` in `wled00/my_config.h` | ||||
|  | ||||
| ### Example wiring | ||||
|  | ||||
| <p align="center"> | ||||
|   <img width="300" src="assets/battery_connection_schematic_01.png"> | ||||
| </p> | ||||
|  | ||||
| ### Define Your Options | ||||
|  | ||||
| | Name                                            | Unit        | Description                                                                           | | ||||
| | ----------------------------------------------- | ----------- |-------------------------------------------------------------------------------------- | | ||||
| | `USERMOD_BATTERY`                               |             | define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp | | ||||
| | `USERMOD_BATTERY_USE_LIPO`                      |             | define this (in `my_config.h`) if you use LiPo rechargeables (1S)                     | | ||||
| | `USERMOD_BATTERY_MEASUREMENT_PIN`               |             | defaults to A0 on ESP8266 and GPIO35 on ESP32                                         | | ||||
| | `USERMOD_BATTERY_MEASUREMENT_INTERVAL`          | ms          | battery check interval. defaults to 30 seconds                                        | | ||||
| | `USERMOD_BATTERY_MIN_VOLTAGE`                   | v           | minimum battery voltage. default is 2.6 (18650 battery standard)                      | | ||||
| | `USERMOD_BATTERY_MAX_VOLTAGE`                   | v           | maximum battery voltage. default is 4.2 (18650 battery standard)                      | | ||||
| | `USERMOD_BATTERY_TOTAL_CAPACITY`                | mAh         | the capacity of all cells in parallel summed up                                       | | ||||
| | `USERMOD_BATTERY_CALIBRATION`                   |             | offset / calibration number, fine tune the measured voltage by the microcontroller    | | ||||
| | Auto-Off                                        | ---         | ---                                                                                   | | ||||
| | `USERMOD_BATTERY_AUTO_OFF_ENABLED`              | true/false  | enables auto-off                                                                      | | ||||
| | `USERMOD_BATTERY_AUTO_OFF_THRESHOLD`            | % (0-100)   | when this threshold is reached master power turns off                                 | | ||||
| | Low-Power-Indicator                             | ---         | ---                                                                                   | | ||||
| | `USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED`   | true/false  | enables low power indication                                                          | | ||||
| | `USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET`    | preset id   | when low power is detected then use this preset to indicate low power                 | | ||||
| | `USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD` | % (0-100)   | when this threshold is reached low power gets indicated                               | | ||||
| | `USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION`  | seconds     | for this long the configured preset is played                                         | | ||||
|  | ||||
| All parameters can be configured at runtime via the Usermods settings page. | ||||
|  | ||||
| ## ⚠️ Important | ||||
|  | ||||
| - Make sure you know your battery specifications! All batteries are **NOT** the same! | ||||
| - Example: | ||||
|  | ||||
| | Your battery specification table  |                 | Options you can define        |  | ||||
| | :-------------------------------- |:--------------- | :---------------------------- | | ||||
| | Capacity                          | 3500mAh 12,5 Wh |                               | | ||||
| | Minimum capacity                  | 3350mAh 11,9 Wh |                               | | ||||
| | Rated voltage                     | 3.6V - 3.7V     |                               | | ||||
| | **Charging end voltage**          | **4,2V ± 0,05** | `USERMOD_BATTERY_MAX_VOLTAGE` | | ||||
| | **Discharge voltage**             | **2,5V**        | `USERMOD_BATTERY_MIN_VOLTAGE` | | ||||
| | Max. discharge current (constant) | 10A (10000mA)   |                               | | ||||
| | max. charging current             | 1.7A (1700mA)   |                               | | ||||
| | ...                               | ...             | ...                           | | ||||
| | ..                                | ..              | ..                            | | ||||
|  | ||||
| Specification from:  [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833) | ||||
|  | ||||
| ## 🌐 Useful Links | ||||
|  | ||||
| - https://lazyzero.de/elektronik/esp8266/wemos_d1_mini_a0/start | ||||
| - https://arduinodiy.wordpress.com/2016/12/25/monitoring-lipo-battery-voltage-with-wemos-d1-minibattery-shield-and-thingspeak/ | ||||
|  | ||||
| ## 📝 Change Log | ||||
|  | ||||
| 2023-01-04 | ||||
|  | ||||
| - basic support for LiPo rechargeable batteries ( `-D USERMOD_BATTERY_USE_LIPO`) | ||||
| - improved support for esp32 (read calibrated voltage) | ||||
| - corrected config saving (measurement pin, and battery min/max were lost) | ||||
| - various bugfixes | ||||
|  | ||||
| 2022-12-25 | ||||
|  | ||||
| - added "auto-off" feature | ||||
| - added "low-power-indication" feature | ||||
| - added "calibration/offset" field to configuration page | ||||
| - added getter and setter, so that user usermods could interact with this one | ||||
| - update readme (added new options, made it markdownlint compliant) | ||||
|  | ||||
| 2021-09-02 | ||||
|  | ||||
| - added "Battery voltage" to info | ||||
| - added circuit diagram to readme | ||||
| - added MQTT support, sending battery voltage | ||||
| - minor fixes | ||||
|  | ||||
| 2021-08-15 | ||||
|  | ||||
| - changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries | ||||
| - Updated readme, added specification table | ||||
|  | ||||
| 2021-08-10 | ||||
|  | ||||
| - Created | ||||
							
								
								
									
										787
									
								
								usermods/Battery/usermod_v2_Battery.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,787 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
| #include "battery_defaults.h" | ||||
|  | ||||
| /* | ||||
|  * Usermod by Maximilian Mewes | ||||
|  * Mail: mewes.maximilian@gmx.de | ||||
|  * GitHub: itCarl | ||||
|  * Date: 25.12.2022 | ||||
|  * If you have any questions, please feel free to contact me. | ||||
|  */ | ||||
| class UsermodBattery : public Usermod  | ||||
| { | ||||
|   private: | ||||
|     // battery pin can be defined in my_config.h | ||||
|     int8_t batteryPin = USERMOD_BATTERY_MEASUREMENT_PIN; | ||||
|     // how often to read the battery voltage | ||||
|     unsigned long readingInterval = USERMOD_BATTERY_MEASUREMENT_INTERVAL; | ||||
|     unsigned long nextReadTime = 0; | ||||
|     unsigned long lastReadTime = 0; | ||||
|     // battery min. voltage | ||||
|     float minBatteryVoltage = USERMOD_BATTERY_MIN_VOLTAGE; | ||||
|     // battery max. voltage | ||||
|     float maxBatteryVoltage = USERMOD_BATTERY_MAX_VOLTAGE; | ||||
|     // all battery cells summed up | ||||
|     unsigned int totalBatteryCapacity = USERMOD_BATTERY_TOTAL_CAPACITY; | ||||
|     // raw analog reading  | ||||
|     float rawValue = 0.0f; | ||||
|     // calculated voltage             | ||||
|     float voltage = maxBatteryVoltage; | ||||
|     // between 0 and 1, to control strength of voltage smoothing filter | ||||
|     float alpha = 0.05f; | ||||
|     // multiplier for the voltage divider that is in place between ADC pin and battery, default will be 2 but might be adapted to readout voltages over ~5v ESP32 or ~6.6v ESP8266 | ||||
|     float voltageMultiplier = USERMOD_BATTERY_VOLTAGE_MULTIPLIER; | ||||
|     // mapped battery level based on voltage | ||||
|     int8_t batteryLevel = 100; | ||||
|     // offset or calibration value to fine tune the calculated voltage | ||||
|     float calibration = USERMOD_BATTERY_CALIBRATION; | ||||
|      | ||||
|     // time left estimation feature | ||||
|     // bool calculateTimeLeftEnabled = USERMOD_BATTERY_CALCULATE_TIME_LEFT_ENABLED; | ||||
|     // float estimatedTimeLeft = 0.0; | ||||
|  | ||||
|     // auto shutdown/shutoff/master off feature | ||||
|     bool autoOffEnabled = USERMOD_BATTERY_AUTO_OFF_ENABLED; | ||||
|     int8_t autoOffThreshold = USERMOD_BATTERY_AUTO_OFF_THRESHOLD; | ||||
|  | ||||
|     // low power indicator feature | ||||
|     bool lowPowerIndicatorEnabled = USERMOD_BATTERY_LOW_POWER_INDICATOR_ENABLED; | ||||
|     int8_t lowPowerIndicatorPreset = USERMOD_BATTERY_LOW_POWER_INDICATOR_PRESET; | ||||
|     int8_t lowPowerIndicatorThreshold = USERMOD_BATTERY_LOW_POWER_INDICATOR_THRESHOLD; | ||||
|     int8_t lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10; | ||||
|     int8_t lowPowerIndicatorDuration = USERMOD_BATTERY_LOW_POWER_INDICATOR_DURATION; | ||||
|     bool lowPowerIndicationDone = false; | ||||
|     unsigned long lowPowerActivationTime = 0; // used temporary during active time | ||||
|     int8_t lastPreset = 0; | ||||
|  | ||||
|     bool initDone = false; | ||||
|     bool initializing = true; | ||||
|  | ||||
|     // strings to reduce flash memory usage (used more than twice) | ||||
|     static const char _name[]; | ||||
|     static const char _readInterval[]; | ||||
|     static const char _enabled[]; | ||||
|     static const char _threshold[]; | ||||
|     static const char _preset[]; | ||||
|     static const char _duration[]; | ||||
|     static const char _init[]; | ||||
|      | ||||
|  | ||||
|     // custom map function | ||||
|     // https://forum.arduino.cc/t/floating-point-using-map-function/348113/2 | ||||
|     double mapf(double x, double in_min, double in_max, double out_min, double out_max)  | ||||
|     { | ||||
|       return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; | ||||
|     } | ||||
|  | ||||
|     float dot2round(float x)  | ||||
|     { | ||||
|       float nx = (int)(x * 100 + .5); | ||||
|       return (float)(nx / 100); | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Turn off all leds | ||||
|      */ | ||||
|     void turnOff() | ||||
|     { | ||||
|       bri = 0; | ||||
|       stateUpdated(CALL_MODE_DIRECT_CHANGE); | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Indicate low power by activating a configured preset for a given time and then switching back to the preset that was selected previously | ||||
|      */ | ||||
|     void lowPowerIndicator() | ||||
|     { | ||||
|       if (!lowPowerIndicatorEnabled) return; | ||||
|       if (batteryPin < 0) return;  // no measurement | ||||
|       if (lowPowerIndicationDone && lowPowerIndicatorReactivationThreshold <= batteryLevel) lowPowerIndicationDone = false; | ||||
|       if (lowPowerIndicatorThreshold <= batteryLevel) return; | ||||
|       if (lowPowerIndicationDone) return; | ||||
|       if (lowPowerActivationTime <= 1) { | ||||
|         lowPowerActivationTime = millis(); | ||||
|         lastPreset = currentPreset; | ||||
|         applyPreset(lowPowerIndicatorPreset); | ||||
|       } | ||||
|  | ||||
|       if (lowPowerActivationTime+(lowPowerIndicatorDuration*1000) <= millis()) { | ||||
|         lowPowerIndicationDone = true; | ||||
|         lowPowerActivationTime = 0; | ||||
|         applyPreset(lastPreset); | ||||
|       }       | ||||
|     } | ||||
|  | ||||
|     float readVoltage() | ||||
|     { | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         // use calibrated millivolts analogread on esp32 (150 mV ~ 2450 mV default attentuation) and divide by 1000 to get from milivolts to volts and multiply by voltage multiplier and apply calibration value | ||||
|         return (analogReadMilliVolts(batteryPin) / 1000.0f) * voltageMultiplier  + calibration; | ||||
|       #else | ||||
|         // use analog read on esp8266 ( 0V ~ 1V no attenuation options) and divide by ADC precision 1023 and multiply by voltage multiplier and apply calibration value | ||||
|         return (analogRead(batteryPin) / 1023.0f) * voltageMultiplier + calibration; | ||||
|       #endif | ||||
|     } | ||||
|  | ||||
|   public: | ||||
|     //Functions called by WLED | ||||
|  | ||||
|     /* | ||||
|      * setup() is called once at boot. WiFi is not yet connected at this point. | ||||
|      * You can use it to initialize variables, sensors or similar. | ||||
|      */ | ||||
|     void setup()  | ||||
|     { | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         bool success = false; | ||||
|         DEBUG_PRINTLN(F("Allocating battery pin...")); | ||||
|         if (batteryPin >= 0 && digitalPinToAnalogChannel(batteryPin) >= 0)  | ||||
|           if (pinManager.allocatePin(batteryPin, false, PinOwner::UM_Battery)) { | ||||
|             DEBUG_PRINTLN(F("Battery pin allocation succeeded.")); | ||||
|             success = true; | ||||
|             voltage = readVoltage(); | ||||
|           } | ||||
|  | ||||
|         if (!success) { | ||||
|           DEBUG_PRINTLN(F("Battery pin allocation failed.")); | ||||
|           batteryPin = -1;  // allocation failed | ||||
|         } else { | ||||
|           pinMode(batteryPin, INPUT); | ||||
|         } | ||||
|       #else //ESP8266 boards have only one analog input pin A0 | ||||
|         pinMode(batteryPin, INPUT); | ||||
|         voltage = readVoltage(); | ||||
|       #endif | ||||
|  | ||||
|       nextReadTime = millis() + readingInterval; | ||||
|       lastReadTime = millis(); | ||||
|  | ||||
|       initDone = true; | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * connected() is called every time the WiFi is (re)connected | ||||
|      * Use it to initialize network interfaces | ||||
|      */ | ||||
|     void connected()  | ||||
|     { | ||||
|       //Serial.println("Connected to WiFi!"); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * loop() is called continuously. Here you can check for events, read sensors, etc. | ||||
|      *  | ||||
|      */ | ||||
|     void loop()  | ||||
|     { | ||||
|       if(strip.isUpdating()) return; | ||||
|  | ||||
|       lowPowerIndicator(); | ||||
|  | ||||
|       // check the battery level every USERMOD_BATTERY_MEASUREMENT_INTERVAL (ms) | ||||
|       if (millis() < nextReadTime) return; | ||||
|  | ||||
|       nextReadTime = millis() + readingInterval; | ||||
|       lastReadTime = millis(); | ||||
|  | ||||
|       if (batteryPin < 0) return;  // nothing to read | ||||
|  | ||||
|       initializing = false; | ||||
|  | ||||
|       rawValue = readVoltage(); | ||||
|       // filter with exponential smoothing because ADC in esp32 is fluctuating too much for a good single readout | ||||
|       voltage = voltage + alpha * (rawValue - voltage); | ||||
|  | ||||
|       // check if voltage is within specified voltage range, allow 10% over/under voltage - removed cause this just makes it hard for people to troubleshoot as the voltage in the web gui will say invalid instead of displaying a voltage | ||||
|       //voltage = ((voltage < minBatteryVoltage * 0.85f) || (voltage > maxBatteryVoltage * 1.1f)) ? -1.0f : voltage; | ||||
|  | ||||
|       // translate battery voltage into percentage | ||||
|       /* | ||||
|         the standard "map" function doesn't work | ||||
|         https://www.arduino.cc/reference/en/language/functions/math/map/  notes and warnings at the bottom | ||||
|       */ | ||||
|       #ifdef USERMOD_BATTERY_USE_LIPO | ||||
|         batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100); // basic mapping | ||||
|         // LiPo batteries have a differnt dischargin curve, see  | ||||
|         //  https://blog.ampow.com/lipo-voltage-chart/ | ||||
|         if (batteryLevel < 40.0f)  | ||||
|           batteryLevel = mapf(batteryLevel, 0, 40, 0, 12);       // last 45% -> drops very quickly | ||||
|         else { | ||||
|           if (batteryLevel < 90.0f) | ||||
|             batteryLevel = mapf(batteryLevel, 40, 90, 12, 95);   // 90% ... 40% -> almost linear drop | ||||
|           else // level >  90% | ||||
|             batteryLevel = mapf(batteryLevel, 90, 105, 95, 100); // highest 15% -> drop slowly | ||||
|         } | ||||
|       #else | ||||
|         batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100); | ||||
|       #endif | ||||
|       if (voltage > -1.0f) batteryLevel = constrain(batteryLevel, 0.0f, 110.0f); | ||||
|  | ||||
|       // if (calculateTimeLeftEnabled) { | ||||
|       //   float currentBatteryCapacity = totalBatteryCapacity; | ||||
|       //   estimatedTimeLeft = (currentBatteryCapacity/strip.currentMilliamps)*60; | ||||
|       // } | ||||
|  | ||||
|       // Auto off -- Master power off | ||||
|       if (autoOffEnabled && (autoOffThreshold >= batteryLevel)) | ||||
|         turnOff(); | ||||
|  | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|       // SmartHome stuff | ||||
|       // still don't know much about MQTT and/or HA | ||||
|       if (WLED_MQTT_CONNECTED) { | ||||
|         char buf[64]; // buffer for snprintf() | ||||
|         snprintf_P(buf, 63, PSTR("%s/voltage"), mqttDeviceTopic); | ||||
|         mqtt->publish(buf, 0, false, String(voltage).c_str()); | ||||
|       } | ||||
| #endif | ||||
|  | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. | ||||
|      * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. | ||||
|      * Below it is shown how this could be used for e.g. a light sensor | ||||
|      */ | ||||
|     void addToJsonInfo(JsonObject& root) | ||||
|     { | ||||
|       JsonObject user = root["u"]; | ||||
|       if (user.isNull()) user = root.createNestedObject("u"); | ||||
|  | ||||
|       if (batteryPin < 0) { | ||||
|         JsonArray infoVoltage = user.createNestedArray(F("Battery voltage")); | ||||
|         infoVoltage.add(F("n/a")); | ||||
|         infoVoltage.add(F(" invalid GPIO")); | ||||
|         return;  // no GPIO - nothing to report | ||||
|       } | ||||
|  | ||||
|       // info modal display names | ||||
|       JsonArray infoPercentage = user.createNestedArray(F("Battery level")); | ||||
|       JsonArray infoVoltage = user.createNestedArray(F("Battery voltage")); | ||||
|       // if (calculateTimeLeftEnabled) | ||||
|       // { | ||||
|       //   JsonArray infoEstimatedTimeLeft = user.createNestedArray(F("Estimated time left")); | ||||
|       //   if (initializing) { | ||||
|       //     infoEstimatedTimeLeft.add(FPSTR(_init)); | ||||
|       //   } else { | ||||
|       //     infoEstimatedTimeLeft.add(estimatedTimeLeft); | ||||
|       //     infoEstimatedTimeLeft.add(F(" min")); | ||||
|       //   } | ||||
|       // } | ||||
|       JsonArray infoNextUpdate = user.createNestedArray(F("Next update")); | ||||
|  | ||||
|       infoNextUpdate.add((nextReadTime - millis()) / 1000); | ||||
|       infoNextUpdate.add(F(" sec")); | ||||
|        | ||||
|       if (initializing) { | ||||
|         infoPercentage.add(FPSTR(_init)); | ||||
|         infoVoltage.add(FPSTR(_init)); | ||||
|         return; | ||||
|       } | ||||
|  | ||||
|       if (batteryLevel < 0) { | ||||
|         infoPercentage.add(F("invalid")); | ||||
|       } else { | ||||
|         infoPercentage.add(batteryLevel); | ||||
|       } | ||||
|       infoPercentage.add(F(" %")); | ||||
|  | ||||
|       if (voltage < 0) { | ||||
|         infoVoltage.add(F("invalid")); | ||||
|       } else { | ||||
|         infoVoltage.add(dot2round(voltage)); | ||||
|       } | ||||
|       infoVoltage.add(F(" V")); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). | ||||
|      * Values in the state object may be modified by connected clients | ||||
|      */ | ||||
|     /* | ||||
|     void addToJsonState(JsonObject& root) | ||||
|     { | ||||
|  | ||||
|     } | ||||
|     */ | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). | ||||
|      * Values in the state object may be modified by connected clients | ||||
|      */ | ||||
|     /* | ||||
|     void readFromJsonState(JsonObject& root) | ||||
|     { | ||||
|     } | ||||
|     */ | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object. | ||||
|      * It will be called by WLED when settings are actually saved (for example, LED settings are saved) | ||||
|      * If you want to force saving the current state, use serializeConfig() in your loop(). | ||||
|      *  | ||||
|      * CAUTION: serializeConfig() will initiate a filesystem write operation. | ||||
|      * It might cause the LEDs to stutter and will cause flash wear if called too often. | ||||
|      * Use it sparingly and always in the loop, never in network callbacks! | ||||
|      *  | ||||
|      * addToConfig() will make your settings editable through the Usermod Settings page automatically. | ||||
|      * | ||||
|      * Usermod Settings Overview: | ||||
|      * - Numeric values are treated as floats in the browser. | ||||
|      *   - If the numeric value entered into the browser contains a decimal point, it will be parsed as a C float | ||||
|      *     before being returned to the Usermod.  The float data type has only 6-7 decimal digits of precision, and | ||||
|      *     doubles are not supported, numbers will be rounded to the nearest float value when being parsed. | ||||
|      *     The range accepted by the input field is +/- 1.175494351e-38 to +/- 3.402823466e+38. | ||||
|      *   - If the numeric value entered into the browser doesn't contain a decimal point, it will be parsed as a | ||||
|      *     C int32_t (range: -2147483648 to 2147483647) before being returned to the usermod. | ||||
|      *     Overflows or underflows are truncated to the max/min value for an int32_t, and again truncated to the type | ||||
|      *     used in the Usermod when reading the value from ArduinoJson. | ||||
|      * - Pin values can be treated differently from an integer value by using the key name "pin" | ||||
|      *   - "pin" can contain a single or array of integer values | ||||
|      *   - On the Usermod Settings page there is simple checking for pin conflicts and warnings for special pins | ||||
|      *     - Red color indicates a conflict.  Yellow color indicates a pin with a warning (e.g. an input-only pin) | ||||
|      *   - Tip: use int8_t to store the pin value in the Usermod, so a -1 value (pin not set) can be used | ||||
|      * | ||||
|      * See usermod_v2_auto_save.h for an example that saves Flash space by reusing ArduinoJson key name strings | ||||
|      *  | ||||
|      * If you need a dedicated settings page with custom layout for your Usermod, that takes a lot more work.   | ||||
|      * You will have to add the setting to the HTML, xml.cpp and set.cpp manually. | ||||
|      * See the WLED Soundreactive fork (code and wiki) for reference.  https://github.com/atuline/WLED | ||||
|      *  | ||||
|      * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! | ||||
|      */ | ||||
|     void addToConfig(JsonObject& root) | ||||
|     { | ||||
|       JsonObject battery = root.createNestedObject(FPSTR(_name));           // usermodname | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         battery[F("pin")] = batteryPin; | ||||
|       #endif | ||||
|  | ||||
|       // battery[F("time-left")] = calculateTimeLeftEnabled; | ||||
|       battery[F("min-voltage")] = minBatteryVoltage; | ||||
|       battery[F("max-voltage")] = maxBatteryVoltage; | ||||
|       battery[F("capacity")] = totalBatteryCapacity; | ||||
|       battery[F("calibration")] = calibration; | ||||
|       battery[F("voltage-multiplier")] = voltageMultiplier; | ||||
|       battery[FPSTR(_readInterval)] = readingInterval; | ||||
|        | ||||
|       JsonObject ao = battery.createNestedObject(F("auto-off"));               // auto off section | ||||
|       ao[FPSTR(_enabled)] = autoOffEnabled; | ||||
|       ao[FPSTR(_threshold)] = autoOffThreshold; | ||||
|  | ||||
|       JsonObject lp = battery.createNestedObject(F("indicator"));    // low power section | ||||
|       lp[FPSTR(_enabled)] = lowPowerIndicatorEnabled; | ||||
|       lp[FPSTR(_preset)] = lowPowerIndicatorPreset; // dropdown trickery (String)lowPowerIndicatorPreset;  | ||||
|       lp[FPSTR(_threshold)] = lowPowerIndicatorThreshold; | ||||
|       lp[FPSTR(_duration)] = lowPowerIndicatorDuration; | ||||
|  | ||||
|       // read voltage in case calibration or voltage multiplier changed to see immediate effect | ||||
|       voltage = readVoltage(); | ||||
|  | ||||
|       DEBUG_PRINTLN(F("Battery config saved.")); | ||||
|     } | ||||
|  | ||||
|     void appendConfigData() | ||||
|     { | ||||
|       oappend(SET_F("addInfo('Battery:min-voltage', 1, 'v');")); | ||||
|       oappend(SET_F("addInfo('Battery:max-voltage', 1, 'v');")); | ||||
|       oappend(SET_F("addInfo('Battery:capacity', 1, 'mAh');")); | ||||
|       oappend(SET_F("addInfo('Battery:interval', 1, 'ms');")); | ||||
|       oappend(SET_F("addInfo('Battery:auto-off:threshold', 1, '%');")); | ||||
|       oappend(SET_F("addInfo('Battery:indicator:threshold', 1, '%');")); | ||||
|       oappend(SET_F("addInfo('Battery:indicator:duration', 1, 's');")); | ||||
|        | ||||
|       // cannot quite get this mf to work. its exeeding some buffer limit i think | ||||
|       // what i wanted is a list of all presets to select one from | ||||
|       // oappend(SET_F("bd=addDropdown('Battery:low-power-indicator', 'preset');")); | ||||
|       // the loop generates: oappend(SET_F("addOption(bd, 'preset name', preset id);")); | ||||
|       // for(int8_t i=1; i < 42; i++) { | ||||
|       //   oappend(SET_F("addOption(bd, 'Preset#")); | ||||
|       //   oappendi(i); | ||||
|       //   oappend(SET_F("',")); | ||||
|       //   oappendi(i); | ||||
|       //   oappend(SET_F(");")); | ||||
|       // } | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * readFromConfig() can be used to read back the custom settings you added with addToConfig(). | ||||
|      * This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page) | ||||
|      *  | ||||
|      * readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes), | ||||
|      * but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup. | ||||
|      * If you don't know what that is, don't fret. It most likely doesn't affect your use case :) | ||||
|      *  | ||||
|      * Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings) | ||||
|      *  | ||||
|      * getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present | ||||
|      * The configComplete variable is true only if the "exampleUsermod" object and all values are present.  If any values are missing, WLED will know to call addToConfig() to save them | ||||
|      *  | ||||
|      * This function is guaranteed to be called on boot, but could also be called every time settings are updated | ||||
|      */ | ||||
|     bool readFromConfig(JsonObject& root) | ||||
|     { | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         int8_t newBatteryPin = batteryPin; | ||||
|       #endif | ||||
|        | ||||
|       JsonObject battery = root[FPSTR(_name)]; | ||||
|       if (battery.isNull())  | ||||
|       { | ||||
|         DEBUG_PRINT(FPSTR(_name)); | ||||
|         DEBUG_PRINTLN(F(": No config found. (Using defaults.)")); | ||||
|         return false; | ||||
|       } | ||||
|  | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         newBatteryPin     = battery[F("pin")] | newBatteryPin; | ||||
|       #endif | ||||
|       // calculateTimeLeftEnabled = battery[F("time-left")] | calculateTimeLeftEnabled; | ||||
|       setMinBatteryVoltage(battery[F("min-voltage")] | minBatteryVoltage); | ||||
|       setMaxBatteryVoltage(battery[F("max-voltage")] | maxBatteryVoltage); | ||||
|       setTotalBatteryCapacity(battery[F("capacity")] | totalBatteryCapacity); | ||||
|       setCalibration(battery[F("calibration")] | calibration); | ||||
|       setVoltageMultiplier(battery[F("voltage-multiplier")] | voltageMultiplier); | ||||
|       setReadingInterval(battery[FPSTR(_readInterval)] | readingInterval); | ||||
|  | ||||
|       JsonObject ao = battery[F("auto-off")]; | ||||
|       setAutoOffEnabled(ao[FPSTR(_enabled)] | autoOffEnabled); | ||||
|       setAutoOffThreshold(ao[FPSTR(_threshold)] | autoOffThreshold); | ||||
|  | ||||
|       JsonObject lp = battery[F("indicator")]; | ||||
|       setLowPowerIndicatorEnabled(lp[FPSTR(_enabled)] | lowPowerIndicatorEnabled); | ||||
|       setLowPowerIndicatorPreset(lp[FPSTR(_preset)] | lowPowerIndicatorPreset); // dropdown trickery (int)lp["preset"] | ||||
|       setLowPowerIndicatorThreshold(lp[FPSTR(_threshold)] | lowPowerIndicatorThreshold); | ||||
|       lowPowerIndicatorReactivationThreshold = lowPowerIndicatorThreshold+10; | ||||
|       setLowPowerIndicatorDuration(lp[FPSTR(_duration)] | lowPowerIndicatorDuration); | ||||
|  | ||||
|       DEBUG_PRINT(FPSTR(_name)); | ||||
|  | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         if (!initDone)  | ||||
|         { | ||||
|           // first run: reading from cfg.json | ||||
|           batteryPin = newBatteryPin; | ||||
|           DEBUG_PRINTLN(F(" config loaded.")); | ||||
|         }  | ||||
|         else  | ||||
|         { | ||||
|           DEBUG_PRINTLN(F(" config (re)loaded.")); | ||||
|  | ||||
|           // changing parameters from settings page | ||||
|           if (newBatteryPin != batteryPin)  | ||||
|           { | ||||
|             // deallocate pin | ||||
|             pinManager.deallocatePin(batteryPin, PinOwner::UM_Battery); | ||||
|             batteryPin = newBatteryPin; | ||||
|             // initialise | ||||
|             setup(); | ||||
|           } | ||||
|         } | ||||
|       #endif | ||||
|  | ||||
|       return !battery[FPSTR(_readInterval)].isNull(); | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Generate a preset sample for low power indication  | ||||
|      */ | ||||
|     void generateExamplePreset() | ||||
|     { | ||||
|       // StaticJsonDocument<300> j; | ||||
|       // JsonObject preset = j.createNestedObject(); | ||||
|       // preset["mainseg"] = 0; | ||||
|       // JsonArray seg = preset.createNestedArray("seg"); | ||||
|       // JsonObject seg0 = seg.createNestedObject(); | ||||
|       // seg0["id"] = 0; | ||||
|       // seg0["start"] = 0; | ||||
|       // seg0["stop"] = 60; | ||||
|       // seg0["grp"] = 0; | ||||
|       // seg0["spc"] = 0; | ||||
|       // seg0["on"] = true; | ||||
|       // seg0["bri"] = 255; | ||||
|  | ||||
|       // JsonArray col0 = seg0.createNestedArray("col"); | ||||
|       // JsonArray col00 = col0.createNestedArray(); | ||||
|       // col00.add(255); | ||||
|       // col00.add(0); | ||||
|       // col00.add(0); | ||||
|  | ||||
|       // seg0["fx"] = 1; | ||||
|       // seg0["sx"] = 128; | ||||
|       // seg0["ix"] = 128; | ||||
|  | ||||
|       // savePreset(199, "Low power Indicator", preset); | ||||
|     } | ||||
|     | ||||
|  | ||||
|     /* | ||||
|      * | ||||
|      * Getter and Setter. Just in case some other usermod wants to interact with this in the future | ||||
|      * | ||||
|      */ | ||||
|  | ||||
|     /* | ||||
|      * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). | ||||
|      * This could be used in the future for the system to determine whether your usermod is installed. | ||||
|      */ | ||||
|     uint16_t getId() | ||||
|     { | ||||
|       return USERMOD_ID_BATTERY; | ||||
|     } | ||||
|  | ||||
|  | ||||
|     unsigned long getReadingInterval() | ||||
|     { | ||||
|       return readingInterval; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * minimum repetition is 3000ms (3s)  | ||||
|      */ | ||||
|     void setReadingInterval(unsigned long newReadingInterval) | ||||
|     { | ||||
|       readingInterval = max((unsigned long)3000, newReadingInterval); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * Get lowest configured battery voltage | ||||
|      */ | ||||
|     float getMinBatteryVoltage() | ||||
|     { | ||||
|       return minBatteryVoltage; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Set lowest battery voltage | ||||
|      * can't be below 0 volt | ||||
|      */ | ||||
|     void setMinBatteryVoltage(float voltage) | ||||
|     { | ||||
|       minBatteryVoltage = max(0.0f, voltage); | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Get highest configured battery voltage | ||||
|      */ | ||||
|     float getMaxBatteryVoltage() | ||||
|     { | ||||
|       return maxBatteryVoltage; | ||||
|     } | ||||
|      | ||||
|     /* | ||||
|      * Set highest battery voltage | ||||
|      * can't be below minBatteryVoltage | ||||
|      */ | ||||
|     void setMaxBatteryVoltage(float voltage) | ||||
|     { | ||||
|       #ifdef USERMOD_BATTERY_USE_LIPO | ||||
|         maxBatteryVoltage = max(getMinBatteryVoltage()+0.7f, voltage); | ||||
|       #else | ||||
|         maxBatteryVoltage = max(getMinBatteryVoltage()+1.0f, voltage); | ||||
|       #endif | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * Get the capacity of all cells in parralel sumed up | ||||
|      * unit: mAh | ||||
|      */ | ||||
|     unsigned int getTotalBatteryCapacity() | ||||
|     { | ||||
|       return totalBatteryCapacity; | ||||
|     } | ||||
|  | ||||
|     void setTotalBatteryCapacity(unsigned int capacity) | ||||
|     { | ||||
|       totalBatteryCapacity = capacity; | ||||
|     } | ||||
|  | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * Get the calculated voltage | ||||
|      * formula: (adc pin value / adc precision * max voltage) + calibration | ||||
|      */ | ||||
|     float getVoltage() | ||||
|     { | ||||
|       return voltage; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Get the mapped battery level (0 - 100) based on voltage | ||||
|      * important: voltage can drop when a load is applied, so its only an estimate | ||||
|      */ | ||||
|     int8_t getBatteryLevel() | ||||
|     { | ||||
|       return batteryLevel; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Get the configured calibration value | ||||
|      * a offset value to fine-tune the calculated voltage. | ||||
|      */ | ||||
|     float getCalibration() | ||||
|     { | ||||
|       return calibration; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Set the voltage calibration offset value | ||||
|      * a offset value to fine-tune the calculated voltage. | ||||
|      */ | ||||
|     void setCalibration(float offset) | ||||
|     { | ||||
|       calibration = offset; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Set the voltage multiplier value | ||||
|      * A multiplier that may need adjusting for different voltage divider setups | ||||
|      */ | ||||
|     void setVoltageMultiplier(float multiplier) | ||||
|     { | ||||
|       voltageMultiplier = multiplier; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Get the voltage multiplier value | ||||
|      * A multiplier that may need adjusting for different voltage divider setups | ||||
|      */ | ||||
|     float getVoltageMultiplier() | ||||
|     { | ||||
|       return voltageMultiplier; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Get auto-off feature enabled status | ||||
|      * is auto-off enabled, true/false | ||||
|      */ | ||||
|     bool getAutoOffEnabled() | ||||
|     { | ||||
|       return autoOffEnabled; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Set auto-off feature status  | ||||
|      */ | ||||
|     void setAutoOffEnabled(bool enabled) | ||||
|     { | ||||
|       autoOffEnabled = enabled; | ||||
|     } | ||||
|      | ||||
|     /* | ||||
|      * Get auto-off threshold in percent (0-100) | ||||
|      */ | ||||
|     int8_t getAutoOffThreshold() | ||||
|     { | ||||
|       return autoOffThreshold; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Set auto-off threshold in percent (0-100)  | ||||
|      */ | ||||
|     void setAutoOffThreshold(int8_t threshold) | ||||
|     { | ||||
|       autoOffThreshold = min((int8_t)100, max((int8_t)0, threshold)); | ||||
|       // when low power indicator is enabled the auto-off threshold cannot be above indicator threshold | ||||
|       autoOffThreshold  = lowPowerIndicatorEnabled /*&& autoOffEnabled*/ ? min(lowPowerIndicatorThreshold-1, (int)autoOffThreshold) : autoOffThreshold; | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * Get low-power-indicator feature enabled status | ||||
|      * is the low-power-indicator enabled, true/false | ||||
|      */ | ||||
|     bool getLowPowerIndicatorEnabled() | ||||
|     { | ||||
|       return lowPowerIndicatorEnabled; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Set low-power-indicator feature status  | ||||
|      */ | ||||
|     void setLowPowerIndicatorEnabled(bool enabled) | ||||
|     { | ||||
|       lowPowerIndicatorEnabled = enabled; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Get low-power-indicator preset to activate when low power is detected | ||||
|      */ | ||||
|     int8_t getLowPowerIndicatorPreset() | ||||
|     { | ||||
|       return lowPowerIndicatorPreset; | ||||
|     } | ||||
|  | ||||
|     /*  | ||||
|      * Set low-power-indicator preset to activate when low power is detected | ||||
|      */ | ||||
|     void setLowPowerIndicatorPreset(int8_t presetId) | ||||
|     { | ||||
|       // String tmp = ""; For what ever reason this doesn't work :( | ||||
|       // lowPowerIndicatorPreset = getPresetName(presetId, tmp) ? presetId : lowPowerIndicatorPreset; | ||||
|       lowPowerIndicatorPreset = presetId; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Get low-power-indicator threshold in percent (0-100) | ||||
|      */ | ||||
|     int8_t getLowPowerIndicatorThreshold() | ||||
|     { | ||||
|       return lowPowerIndicatorThreshold; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Set low-power-indicator threshold in percent (0-100) | ||||
|      */ | ||||
|     void setLowPowerIndicatorThreshold(int8_t threshold) | ||||
|     { | ||||
|       lowPowerIndicatorThreshold = threshold; | ||||
|       // when auto-off is enabled the indicator threshold cannot be below auto-off threshold | ||||
|       lowPowerIndicatorThreshold  = autoOffEnabled /*&& lowPowerIndicatorEnabled*/ ? max(autoOffThreshold+1, (int)lowPowerIndicatorThreshold) : max(5, (int)lowPowerIndicatorThreshold); | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Get low-power-indicator duration in seconds | ||||
|      */ | ||||
|     int8_t getLowPowerIndicatorDuration() | ||||
|     { | ||||
|       return lowPowerIndicatorDuration; | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * Set low-power-indicator duration in seconds | ||||
|      */ | ||||
|     void setLowPowerIndicatorDuration(int8_t duration) | ||||
|     { | ||||
|       lowPowerIndicatorDuration = duration; | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * Get low-power-indicator status when the indication is done thsi returns true | ||||
|      */ | ||||
|     bool getLowPowerIndicatorDone() | ||||
|     { | ||||
|       return lowPowerIndicationDone; | ||||
|     } | ||||
| }; | ||||
|  | ||||
| // strings to reduce flash memory usage (used more than twice) | ||||
| const char UsermodBattery::_name[]          PROGMEM = "Battery"; | ||||
| const char UsermodBattery::_readInterval[]  PROGMEM = "interval"; | ||||
| const char UsermodBattery::_enabled[]       PROGMEM = "enabled"; | ||||
| const char UsermodBattery::_threshold[]     PROGMEM = "threshold"; | ||||
| const char UsermodBattery::_preset[]        PROGMEM = "preset"; | ||||
| const char UsermodBattery::_duration[]      PROGMEM = "duration"; | ||||
| const char UsermodBattery::_init[]          PROGMEM = "init"; | ||||
| @@ -271,6 +271,7 @@ class UsermodCronixie : public Usermod { | ||||
|     { | ||||
|       if (root["nx"].is<const char*>()) { | ||||
|         strncpy(cronixieDisplay, root["nx"], 6); | ||||
|         setCronixie(); | ||||
|       } | ||||
|     } | ||||
|  | ||||
|   | ||||
| @@ -1,6 +1,10 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
|  | ||||
| #include <dht_nonblocking.h> | ||||
|  | ||||
| @@ -45,7 +49,7 @@ | ||||
| #endif | ||||
|  | ||||
| // how many seconds after boot to take first measurement, 90 seconds | ||||
| // 90 gives enough time to OTA update firmware if this crashses | ||||
| // 90 gives enough time to OTA update firmware if this crashes | ||||
| #ifndef USERMOD_DHT_FIRST_MEASUREMENT_AT | ||||
| #define USERMOD_DHT_FIRST_MEASUREMENT_AT 90000 | ||||
| #endif | ||||
|   | ||||
| @@ -22,8 +22,12 @@ | ||||
|  | ||||
| //class name. Use something descriptive and leave the ": public Usermod" part :) | ||||
| class MyExampleUsermod : public Usermod { | ||||
|  | ||||
|   private: | ||||
|     //Private class members. You can declare variables and functions only accessible to your usermod here | ||||
|  | ||||
|     // Private class members. You can declare variables and functions only accessible to your usermod here | ||||
|     bool enabled = false; | ||||
|     bool initDone = false; | ||||
|     unsigned long lastTime = 0; | ||||
|  | ||||
|     // set your config variables to their boot default value (this can also be done in readFromConfig() or a constructor if you prefer) | ||||
| @@ -37,15 +41,56 @@ class MyExampleUsermod : public Usermod { | ||||
|     long testLong; | ||||
|     int8_t testPins[2]; | ||||
|  | ||||
|     // string that are used multiple time (this will save some flash memory) | ||||
|     static const char _name[]; | ||||
|     static const char _enabled[]; | ||||
|  | ||||
|  | ||||
|     // any private methods should go here (non-inline method should be defined out of class) | ||||
|     void publishMqtt(const char* state, bool retain = false); // example for publishing MQTT message | ||||
|  | ||||
|  | ||||
|   public: | ||||
|     //Functions called by WLED | ||||
|  | ||||
|     // non WLED related methods, may be used for data exchange between usermods (non-inline methods should be defined out of class) | ||||
|  | ||||
|     /** | ||||
|      * Enable/Disable the usermod | ||||
|      */ | ||||
|     inline void enable(bool enable) { enabled = enable; } | ||||
|  | ||||
|     /** | ||||
|      * Get usermod enabled/disabled state | ||||
|      */ | ||||
|     inline bool isEnabled() { return enabled; } | ||||
|  | ||||
|     // in such case add the following to another usermod: | ||||
|     //  in private vars: | ||||
|     //   #ifdef USERMOD_EXAMPLE | ||||
|     //   MyExampleUsermod* UM; | ||||
|     //   #endif | ||||
|     //  in setup() | ||||
|     //   #ifdef USERMOD_EXAMPLE | ||||
|     //   UM = (MyExampleUsermod*) usermods.lookup(USERMOD_ID_EXAMPLE); | ||||
|     //   #endif | ||||
|     //  somewhere in loop() or other member method | ||||
|     //   #ifdef USERMOD_EXAMPLE | ||||
|     //   if (UM != nullptr) isExampleEnabled = UM->isEnabled(); | ||||
|     //   if (!isExampleEnabled) UM->enable(true); | ||||
|     //   #endif | ||||
|  | ||||
|  | ||||
|     // methods called by WLED (can be inlined as they are called only once but if you call them explicitly define them out of class) | ||||
|  | ||||
|     /* | ||||
|      * setup() is called once at boot. WiFi is not yet connected at this point. | ||||
|      * readFromConfig() is called prior to setup() | ||||
|      * You can use it to initialize variables, sensors or similar. | ||||
|      */ | ||||
|     void setup() { | ||||
|       // do your set-up here | ||||
|       //Serial.println("Hello from my usermod!"); | ||||
|       initDone = true; | ||||
|     } | ||||
|  | ||||
|  | ||||
| @@ -69,6 +114,11 @@ class MyExampleUsermod : public Usermod { | ||||
|      *    Instead, use a timer check as shown here. | ||||
|      */ | ||||
|     void loop() { | ||||
|       // if usermod is disabled or called during strip updating just exit | ||||
|       // NOTE: on very long strips strip.isUpdating() may always return true so update accordingly | ||||
|       if (!enabled || strip.isUpdating()) return; | ||||
|  | ||||
|       // do your magic here | ||||
|       if (millis() - lastTime > 1000) { | ||||
|         //Serial.println("I'm alive!"); | ||||
|         lastTime = millis(); | ||||
| @@ -81,19 +131,25 @@ class MyExampleUsermod : public Usermod { | ||||
|      * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. | ||||
|      * Below it is shown how this could be used for e.g. a light sensor | ||||
|      */ | ||||
|     /* | ||||
|     void addToJsonInfo(JsonObject& root) | ||||
|     { | ||||
|       int reading = 20; | ||||
|       //this code adds "u":{"Light":[20," lux"]} to the info object | ||||
|       // if "u" object does not exist yet wee need to create it | ||||
|       JsonObject user = root["u"]; | ||||
|       if (user.isNull()) user = root.createNestedObject("u"); | ||||
|  | ||||
|       JsonArray lightArr = user.createNestedArray("Light"); //name | ||||
|       lightArr.add(reading); //value | ||||
|       lightArr.add(" lux"); //unit | ||||
|       //this code adds "u":{"ExampleUsermod":[20," lux"]} to the info object | ||||
|       //int reading = 20; | ||||
|       //JsonArray lightArr = user.createNestedArray(FPSTR(_name))); //name | ||||
|       //lightArr.add(reading); //value | ||||
|       //lightArr.add(F(" lux")); //unit | ||||
|  | ||||
|       // if you are implementing a sensor usermod, you may publish sensor data | ||||
|       //JsonObject sensor = root[F("sensor")]; | ||||
|       //if (sensor.isNull()) sensor = root.createNestedObject(F("sensor")); | ||||
|       //temp = sensor.createNestedArray(F("light")); | ||||
|       //temp.add(reading); | ||||
|       //temp.add(F("lux")); | ||||
|     } | ||||
|     */ | ||||
|  | ||||
|  | ||||
|     /* | ||||
| @@ -102,7 +158,12 @@ class MyExampleUsermod : public Usermod { | ||||
|      */ | ||||
|     void addToJsonState(JsonObject& root) | ||||
|     { | ||||
|       //root["user0"] = userVar0; | ||||
|       if (!initDone || !enabled) return;  // prevent crash on boot applyPreset() | ||||
|  | ||||
|       JsonObject usermod = root[FPSTR(_name)]; | ||||
|       if (usermod.isNull()) usermod = root.createNestedObject(FPSTR(_name)); | ||||
|  | ||||
|       //usermod["user0"] = userVar0; | ||||
|     } | ||||
|  | ||||
|  | ||||
| @@ -112,7 +173,14 @@ class MyExampleUsermod : public Usermod { | ||||
|      */ | ||||
|     void readFromJsonState(JsonObject& root) | ||||
|     { | ||||
|       userVar0 = root["user0"] | userVar0; //if "user0" key exists in JSON, update, else keep old value | ||||
|       if (!initDone) return;  // prevent crash on boot applyPreset() | ||||
|  | ||||
|       JsonObject usermod = root[FPSTR(_name)]; | ||||
|       if (!usermod.isNull()) { | ||||
|         // expect JSON usermod data in usermod name object: {"ExampleUsermod:{"user0":10}"} | ||||
|         userVar0 = usermod["user0"] | userVar0; //if "user0" key exists in JSON, update, else keep old value | ||||
|       } | ||||
|       // you can as well check WLED state JSON keys | ||||
|       //if (root["bri"] == 255) Serial.println(F("Don't burn down your garage!")); | ||||
|     } | ||||
|  | ||||
| @@ -154,8 +222,10 @@ class MyExampleUsermod : public Usermod { | ||||
|      */ | ||||
|     void addToConfig(JsonObject& root) | ||||
|     { | ||||
|       JsonObject top = root.createNestedObject("exampleUsermod"); | ||||
|       top["great"] = userVar0; //save these vars persistently whenever settings are saved | ||||
|       JsonObject top = root.createNestedObject(FPSTR(_name)); | ||||
|       top[FPSTR(_enabled)] = enabled; | ||||
|       //save these vars persistently whenever settings are saved | ||||
|       top["great"] = userVar0; | ||||
|       top["testBool"] = testBool; | ||||
|       top["testInt"] = testInt; | ||||
|       top["testLong"] = testLong; | ||||
| @@ -188,7 +258,7 @@ class MyExampleUsermod : public Usermod { | ||||
|       // default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor | ||||
|       // setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) | ||||
|  | ||||
|       JsonObject top = root["exampleUsermod"]; | ||||
|       JsonObject top = root[FPSTR(_name)]; | ||||
|  | ||||
|       bool configComplete = !top.isNull(); | ||||
|  | ||||
| @@ -201,6 +271,8 @@ class MyExampleUsermod : public Usermod { | ||||
|       // A 3-argument getJsonValue() assigns the 3rd argument as a default value if the Json value is missing | ||||
|       configComplete &= getJsonValue(top["testInt"], testInt, 42);   | ||||
|       configComplete &= getJsonValue(top["testLong"], testLong, -42424242); | ||||
|  | ||||
|       // "pin" fields have special handling in settings page (or some_pin as well) | ||||
|       configComplete &= getJsonValue(top["pin"][0], testPins[0], -1); | ||||
|       configComplete &= getJsonValue(top["pin"][1], testPins[1], -1); | ||||
|  | ||||
| @@ -208,6 +280,21 @@ class MyExampleUsermod : public Usermod { | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * appendConfigData() is called when user enters usermod settings page | ||||
|      * it may add additional metadata for certain entry fields (adding drop down is possible) | ||||
|      * be careful not to add too much as oappend() buffer is limited to 3k | ||||
|      */ | ||||
|     void appendConfigData() | ||||
|     { | ||||
|       oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":great")); oappend(SET_F("',1,'<i>(this is a great config value)</i>');")); | ||||
|       oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":testString")); oappend(SET_F("',1,'enter any string you want');")); | ||||
|       oappend(SET_F("dd=addDropdown('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F("','testInt');")); | ||||
|       oappend(SET_F("addOption(dd,'Nothing',0);")); | ||||
|       oappend(SET_F("addOption(dd,'Everything',42);")); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * handleOverlayDraw() is called just before every show() (LED strip update frame) after effects have set the colors. | ||||
|      * Use this to blank out some LEDs or set them to a different color regardless of the set effect mode. | ||||
| @@ -218,7 +305,72 @@ class MyExampleUsermod : public Usermod { | ||||
|       //strip.setPixelColor(0, RGBW32(0,0,0,0)) // set the first pixel to black | ||||
|     } | ||||
|  | ||||
|     | ||||
|  | ||||
|     /** | ||||
|      * handleButton() can be used to override default button behaviour. Returning true | ||||
|      * will prevent button working in a default way. | ||||
|      * Replicating button.cpp | ||||
|      */ | ||||
|     bool handleButton(uint8_t b) { | ||||
|       yield(); | ||||
|       // ignore certain button types as they may have other consequences | ||||
|       if (!enabled | ||||
|        || buttonType[b] == BTN_TYPE_NONE | ||||
|        || buttonType[b] == BTN_TYPE_RESERVED | ||||
|        || buttonType[b] == BTN_TYPE_PIR_SENSOR | ||||
|        || buttonType[b] == BTN_TYPE_ANALOG | ||||
|        || buttonType[b] == BTN_TYPE_ANALOG_INVERTED) { | ||||
|         return false; | ||||
|       } | ||||
|  | ||||
|       bool handled = false; | ||||
|       // do your button handling here | ||||
|       return handled; | ||||
|     } | ||||
|    | ||||
|  | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|     /** | ||||
|      * handling of MQTT message | ||||
|      * topic only contains stripped topic (part after /wled/MAC) | ||||
|      */ | ||||
|     bool onMqttMessage(char* topic, char* payload) { | ||||
|       // check if we received a command | ||||
|       //if (strlen(topic) == 8 && strncmp_P(topic, PSTR("/command"), 8) == 0) { | ||||
|       //  String action = payload; | ||||
|       //  if (action == "on") { | ||||
|       //    enabled = true; | ||||
|       //    return true; | ||||
|       //  } else if (action == "off") { | ||||
|       //    enabled = false; | ||||
|       //    return true; | ||||
|       //  } else if (action == "toggle") { | ||||
|       //    enabled = !enabled; | ||||
|       //    return true; | ||||
|       //  } | ||||
|       //} | ||||
|       return false; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * onMqttConnect() is called when MQTT connection is established | ||||
|      */ | ||||
|     void onMqttConnect(bool sessionPresent) { | ||||
|       // do any MQTT related initialisation here | ||||
|       //publishMqtt("I am alive!"); | ||||
|     } | ||||
| #endif | ||||
|  | ||||
|  | ||||
|     /** | ||||
|      * onStateChanged() is used to detect WLED state change | ||||
|      * @mode parameter is CALL_MODE_... parameter used for notifications | ||||
|      */ | ||||
|     void onStateChange(uint8_t mode) { | ||||
|       // do something if WLED state changed (color, brightness, effect, preset, etc) | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). | ||||
|      * This could be used in the future for the system to determine whether your usermod is installed. | ||||
| @@ -230,4 +382,25 @@ class MyExampleUsermod : public Usermod { | ||||
|  | ||||
|    //More methods can be added in the future, this example will then be extended. | ||||
|    //Your usermod will remain compatible as it does not need to implement all methods from the Usermod base class! | ||||
| }; | ||||
| }; | ||||
|  | ||||
|  | ||||
| // add more strings here to reduce flash memory usage | ||||
| const char MyExampleUsermod::_name[]    PROGMEM = "ExampleUsermod"; | ||||
| const char MyExampleUsermod::_enabled[] PROGMEM = "enabled"; | ||||
|  | ||||
|  | ||||
| // implementation of non-inline member methods | ||||
|  | ||||
| void MyExampleUsermod::publishMqtt(const char* state, bool retain) | ||||
| { | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|   //Check if MQTT Connected, otherwise it will crash the 8266 | ||||
|   if (WLED_MQTT_CONNECTED) { | ||||
|     char subuf[64]; | ||||
|     strcpy(subuf, mqttDeviceTopic); | ||||
|     strcat_P(subuf, PSTR("/example")); | ||||
|     mqtt->publish(subuf, 0, retain, state); | ||||
|   } | ||||
| #endif | ||||
| } | ||||
|   | ||||
| @@ -133,13 +133,13 @@ private: | ||||
|       return false; | ||||
|     } | ||||
|  | ||||
|     read32(bmpFS); // filesize in bytes | ||||
|     read32(bmpFS); // reserved | ||||
|     (void) read32(bmpFS); // filesize in bytes | ||||
|     (void) read32(bmpFS); // reserved | ||||
|     seekOffset = read32(bmpFS); // start of bitmap | ||||
|     headerSize = read32(bmpFS); // header size | ||||
|     w = read32(bmpFS); // width | ||||
|     h = read32(bmpFS); // height | ||||
|     read16(bmpFS); // color planes (must be 1) | ||||
|     (void) read16(bmpFS); // color planes (must be 1) | ||||
|     bitDepth = read16(bmpFS); | ||||
|  | ||||
|     if (read32(bmpFS) != 0 || (bitDepth != 24 && bitDepth != 1 && bitDepth != 4 && bitDepth != 8)) { | ||||
| @@ -151,9 +151,9 @@ private: | ||||
|     uint32_t palette[256]; | ||||
|     if (bitDepth <= 8) // 1,4,8 bit bitmap: read color palette | ||||
|     { | ||||
|       read32(bmpFS); read32(bmpFS); read32(bmpFS); // size, w resolution, h resolution | ||||
|       (void) read32(bmpFS); (void) read32(bmpFS); (void) read32(bmpFS); // size, w resolution, h resolution | ||||
|       paletteSize = read32(bmpFS); | ||||
|       if (paletteSize == 0) paletteSize = bitDepth * bitDepth; //if 0, size is 2^bitDepth | ||||
|       if (paletteSize == 0) paletteSize = 1 << bitDepth; //if 0, size is 2^bitDepth | ||||
|       bmpFS.seek(14 + headerSize); // start of color palette | ||||
|       for (uint16_t i = 0; i < paletteSize; i++) { | ||||
|         palette[i] = read32(bmpFS); | ||||
| @@ -198,7 +198,7 @@ private: | ||||
|           } | ||||
|           b = c; g = c >> 8; r = c >> 16; | ||||
|         } | ||||
|         if (dimming != 255) { // only dimm when needed | ||||
|         if (dimming != 255) { // only dim when needed | ||||
|           r *= dimming; g *= dimming; b *= dimming; | ||||
|           r  = r  >> 8; g  = g  >> 8; b  = b  >> 8; | ||||
|         } | ||||
|   | ||||
| @@ -1,3 +1,7 @@ | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #include "wled.h" | ||||
| #include <Arduino.h> | ||||
| #include <U8x8lib.h> // from https://github.com/olikraus/u8g2/ | ||||
| @@ -11,23 +15,23 @@ OneWire oneWire(13); | ||||
| DallasTemperature sensor(&oneWire); | ||||
| long temptimer = millis(); | ||||
| long lastMeasure = 0; | ||||
| #define Celsius // Show temperature mesaurement in Celcius otherwise is in Fahrenheit  | ||||
| #define Celsius // Show temperature measurement in Celsius otherwise is in Fahrenheit  | ||||
|  | ||||
| // If display does not work or looks corrupted check the | ||||
| // constructor reference: | ||||
| // https://github.com/olikraus/u8g2/wiki/u8x8setupcpp | ||||
| // or check the gallery: | ||||
| // https://github.com/olikraus/u8g2/wiki/gallery | ||||
| // --> First choise of cheap I2C OLED 128X32 0.91" | ||||
| // --> First choice of cheap I2C OLED 128X32 0.91" | ||||
| U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA | ||||
| // --> Second choise of cheap I2C OLED 128X64 0.96" or 1.3" | ||||
| // --> Second choice of cheap I2C OLED 128X64 0.96" or 1.3" | ||||
| //U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA | ||||
| // gets called once at boot. Do all initialization that doesn't depend on | ||||
| // network here | ||||
| void userSetup() { | ||||
|   sensor.begin(); //Start Dallas temperature sensor | ||||
|   u8x8.begin(); | ||||
|   //u8x8.setFlipMode(1); //Uncoment if using WLED Wemos shield  | ||||
|   //u8x8.setFlipMode(1); //Un-comment if using WLED Wemos shield  | ||||
|   u8x8.setPowerSave(0); | ||||
|   u8x8.setContrast(10); //Contrast setup will help to preserve OLED lifetime. In case OLED need to be brighter increase number up to 255 | ||||
|   u8x8.setFont(u8x8_font_chroma48medium8_r); | ||||
| @@ -67,7 +71,7 @@ void userLoop() { | ||||
|     if (mqtt != nullptr) | ||||
|     { | ||||
|       sensor.requestTemperatures(); | ||||
| //Gets prefered temperature scale based on selection in definitions section | ||||
| //Gets preferred temperature scale based on selection in definitions section | ||||
|       #ifdef Celsius | ||||
|       float board_temperature = sensor.getTempCByIndex(0); | ||||
|       #else | ||||
| @@ -134,11 +138,11 @@ void userLoop() { | ||||
|   // First row with Wifi name | ||||
|   u8x8.setCursor(1, 0); | ||||
|   u8x8.print(knownSsid.substring(0, u8x8.getCols() > 1 ? u8x8.getCols() - 2 : 0)); | ||||
|   // Print `~` char to indicate that SSID is longer, than owr dicplay | ||||
|   // Print `~` char to indicate that SSID is longer than our display | ||||
|   if (knownSsid.length() > u8x8.getCols()) | ||||
|     u8x8.print("~"); | ||||
|  | ||||
|   // Second row with IP or Psssword | ||||
|   // Second row with IP or Password | ||||
|   u8x8.setCursor(1, 1); | ||||
|   // Print password in AP mode and if led is OFF. | ||||
|   if (apActive && bri == 0) | ||||
|   | ||||
| @@ -1,3 +1,7 @@ | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #include "wled.h" | ||||
| #include <Arduino.h> | ||||
| #include <U8x8lib.h> // from https://github.com/olikraus/u8g2/ | ||||
| @@ -6,7 +10,7 @@ | ||||
|  | ||||
| void UpdateBME280Data(); | ||||
|  | ||||
| #define Celsius // Show temperature mesaurement in Celcius otherwise is in Fahrenheit  | ||||
| #define Celsius // Show temperature measurement in Celsius otherwise is in Fahrenheit  | ||||
| BME280I2C bme;    // Default : forced mode, standby time = 1000 ms | ||||
|                   // Oversampling = pressure ×1, temperature ×1, humidity ×1, filter off, | ||||
|  | ||||
| @@ -16,14 +20,14 @@ uint8_t SDA_PIN = 21; | ||||
| #else //ESP8266 boards | ||||
| uint8_t SCL_PIN = 5; | ||||
| uint8_t SDA_PIN = 4; | ||||
| // uint8_t RST_PIN = 16; // Uncoment for Heltec WiFi-Kit-8 | ||||
| // uint8_t RST_PIN = 16; // Un-comment for Heltec WiFi-Kit-8 | ||||
| #endif | ||||
|  | ||||
| //The SCL and SDA pins are defined here. | ||||
| //ESP8266 Wemos D1 mini board use SCL=5 SDA=4 while ESP32 Wemos32 mini board use SCL=22 SDA=21 | ||||
| #define U8X8_PIN_SCL SCL_PIN | ||||
| #define U8X8_PIN_SDA SDA_PIN | ||||
| //#define U8X8_PIN_RESET RST_PIN // Uncoment for Heltec WiFi-Kit-8 | ||||
| //#define U8X8_PIN_RESET RST_PIN // Un-comment for Heltec WiFi-Kit-8 | ||||
|  | ||||
| // If display does not work or looks corrupted check the | ||||
| // constructor reference: | ||||
| @@ -32,9 +36,9 @@ uint8_t SDA_PIN = 4; | ||||
| // https://github.com/olikraus/u8g2/wiki/gallery | ||||
| // --> First choise of cheap I2C OLED 128X32 0.91" | ||||
| U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA | ||||
| // --> Second choise of cheap I2C OLED 128X64 0.96" or 1.3" | ||||
| // --> Second choice of cheap I2C OLED 128X64 0.96" or 1.3" | ||||
| //U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA | ||||
| // --> Third choise of Heltec WiFi-Kit-8 OLED 128X32 0.91" | ||||
| // --> Third choice of Heltec WiFi-Kit-8 OLED 128X32 0.91" | ||||
| //U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_RESET, U8X8_PIN_SCL, U8X8_PIN_SDA); // Constructor for Heltec WiFi-Kit-8 | ||||
| // gets called once at boot. Do all initialization that doesn't depend on network here | ||||
|  | ||||
| @@ -177,11 +181,11 @@ void userLoop() { | ||||
|   // First row with Wifi name | ||||
|   u8x8.setCursor(1, 0); | ||||
|   u8x8.print(knownSsid.substring(0, u8x8.getCols() > 1 ? u8x8.getCols() - 2 : 0)); | ||||
|   // Print `~` char to indicate that SSID is longer, than owr dicplay | ||||
|   // Print `~` char to indicate that SSID is longer than our display | ||||
|   if (knownSsid.length() > u8x8.getCols()) | ||||
|     u8x8.print("~"); | ||||
|  | ||||
|   // Second row with IP or Psssword | ||||
|   // Second row with IP or Password | ||||
|   u8x8.setCursor(1, 1); | ||||
|   // Print password in AP mode and if led is OFF. | ||||
|   if (apActive && bri == 0) | ||||
|   | ||||
| @@ -2,7 +2,7 @@ | ||||
|  | ||||
| **Attention: This usermod compiles only for ESP8266** | ||||
|  | ||||
| This usermod-v2 modification performs a ping request to a local IP address every 60 seconds. This ensures WLED net services remain accessible in some problematic WLAN environments. | ||||
| This usermod-v2 modification performs a ping request to a local IP address every 60 seconds. This ensures WLED net services remain accessible in some problematic WiFi environments. | ||||
|  | ||||
| The modification works with static or DHCP IP address configuration. | ||||
|  | ||||
| @@ -24,7 +24,7 @@ The usermod supports the following state changes: | ||||
|  | ||||
| | JSON key    | Value range      | Description                     | | ||||
| |-------------|------------------|---------------------------------| | ||||
| | PingDelayMs | 5000 to 18000000 | Deactivdate/activate the sensor | | ||||
| | PingDelayMs | 5000 to 18000000 | Deactivate/activate the sensor  | | ||||
|  | ||||
|  Changes also persist after a reboot. | ||||
|  | ||||
|   | ||||
							
								
								
									
										17
									
								
								usermods/Internal_Temperature_v2/readme.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,17 @@ | ||||
| # Internal Temperature Usermod | ||||
| This usermod adds the temperature readout to the Info tab and also publishes that over the topic `mcutemp` topic. | ||||
|  | ||||
| ## Important | ||||
| A shown temp of 53,33°C might indicate that the internal temp is not supported. | ||||
|  | ||||
| ESP8266 does not have a internal temp sensor | ||||
|  | ||||
| ESP32S2 seems to crash on reading the sensor -> disabled | ||||
|  | ||||
| ## Installation | ||||
| Add a build flag `-D USERMOD_INTERNAL_TEMPERATURE` to your `platformio.ini` (or `platformio_override.ini`). | ||||
|  | ||||
| ## Authors | ||||
| Soeren Willrodt [@lost-hope](https://github.com/lost-hope) | ||||
|  | ||||
| Dimitry Zhemkov [@dima-zhemkov](https://github.com/dima-zhemkov) | ||||
							
								
								
									
										117
									
								
								usermods/Internal_Temperature_v2/usermod_internal_temperature.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,117 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
|  | ||||
| class InternalTemperatureUsermod : public Usermod | ||||
| { | ||||
|  | ||||
| private: | ||||
|   unsigned long loopInterval = 10000; | ||||
|   unsigned long lastTime = 0; | ||||
|   bool isEnabled = false; | ||||
|   float temperature = 0; | ||||
|  | ||||
|   static const char _name[]; | ||||
|   static const char _enabled[]; | ||||
|   static const char _loopInterval[]; | ||||
|  | ||||
|   // any private methods should go here (non-inline method should be defined out of class) | ||||
|   void publishMqtt(const char *state, bool retain = false); // example for publishing MQTT message | ||||
|  | ||||
| public: | ||||
|   void setup() | ||||
|   { | ||||
|   } | ||||
|  | ||||
|   void loop() | ||||
|   { | ||||
|     // if usermod is disabled or called during strip updating just exit | ||||
|     // NOTE: on very long strips strip.isUpdating() may always return true so update accordingly | ||||
|     if (!isEnabled || strip.isUpdating() || millis() - lastTime <= loopInterval) | ||||
|       return; | ||||
|  | ||||
|     lastTime = millis(); | ||||
|  | ||||
| #ifdef ESP8266 // ESP8266 | ||||
|     // does not seem possible | ||||
|     temperature = -1; | ||||
| #elif defined(CONFIG_IDF_TARGET_ESP32S2) // ESP32S2 | ||||
|     temperature = -1; | ||||
| #else                                    // ESP32 ESP32S3 and ESP32C3 | ||||
|     temperature = roundf(temperatureRead() * 10) / 10; | ||||
| #endif | ||||
|  | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|     if (WLED_MQTT_CONNECTED) | ||||
|     { | ||||
|       char array[10]; | ||||
|       snprintf(array, sizeof(array), "%f", temperature); | ||||
|       publishMqtt(array); | ||||
|     } | ||||
| #endif | ||||
|   } | ||||
|  | ||||
|   void addToJsonInfo(JsonObject &root) | ||||
|   { | ||||
|     if (!isEnabled) | ||||
|       return; | ||||
|  | ||||
|     // if "u" object does not exist yet wee need to create it | ||||
|     JsonObject user = root["u"]; | ||||
|     if (user.isNull()) | ||||
|       user = root.createNestedObject("u"); | ||||
|  | ||||
|     JsonArray userTempArr = user.createNestedArray(FPSTR(_name)); | ||||
|     userTempArr.add(temperature); | ||||
|     userTempArr.add(F(" °C")); | ||||
|  | ||||
|     // if "sensor" object does not exist yet wee need to create it | ||||
|     JsonObject sensor = root[F("sensor")]; | ||||
|     if (sensor.isNull()) | ||||
|       sensor = root.createNestedObject(F("sensor")); | ||||
|  | ||||
|     JsonArray sensorTempArr = sensor.createNestedArray(FPSTR(_name)); | ||||
|     sensorTempArr.add(temperature); | ||||
|     sensorTempArr.add(F("°C")); | ||||
|   } | ||||
|  | ||||
|   void addToConfig(JsonObject &root) | ||||
|   { | ||||
|     JsonObject top = root.createNestedObject(FPSTR(_name)); | ||||
|     top[FPSTR(_enabled)] = isEnabled; | ||||
|     top[FPSTR(_loopInterval)] = loopInterval; | ||||
|   } | ||||
|  | ||||
|   bool readFromConfig(JsonObject &root) | ||||
|   { | ||||
|     JsonObject top = root[FPSTR(_name)]; | ||||
|     bool configComplete = !top.isNull(); | ||||
|     configComplete &= getJsonValue(top[FPSTR(_enabled)], isEnabled); | ||||
|     configComplete &= getJsonValue(top[FPSTR(_loopInterval)], loopInterval); | ||||
|  | ||||
|     return configComplete; | ||||
|   } | ||||
|  | ||||
|   uint16_t getId() | ||||
|   { | ||||
|     return USERMOD_ID_INTERNAL_TEMPERATURE; | ||||
|   } | ||||
| }; | ||||
|  | ||||
| const char InternalTemperatureUsermod::_name[] PROGMEM = "Internal Temperature"; | ||||
| const char InternalTemperatureUsermod::_enabled[] PROGMEM = "Enabled"; | ||||
| const char InternalTemperatureUsermod::_loopInterval[] PROGMEM = "Loop Interval"; | ||||
|  | ||||
| void InternalTemperatureUsermod::publishMqtt(const char *state, bool retain) | ||||
| { | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|   // Check if MQTT Connected, otherwise it will crash the 8266 | ||||
|   if (WLED_MQTT_CONNECTED) | ||||
|   { | ||||
|     char subuf[64]; | ||||
|     strcpy(subuf, mqttDeviceTopic); | ||||
|     strcat_P(subuf, PSTR("/mcutemp")); | ||||
|     mqtt->publish(subuf, 0, retain, state); | ||||
|   } | ||||
| #endif | ||||
| } | ||||
							
								
								
									
										26
									
								
								usermods/LDR_Dusk_Dawn_v2/README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,26 @@ | ||||
| # LDR_Dusk_Dawn_v2 | ||||
| This usermod will obtain readings from a Light Dependent Resistor (LDR) and will turn on/off specific presets based on those readings. This is useful for exterior lighting situations where you want the lights to only be on when it is dark out. | ||||
|  | ||||
| # Installation | ||||
| Add "-D USERMOD_LDR_DUSK_DAWN" to your platformio.ini [common] build_flags and build. | ||||
|  | ||||
| Example: | ||||
| ``` | ||||
| [common] | ||||
| build_flags = | ||||
|   -D USERMOD_LDR_DUSK_DAWN   # Enable LDR Dusk Dawn Usermod | ||||
| ``` | ||||
|  | ||||
| # Usermod Settings | ||||
| Setting | Description | Default | ||||
| --- | --- | --- | ||||
| Enabled | Enable/Disable the LDR functionality. | Disabled | ||||
| LDR Pin | The analog capable pin your LDR is connected to. | 34 | ||||
| Threshold Minutes | The number of minutes of consistent readings above/below the on/off threshold before the LED state will change. | 5 | ||||
| Threshold | The analog read value threshold from the LDR. Readings lower than this number will count towards changing the LED state to off. You can see the current LDR reading by going into the info section when LDR functionality is enabled. | 1000 | ||||
| On Preset | The WLED preset to be used for the LED on state. | 1 | ||||
| Off Preset | The WLED preset to be used for the LED off state. | 2 | ||||
|  | ||||
| ## Author | ||||
| [@jeffwdh](https://github.com/jeffwdh)   | ||||
| jeffwdh@tarball.ca | ||||
							
								
								
									
										153
									
								
								usermods/LDR_Dusk_Dawn_v2/usermod_LDR_Dusk_Dawn_v2.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,153 @@ | ||||
| #pragma once | ||||
| #include "wled.h" | ||||
|  | ||||
| #ifndef ARDUINO_ARCH_ESP32 | ||||
|   // 8266 does not support analogRead on user selectable pins  | ||||
|   #error only ESP32 is supported by usermod LDR_DUSK_DAWN | ||||
| #endif | ||||
|  | ||||
| class LDR_Dusk_Dawn_v2 : public Usermod { | ||||
|   private: | ||||
|     // Defaults | ||||
|     bool ldrEnabled = false; | ||||
|     int ldrPin = 34; //A2 on Adafruit Huzzah32 | ||||
|     int ldrThresholdMinutes = 5; // How many minutes of readings above/below threshold until it switches LED state | ||||
|     int ldrThreshold = 1000; // Readings higher than this number will turn off LED.  | ||||
|     int ldrOnPreset = 1; // Default "On" Preset | ||||
|     int ldrOffPreset = 2; // Default "Off" Preset | ||||
|  | ||||
|     // Variables | ||||
|     bool initDone = false; | ||||
|     bool ldrEnabledPreviously = false; // Was LDR enabled for the previous check? First check is always no. | ||||
|     int ldrOffCount; // Number of readings above the threshold | ||||
|     int ldrOnCount; // Number of readings below the threshold | ||||
|     int ldrReading = 0; // Last LDR reading | ||||
|     int ldrLEDState; // Current LED on/off state | ||||
|     unsigned long lastMillis = 0; | ||||
|     static const char _name[]; | ||||
|  | ||||
|   public: | ||||
|     void setup() { | ||||
|       // register ldrPin | ||||
|       if ((ldrPin >= 0) && (digitalPinToAnalogChannel(ldrPin) >= 0)) { | ||||
|         if(!pinManager.allocatePin(ldrPin, false, PinOwner::UM_LDR_DUSK_DAWN)) ldrEnabled = false; // pin already in use -> disable usermod | ||||
|         else pinMode(ldrPin, INPUT);                                                               // alloc success -> configure pin for input | ||||
|       } else ldrEnabled = false;                                                                   // invalid pin -> disable usermod | ||||
|       initDone = true; | ||||
|     } | ||||
|  | ||||
|     void loop() { | ||||
|       // Only update every 10 seconds | ||||
|       if (millis() - lastMillis > 10000) {       | ||||
|         if (  (ldrEnabled == true) | ||||
|            && (ldrPin >= 0) && (digitalPinToAnalogChannel(ldrPin) >= 0) ) { // make sure that pin is valid for analogread() | ||||
|           // Default state is off | ||||
|           if (ldrEnabledPreviously == false) { | ||||
|               applyPreset(ldrOffPreset); | ||||
|               ldrEnabledPreviously = true; | ||||
|               ldrLEDState = 0; | ||||
|           } | ||||
|  | ||||
|           // Get LDR reading and increment counter by number of seconds since last read | ||||
|           ldrReading = analogRead(ldrPin); | ||||
|           if (ldrReading <= ldrThreshold) { | ||||
|             ldrOnCount = ldrOnCount + 10; | ||||
|             ldrOffCount = 0; | ||||
|           } else { | ||||
|             ldrOffCount = ldrOffCount + 10; | ||||
|             ldrOnCount = 0; | ||||
|           } | ||||
|  | ||||
|           if (ldrOnCount >= (ldrThresholdMinutes * 60)) { | ||||
|             ldrOnCount = 0; | ||||
|             // If LEDs were previously off, turn on | ||||
|             if (ldrLEDState == 0) { | ||||
|               applyPreset(ldrOnPreset); | ||||
|               ldrLEDState = 1; | ||||
|             } | ||||
|           } | ||||
|  | ||||
|           if (ldrOffCount >= (ldrThresholdMinutes * 60)) { | ||||
|             ldrOffCount = 0; | ||||
|             // If LEDs were previously on, turn off | ||||
|             if (ldrLEDState == 1) { | ||||
|               applyPreset(ldrOffPreset); | ||||
|               ldrLEDState = 0; | ||||
|             } | ||||
|           } | ||||
|         } else { | ||||
|           // LDR is disabled, reset variables to default | ||||
|           ldrReading = 0; | ||||
|           ldrOnCount = 0; | ||||
|           ldrOffCount = 0; | ||||
|           ldrLEDState = 0; | ||||
|           ldrEnabledPreviously = false; | ||||
|         } | ||||
|         lastMillis = millis(); | ||||
|       } | ||||
|     } | ||||
|  | ||||
|   void addToConfig(JsonObject& root) { | ||||
|       JsonObject top = root.createNestedObject(FPSTR(_name)); | ||||
|       top["Enabled"] = ldrEnabled; | ||||
|       top["LDR Pin"] = ldrPin; | ||||
|       top["Threshold Minutes"] = ldrThresholdMinutes; | ||||
|       top["Threshold"] = ldrThreshold; | ||||
|       top["On Preset"] = ldrOnPreset; | ||||
|       top["Off Preset"] = ldrOffPreset; | ||||
|   } | ||||
|  | ||||
|   bool readFromConfig(JsonObject& root) { | ||||
|       int8_t oldLdrPin = ldrPin; | ||||
|       JsonObject top = root[FPSTR(_name)]; | ||||
|       bool configComplete = !top.isNull(); | ||||
|       configComplete &= getJsonValue(top["Enabled"], ldrEnabled); | ||||
|       configComplete &= getJsonValue(top["LDR Pin"], ldrPin); | ||||
|       configComplete &= getJsonValue(top["Threshold Minutes"], ldrThresholdMinutes); | ||||
|       configComplete &= getJsonValue(top["Threshold"], ldrThreshold); | ||||
|       configComplete &= getJsonValue(top["On Preset"], ldrOnPreset); | ||||
|       configComplete &= getJsonValue(top["Off Preset"], ldrOffPreset); | ||||
|  | ||||
|       if (initDone && (ldrPin != oldLdrPin)) { | ||||
|          // pin changed - un-register previous pin, register new pin | ||||
|         if (oldLdrPin >= 0) pinManager.deallocatePin(oldLdrPin, PinOwner::UM_LDR_DUSK_DAWN); | ||||
|         setup();             // setup new pin | ||||
|       } | ||||
|       return configComplete; | ||||
|   } | ||||
|  | ||||
|   void addToJsonInfo(JsonObject& root) { | ||||
|       // If "u" object does not exist yet we need to create it | ||||
|       JsonObject user = root["u"]; | ||||
|       if (user.isNull()) user = root.createNestedObject("u"); | ||||
|  | ||||
|       JsonArray LDR_Enabled = user.createNestedArray("LDR dusk/dawn enabled"); | ||||
|       LDR_Enabled.add(ldrEnabled); | ||||
|       if (!ldrEnabled) return; // do not add more if usermod is disabled | ||||
|  | ||||
|       JsonArray LDR_Reading = user.createNestedArray("LDR reading"); | ||||
|       LDR_Reading.add(ldrReading); | ||||
|  | ||||
|       JsonArray LDR_State = user.createNestedArray("LDR turned LEDs on"); | ||||
|       LDR_State.add(bool(ldrLEDState)); | ||||
|  | ||||
|       // Optional debug information: | ||||
|       //JsonArray LDR_On_Count = user.createNestedArray("LDR on count"); | ||||
|       //LDR_On_Count.add(ldrOnCount); | ||||
|  | ||||
|       //JsonArray LDR_Off_Count = user.createNestedArray("LDR off count"); | ||||
|       //LDR_Off_Count.add(ldrOffCount); | ||||
|  | ||||
|       //bool pinValid = ((ldrPin >= 0) && (digitalPinToAnalogChannel(ldrPin) >= 0)); | ||||
|       //if (pinManager.getPinOwner(ldrPin) != PinOwner::UM_LDR_DUSK_DAWN) pinValid = false; | ||||
|       //JsonArray LDR_valid = user.createNestedArray(F("LDR pin")); | ||||
|       //LDR_valid.add(ldrPin); | ||||
|       //LDR_valid.add(pinValid ? F(" OK"): F(" invalid")); | ||||
|   } | ||||
|  | ||||
|   uint16_t getId() { | ||||
|     return USERMOD_ID_LDR_DUSK_DAWN; | ||||
|   } | ||||
| }; | ||||
|  | ||||
| const char LDR_Dusk_Dawn_v2::_name[]    PROGMEM = "LDR_Dusk_Dawn_v2"; | ||||
| @@ -23,7 +23,7 @@ You can also use usermod's off timer instead of sensor's. In such case rotate th | ||||
|  | ||||
| ## Usermod installation | ||||
|  | ||||
| **NOTE:** Usermod has been included in master branch of WLED so it can be compiled in directly just by defining `-D USERMOD_PIRSWITCH` and optionaly `-D PIR_SENSOR_PIN=16` to override default pin. You can also change the default off time by adding `-D PIR_SENSOR_OFF_SEC=30`. | ||||
| **NOTE:** Usermod has been included in master branch of WLED so it can be compiled in directly just by defining `-D USERMOD_PIRSWITCH` and optionally `-D PIR_SENSOR_PIN=16` to override default pin. You can also change the default off time by adding `-D PIR_SENSOR_OFF_SEC=30`. | ||||
|  | ||||
| ## API to enable/disable the PIR sensor from outside. For example from another usermod: | ||||
|  | ||||
| @@ -31,7 +31,7 @@ To query or change the PIR sensor state the methods `bool PIRsensorEnabled()` an | ||||
|  | ||||
| When the PIR sensor state changes an MQTT message is broadcasted with topic `wled/deviceMAC/motion` and message `on` or `off`. | ||||
| Usermod can also be configured to send just the MQTT message but not change WLED state using settings page as well as responding to motion only at night | ||||
| (assuming NTP and lattitude/longitude are set to determine sunrise/sunset times). | ||||
| (assuming NTP and latitude/longitude are set to determine sunrise/sunset times). | ||||
|  | ||||
| ### There are two options to get access to the usermod instance: | ||||
|  | ||||
| @@ -85,7 +85,7 @@ Have fun - @gegu & @blazoncek | ||||
|  | ||||
| 2021-11 | ||||
| * Added information about dynamic configuration options | ||||
| * Added option to temporary enable/disble usermod from WLED UI (Info dialog) | ||||
| * Added option to temporary enable/disable usermod from WLED UI (Info dialog) | ||||
|  | ||||
| 2022-11 | ||||
| * Added compile time option for off timer. | ||||
|   | ||||
| @@ -20,7 +20,7 @@ | ||||
|  * This usermod handles PIR sensor states. | ||||
|  * The strip will be switched on and the off timer will be resetted when the sensor goes HIGH.  | ||||
|  * When the sensor state goes LOW, the off timer is started and when it expires, the strip is switched off.  | ||||
|  *  | ||||
|  * Maintained by: @blazoncek | ||||
|  *  | ||||
|  * Usermods allow you to add own functionality to WLED more easily | ||||
|  * See: https://github.com/Aircoookie/WLED/wiki/Add-own-functionality | ||||
| @@ -38,21 +38,21 @@ public: | ||||
|   ~PIRsensorSwitch() {} | ||||
|  | ||||
|   //Enable/Disable the PIR sensor | ||||
|   void EnablePIRsensor(bool en) { enabled = en; } | ||||
|   inline void EnablePIRsensor(bool en) { enabled = en; } | ||||
|    | ||||
|   // Get PIR sensor enabled/disabled state | ||||
|   bool PIRsensorEnabled() { return enabled; } | ||||
|   inline bool PIRsensorEnabled() { return enabled; } | ||||
|  | ||||
| private: | ||||
|  | ||||
|   byte prevPreset   = 0; | ||||
|   byte prevPlaylist = 0; | ||||
|  | ||||
|   uint32_t offTimerStart = 0;                   // off timer start time | ||||
|   volatile unsigned long offTimerStart = 0;     // off timer start time | ||||
|   volatile bool PIRtriggered           = false; // did PIR trigger? | ||||
|   byte NotifyUpdateMode  = CALL_MODE_NO_NOTIFY; // notification mode for stateUpdated(): CALL_MODE_NO_NOTIFY or CALL_MODE_DIRECT_CHANGE | ||||
|   byte sensorPinState    = LOW;                 // current PIR sensor pin state | ||||
|   bool initDone          = false;               // status of initialization | ||||
|   bool PIRtriggered      = false; | ||||
|   unsigned long lastLoop = 0; | ||||
|  | ||||
|   // configurable parameters | ||||
| @@ -66,6 +66,7 @@ private: | ||||
|   // flag to enable triggering only if WLED is initially off (LEDs are not on, preventing running effect being overwritten by PIR) | ||||
|   bool m_offOnly            = false; | ||||
|   bool m_offMode            = offMode; | ||||
|   bool m_override           = false; | ||||
|  | ||||
|   // Home Assistant | ||||
|   bool HomeAssistantDiscovery = false;        // is HA discovery turned on | ||||
| @@ -81,168 +82,33 @@ private: | ||||
|   static const char _offOnly[]; | ||||
|   static const char _haDiscovery[]; | ||||
|   static const char _notify[]; | ||||
|   static const char _override[]; | ||||
|  | ||||
|   /** | ||||
|    * check if it is daytime | ||||
|    * if sunrise/sunset is not defined (no NTP or lat/lon) default to nighttime | ||||
|    */ | ||||
|   bool isDayTime() { | ||||
|     updateLocalTime(); | ||||
|     uint8_t hr = hour(localTime); | ||||
|     uint8_t mi = minute(localTime); | ||||
|  | ||||
|     if (sunrise && sunset) { | ||||
|       if (hour(sunrise)<hr && hour(sunset)>hr) { | ||||
|         return true; | ||||
|       } else { | ||||
|         if (hour(sunrise)==hr && minute(sunrise)<mi) { | ||||
|           return true; | ||||
|         } | ||||
|         if (hour(sunset)==hr && minute(sunset)>mi) { | ||||
|           return true; | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|     return false; | ||||
|   } | ||||
|   static bool isDayTime(); | ||||
|  | ||||
|   /** | ||||
|    * switch strip on/off | ||||
|    */ | ||||
|   void switchStrip(bool switchOn) | ||||
|   { | ||||
|     if (m_offOnly && bri && (switchOn || (!PIRtriggered && !switchOn))) return; //if lights on and off only, do nothing | ||||
|     if (PIRtriggered && switchOn) return; //if already on and triggered before, do nothing | ||||
|     PIRtriggered = switchOn; | ||||
|     if (switchOn) { | ||||
|       if (m_onPreset) { | ||||
|         if (currentPlaylist>0 && !offMode) { | ||||
|           prevPlaylist = currentPlaylist; | ||||
|           unloadPlaylist(); | ||||
|         } else if (currentPreset>0 && !offMode) { | ||||
|           prevPreset   = currentPreset; | ||||
|         } else { | ||||
|           saveTemporaryPreset(); | ||||
|           prevPlaylist = 0; | ||||
|           prevPreset   = 255; | ||||
|         } | ||||
|         applyPreset(m_onPreset, NotifyUpdateMode); | ||||
|         return; | ||||
|       } | ||||
|       // preset not assigned | ||||
|       if (bri == 0) { | ||||
|         bri = briLast; | ||||
|         stateUpdated(NotifyUpdateMode); | ||||
|       } | ||||
|     } else { | ||||
|       if (m_offPreset) { | ||||
|         if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(m_offPreset, NotifyUpdateMode); | ||||
|         return; | ||||
|       } else if (prevPlaylist) { | ||||
|         if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(prevPlaylist, NotifyUpdateMode); | ||||
|         prevPlaylist = 0; | ||||
|         return; | ||||
|       } else if (prevPreset) { | ||||
|         if (prevPreset<255) { if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(prevPreset, NotifyUpdateMode); } | ||||
|         else                { if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyTemporaryPreset(); } | ||||
|         prevPreset = 0; | ||||
|         return; | ||||
|       } | ||||
|       // preset not assigned | ||||
|       if (bri != 0) { | ||||
|         briLast = bri; | ||||
|         bri = 0; | ||||
|         stateUpdated(NotifyUpdateMode); | ||||
|       } | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   void publishMqtt(const char* state) | ||||
|   { | ||||
|     //Check if MQTT Connected, otherwise it will crash the 8266 | ||||
|     if (WLED_MQTT_CONNECTED) { | ||||
|       char subuf[64]; | ||||
|       strcpy(subuf, mqttDeviceTopic); | ||||
|       strcat_P(subuf, PSTR("/motion")); | ||||
|       mqtt->publish(subuf, 0, false, state); | ||||
|     } | ||||
|   } | ||||
|   void switchStrip(bool switchOn); | ||||
|   void publishMqtt(const char* state); | ||||
|  | ||||
|   // Create an MQTT Binary Sensor for Home Assistant Discovery purposes, this includes a pointer to the topic that is published to in the Loop. | ||||
|   void publishHomeAssistantAutodiscovery() | ||||
|   { | ||||
|     if (WLED_MQTT_CONNECTED) { | ||||
|       StaticJsonDocument<600> doc; | ||||
|       char uid[24], json_str[1024], buf[128]; | ||||
|  | ||||
|       sprintf_P(buf, PSTR("%s Motion"), serverDescription); //max length: 33 + 7 = 40 | ||||
|       doc[F("name")] = buf; | ||||
|       sprintf_P(buf, PSTR("%s/motion"), mqttDeviceTopic);   //max length: 33 + 7 = 40 | ||||
|       doc[F("stat_t")] = buf; | ||||
|       doc[F("pl_on")]  = "on"; | ||||
|       doc[F("pl_off")] = "off"; | ||||
|       sprintf_P(uid, PSTR("%s_motion"), escapedMac.c_str()); | ||||
|       doc[F("uniq_id")] = uid; | ||||
|       doc[F("dev_cla")] = F("motion"); | ||||
|       doc[F("exp_aft")] = 1800; | ||||
|  | ||||
|       JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device | ||||
|       device[F("name")] = serverDescription; | ||||
|       device[F("ids")]  = String(F("wled-sensor-")) + mqttClientID; | ||||
|       device[F("mf")]   = "WLED"; | ||||
|       device[F("mdl")]  = F("FOSS"); | ||||
|       device[F("sw")]   = versionString; | ||||
|        | ||||
|       sprintf_P(buf, PSTR("homeassistant/binary_sensor/%s/config"), uid); | ||||
|       DEBUG_PRINTLN(buf); | ||||
|       size_t payload_size = serializeJson(doc, json_str); | ||||
|       DEBUG_PRINTLN(json_str); | ||||
|  | ||||
|       mqtt->publish(buf, 0, true, json_str, payload_size); // do we really need to retain? | ||||
|     } | ||||
|   } | ||||
|   void publishHomeAssistantAutodiscovery(); | ||||
|  | ||||
|   /** | ||||
|    * Read and update PIR sensor state. | ||||
|    * Initilize/reset switch off timer | ||||
|    * Initialize/reset switch off timer | ||||
|    */ | ||||
|   bool updatePIRsensorState() | ||||
|   { | ||||
|     bool pinState = digitalRead(PIRsensorPin); | ||||
|     if (pinState != sensorPinState) { | ||||
|       sensorPinState = pinState; // change previous state | ||||
|  | ||||
|       if (sensorPinState == HIGH) { | ||||
|         offTimerStart = 0; | ||||
|         if (!m_mqttOnly && (!m_nightTimeOnly || (m_nightTimeOnly && !isDayTime()))) switchStrip(true); | ||||
|         else if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); | ||||
|         publishMqtt("on"); | ||||
|       } else { | ||||
|         // start switch off timer | ||||
|         offTimerStart = millis(); | ||||
|         if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); | ||||
|       } | ||||
|       return true; | ||||
|     } | ||||
|     return false; | ||||
|   } | ||||
|   bool updatePIRsensorState(); | ||||
|  | ||||
|   /** | ||||
|    * switch off the strip if the delay has elapsed  | ||||
|    */ | ||||
|   bool handleOffTimer() | ||||
|   { | ||||
|     if (offTimerStart > 0 && millis() - offTimerStart > m_switchOffDelay) { | ||||
|       offTimerStart = 0; | ||||
|       if (enabled == true) { | ||||
|         if (!m_mqttOnly && (!m_nightTimeOnly || (m_nightTimeOnly && !isDayTime()) || PIRtriggered)) switchStrip(false); | ||||
|         else if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); | ||||
|         publishMqtt("off"); | ||||
|       } | ||||
|       return true; | ||||
|     } | ||||
|     return false; | ||||
|   } | ||||
|   bool handleOffTimer(); | ||||
|  | ||||
| public: | ||||
|   //Functions called by WLED | ||||
| @@ -251,172 +117,57 @@ public: | ||||
|    * setup() is called once at boot. WiFi is not yet connected at this point. | ||||
|    * You can use it to initialize variables, sensors or similar. | ||||
|    */ | ||||
|   void setup() | ||||
|   { | ||||
|     if (enabled) { | ||||
|       // pin retrieved from cfg.json (readFromConfig()) prior to running setup() | ||||
|       if (PIRsensorPin >= 0 && pinManager.allocatePin(PIRsensorPin, false, PinOwner::UM_PIR)) { | ||||
|         // PIR Sensor mode INPUT_PULLUP | ||||
|         pinMode(PIRsensorPin, INPUT_PULLUP); | ||||
|         sensorPinState = digitalRead(PIRsensorPin); | ||||
|       } else { | ||||
|         if (PIRsensorPin >= 0) { | ||||
|           DEBUG_PRINTLN(F("PIRSensorSwitch pin allocation failed.")); | ||||
|         } | ||||
|         PIRsensorPin = -1;  // allocation failed | ||||
|         enabled = false; | ||||
|       } | ||||
|     } | ||||
|     initDone = true; | ||||
|   } | ||||
|   void setup(); | ||||
|  | ||||
|   /** | ||||
|    * connected() is called every time the WiFi is (re)connected | ||||
|    * Use it to initialize network interfaces | ||||
|    */ | ||||
|   void connected() | ||||
|   { | ||||
|   } | ||||
|   //void connected(); | ||||
|  | ||||
|   /** | ||||
|    * onMqttConnect() is called when MQTT connection is established | ||||
|    */ | ||||
|   void onMqttConnect(bool sessionPresent) { | ||||
|     if (HomeAssistantDiscovery) { | ||||
|       publishHomeAssistantAutodiscovery(); | ||||
|     } | ||||
|   } | ||||
|   void onMqttConnect(bool sessionPresent); | ||||
|  | ||||
|   /** | ||||
|    * loop() is called continuously. Here you can check for events, read sensors, etc. | ||||
|    */ | ||||
|   void loop() | ||||
|   { | ||||
|     // only check sensors 4x/s | ||||
|     if (!enabled || millis() - lastLoop < 250 || strip.isUpdating()) return; | ||||
|     lastLoop = millis(); | ||||
|  | ||||
|     if (!updatePIRsensorState()) { | ||||
|       handleOffTimer(); | ||||
|     } | ||||
|   } | ||||
|   void loop(); | ||||
|  | ||||
|   /** | ||||
|    * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. | ||||
|    *  | ||||
|    * Add PIR sensor state and switch off timer duration to jsoninfo | ||||
|    */ | ||||
|   void addToJsonInfo(JsonObject &root) | ||||
|   { | ||||
|     JsonObject user = root["u"]; | ||||
|     if (user.isNull()) user = root.createNestedObject("u"); | ||||
|   void addToJsonInfo(JsonObject &root); | ||||
|  | ||||
|     JsonArray infoArr = user.createNestedArray(FPSTR(_name)); | ||||
|  | ||||
|     String uiDomString; | ||||
|     if (enabled) { | ||||
|       if (offTimerStart > 0) | ||||
|       { | ||||
|         uiDomString = ""; | ||||
|         unsigned int offSeconds = (m_switchOffDelay - (millis() - offTimerStart)) / 1000; | ||||
|         if (offSeconds >= 3600) | ||||
|         { | ||||
|           uiDomString += (offSeconds / 3600); | ||||
|           uiDomString += F("h "); | ||||
|           offSeconds %= 3600; | ||||
|         } | ||||
|         if (offSeconds >= 60) | ||||
|         { | ||||
|           uiDomString += (offSeconds / 60); | ||||
|           offSeconds %= 60; | ||||
|         } | ||||
|         else if (uiDomString.length() > 0) | ||||
|         { | ||||
|           uiDomString += 0; | ||||
|         } | ||||
|         if (uiDomString.length() > 0) | ||||
|         { | ||||
|           uiDomString += F("min "); | ||||
|         } | ||||
|         uiDomString += (offSeconds); | ||||
|         infoArr.add(uiDomString + F("s")); | ||||
|       } else { | ||||
|         infoArr.add(sensorPinState ? F("sensor on") : F("inactive")); | ||||
|       } | ||||
|     } else { | ||||
|       infoArr.add(F("disabled")); | ||||
|     } | ||||
|  | ||||
|     uiDomString  = F(" <button class=\"btn btn-xs\" onclick=\"requestJson({"); | ||||
|     uiDomString += FPSTR(_name); | ||||
|     uiDomString += F(":{"); | ||||
|     uiDomString += FPSTR(_enabled); | ||||
|     if (enabled) { | ||||
|       uiDomString += F(":false}});\">"); | ||||
|       uiDomString += F("<i class=\"icons on\"></i>"); | ||||
|     } else { | ||||
|       uiDomString += F(":true}});\">"); | ||||
|       uiDomString += F("<i class=\"icons off\"></i>"); | ||||
|     } | ||||
|     uiDomString += F("</button>"); | ||||
|     infoArr.add(uiDomString); | ||||
|  | ||||
|     JsonObject sensor = root[F("sensor")]; | ||||
|     if (sensor.isNull()) sensor = root.createNestedObject(F("sensor")); | ||||
|     sensor[F("motion")] = sensorPinState || offTimerStart>0 ? true : false; | ||||
|   } | ||||
|   /** | ||||
|    * onStateChanged() is used to detect WLED state change | ||||
|    */ | ||||
|   void onStateChange(uint8_t mode); | ||||
|  | ||||
|   /** | ||||
|    * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). | ||||
|    * Values in the state object may be modified by connected clients | ||||
|    */ | ||||
| /* | ||||
|   void addToJsonState(JsonObject &root) | ||||
|   { | ||||
|   } | ||||
| */ | ||||
|   //void addToJsonState(JsonObject &root); | ||||
|  | ||||
|   /** | ||||
|    * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). | ||||
|    * Values in the state object may be modified by connected clients | ||||
|    */ | ||||
|  | ||||
|   void readFromJsonState(JsonObject &root) | ||||
|   { | ||||
|     if (!initDone) return;  // prevent crash on boot applyPreset() | ||||
|     JsonObject usermod = root[FPSTR(_name)]; | ||||
|     if (!usermod.isNull()) { | ||||
|       if (usermod[FPSTR(_enabled)].is<bool>()) { | ||||
|         enabled = usermod[FPSTR(_enabled)].as<bool>(); | ||||
|       } | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   void readFromJsonState(JsonObject &root); | ||||
|  | ||||
|   /** | ||||
|    * provide the changeable values | ||||
|    */ | ||||
|   void addToConfig(JsonObject &root) | ||||
|   { | ||||
|     JsonObject top = root.createNestedObject(FPSTR(_name)); | ||||
|     top[FPSTR(_enabled)]        = enabled; | ||||
|     top[FPSTR(_switchOffDelay)] = m_switchOffDelay / 1000; | ||||
|     top["pin"]                  = PIRsensorPin; | ||||
|     top[FPSTR(_onPreset)]       = m_onPreset; | ||||
|     top[FPSTR(_offPreset)]      = m_offPreset; | ||||
|     top[FPSTR(_nightTime)]      = m_nightTimeOnly; | ||||
|     top[FPSTR(_mqttOnly)]       = m_mqttOnly; | ||||
|     top[FPSTR(_offOnly)]        = m_offOnly; | ||||
|     top[FPSTR(_haDiscovery)]    = HomeAssistantDiscovery; | ||||
|     top[FPSTR(_notify)]         = (NotifyUpdateMode != CALL_MODE_NO_NOTIFY); | ||||
|     DEBUG_PRINTLN(F("PIR config saved.")); | ||||
|   } | ||||
|   void addToConfig(JsonObject &root); | ||||
|  | ||||
|   void appendConfigData() | ||||
|   { | ||||
|     oappend(SET_F("addInfo('PIRsensorSwitch:HA-discovery',1,'HA=Home Assistant');"));     // 0 is field type, 1 is actual field | ||||
|     oappend(SET_F("addInfo('PIRsensorSwitch:notifications',1,'Periodic WS updates');"));  // 0 is field type, 1 is actual field | ||||
|   } | ||||
|   /** | ||||
|    * provide UI information and allow extending UI options | ||||
|    */ | ||||
|   void appendConfigData(); | ||||
|  | ||||
|   /** | ||||
|    * restore the changeable values | ||||
| @@ -424,72 +175,13 @@ public: | ||||
|    * | ||||
|    * The function should return true if configuration was successfully loaded or false if there was no configuration. | ||||
|    */ | ||||
|   bool readFromConfig(JsonObject &root) | ||||
|   { | ||||
|     bool oldEnabled = enabled; | ||||
|     int8_t oldPin = PIRsensorPin; | ||||
|  | ||||
|     DEBUG_PRINT(FPSTR(_name)); | ||||
|     JsonObject top = root[FPSTR(_name)]; | ||||
|     if (top.isNull()) { | ||||
|       DEBUG_PRINTLN(F(": No config found. (Using defaults.)")); | ||||
|       return false; | ||||
|     } | ||||
|  | ||||
|     PIRsensorPin = top["pin"] | PIRsensorPin; | ||||
|  | ||||
|     enabled = top[FPSTR(_enabled)] | enabled; | ||||
|  | ||||
|     m_switchOffDelay = (top[FPSTR(_switchOffDelay)] | m_switchOffDelay/1000) * 1000; | ||||
|  | ||||
|     m_onPreset = top[FPSTR(_onPreset)] | m_onPreset; | ||||
|     m_onPreset = max(0,min(250,(int)m_onPreset)); | ||||
|     m_offPreset = top[FPSTR(_offPreset)] | m_offPreset; | ||||
|     m_offPreset = max(0,min(250,(int)m_offPreset)); | ||||
|  | ||||
|     m_nightTimeOnly = top[FPSTR(_nightTime)] | m_nightTimeOnly; | ||||
|     m_mqttOnly      = top[FPSTR(_mqttOnly)] | m_mqttOnly; | ||||
|     m_offOnly       = top[FPSTR(_offOnly)] | m_offOnly; | ||||
|     HomeAssistantDiscovery = top[FPSTR(_haDiscovery)] | HomeAssistantDiscovery; | ||||
|  | ||||
|     NotifyUpdateMode = top[FPSTR(_notify)] ? CALL_MODE_DIRECT_CHANGE : CALL_MODE_NO_NOTIFY; | ||||
|  | ||||
|     if (!initDone) { | ||||
|       // reading config prior to setup() | ||||
|       DEBUG_PRINTLN(F(" config loaded.")); | ||||
|     } else { | ||||
|       if (oldPin != PIRsensorPin || oldEnabled != enabled) { | ||||
|         // check if pin is OK | ||||
|         if (oldPin != PIRsensorPin && oldPin >= 0) { | ||||
|           // if we are changing pin in settings page | ||||
|           // deallocate old pin | ||||
|           pinManager.deallocatePin(oldPin, PinOwner::UM_PIR); | ||||
|           if (pinManager.allocatePin(PIRsensorPin, false, PinOwner::UM_PIR)) { | ||||
|             pinMode(PIRsensorPin, INPUT_PULLUP); | ||||
|           } else { | ||||
|             // allocation failed | ||||
|             PIRsensorPin = -1; | ||||
|             enabled = false; | ||||
|           } | ||||
|         } | ||||
|         if (enabled) { | ||||
|           sensorPinState = digitalRead(PIRsensorPin); | ||||
|         } | ||||
|       } | ||||
|       DEBUG_PRINTLN(F(" config (re)loaded.")); | ||||
|     } | ||||
|     // use "return !top["newestParameter"].isNull();" when updating Usermod with new features | ||||
|     return !top[FPSTR(_haDiscovery)].isNull(); | ||||
|   } | ||||
|   bool readFromConfig(JsonObject &root); | ||||
|  | ||||
|   /** | ||||
|    * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). | ||||
|    * This could be used in the future for the system to determine whether your usermod is installed. | ||||
|    */ | ||||
|   uint16_t getId() | ||||
|   { | ||||
|     return USERMOD_ID_PIRSWITCH; | ||||
|   } | ||||
|   uint16_t getId() { return USERMOD_ID_PIRSWITCH; } | ||||
| }; | ||||
|  | ||||
| // strings to reduce flash memory usage (used more than twice) | ||||
| @@ -503,3 +195,359 @@ const char PIRsensorSwitch::_mqttOnly[]       PROGMEM = "mqtt-only"; | ||||
| const char PIRsensorSwitch::_offOnly[]        PROGMEM = "off-only"; | ||||
| const char PIRsensorSwitch::_haDiscovery[]    PROGMEM = "HA-discovery"; | ||||
| const char PIRsensorSwitch::_notify[]         PROGMEM = "notifications"; | ||||
| const char PIRsensorSwitch::_override[]       PROGMEM = "override"; | ||||
|  | ||||
| bool PIRsensorSwitch::isDayTime() { | ||||
|   updateLocalTime(); | ||||
|   uint8_t hr = hour(localTime); | ||||
|   uint8_t mi = minute(localTime); | ||||
|  | ||||
|   if (sunrise && sunset) { | ||||
|     if (hour(sunrise)<hr && hour(sunset)>hr) { | ||||
|       return true; | ||||
|     } else { | ||||
|       if (hour(sunrise)==hr && minute(sunrise)<mi) { | ||||
|         return true; | ||||
|       } | ||||
|       if (hour(sunset)==hr && minute(sunset)>mi) { | ||||
|         return true; | ||||
|       } | ||||
|     } | ||||
|   } | ||||
|   return false; | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::switchStrip(bool switchOn) | ||||
| { | ||||
|   if (m_offOnly && bri && (switchOn || (!PIRtriggered && !switchOn))) return; //if lights on and off only, do nothing | ||||
|   if (PIRtriggered && switchOn) return; //if already on and triggered before, do nothing | ||||
|   PIRtriggered = switchOn; | ||||
|   DEBUG_PRINT(F("PIR: strip=")); DEBUG_PRINTLN(switchOn?"on":"off"); | ||||
|   if (switchOn) { | ||||
|     if (m_onPreset) { | ||||
|       if (currentPlaylist>0 && !offMode) { | ||||
|         prevPlaylist = currentPlaylist; | ||||
|         unloadPlaylist(); | ||||
|       } else if (currentPreset>0 && !offMode) { | ||||
|         prevPreset   = currentPreset; | ||||
|       } else { | ||||
|         saveTemporaryPreset(); | ||||
|         prevPlaylist = 0; | ||||
|         prevPreset   = 255; | ||||
|       } | ||||
|       applyPreset(m_onPreset, NotifyUpdateMode); | ||||
|       return; | ||||
|     } | ||||
|     // preset not assigned | ||||
|     if (bri == 0) { | ||||
|       bri = briLast; | ||||
|       stateUpdated(NotifyUpdateMode); | ||||
|     } | ||||
|   } else { | ||||
|     if (m_offPreset) { | ||||
|       applyPreset(m_offPreset, NotifyUpdateMode); | ||||
|       return; | ||||
|     } else if (prevPlaylist) { | ||||
|       if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(prevPlaylist, NotifyUpdateMode); | ||||
|       prevPlaylist = 0; | ||||
|       return; | ||||
|     } else if (prevPreset) { | ||||
|       if (prevPreset<255) { if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyPreset(prevPreset, NotifyUpdateMode); } | ||||
|       else                { if (currentPreset==m_onPreset || currentPlaylist==m_onPreset) applyTemporaryPreset(); } | ||||
|       prevPreset = 0; | ||||
|       return; | ||||
|     } | ||||
|     // preset not assigned | ||||
|     if (bri != 0) { | ||||
|       briLast = bri; | ||||
|       bri = 0; | ||||
|       stateUpdated(NotifyUpdateMode); | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::publishMqtt(const char* state) | ||||
| { | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|   //Check if MQTT Connected, otherwise it will crash the 8266 | ||||
|   if (WLED_MQTT_CONNECTED) { | ||||
|     char buf[64]; | ||||
|     sprintf_P(buf, PSTR("%s/motion"), mqttDeviceTopic);   //max length: 33 + 7 = 40 | ||||
|     mqtt->publish(buf, 0, false, state); | ||||
|   } | ||||
| #endif | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::publishHomeAssistantAutodiscovery() | ||||
| { | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|   if (WLED_MQTT_CONNECTED) { | ||||
|     StaticJsonDocument<600> doc; | ||||
|     char uid[24], json_str[1024], buf[128]; | ||||
|  | ||||
|     sprintf_P(buf, PSTR("%s Motion"), serverDescription); //max length: 33 + 7 = 40 | ||||
|     doc[F("name")] = buf; | ||||
|     sprintf_P(buf, PSTR("%s/motion"), mqttDeviceTopic);   //max length: 33 + 7 = 40 | ||||
|     doc[F("stat_t")] = buf; | ||||
|     doc[F("pl_on")]  = "on"; | ||||
|     doc[F("pl_off")] = "off"; | ||||
|     sprintf_P(uid, PSTR("%s_motion"), escapedMac.c_str()); | ||||
|     doc[F("uniq_id")] = uid; | ||||
|     doc[F("dev_cla")] = F("motion"); | ||||
|     doc[F("exp_aft")] = 1800; | ||||
|  | ||||
|     JsonObject device = doc.createNestedObject(F("device")); // attach the sensor to the same device | ||||
|     device[F("name")] = serverDescription; | ||||
|     device[F("ids")]  = String(F("wled-sensor-")) + mqttClientID; | ||||
|     device[F("mf")]   = "WLED"; | ||||
|     device[F("mdl")]  = F("FOSS"); | ||||
|     device[F("sw")]   = versionString; | ||||
|      | ||||
|     sprintf_P(buf, PSTR("homeassistant/binary_sensor/%s/config"), uid); | ||||
|     DEBUG_PRINTLN(buf); | ||||
|     size_t payload_size = serializeJson(doc, json_str); | ||||
|     DEBUG_PRINTLN(json_str); | ||||
|  | ||||
|     mqtt->publish(buf, 0, true, json_str, payload_size); // do we really need to retain? | ||||
|   } | ||||
| #endif | ||||
| } | ||||
|  | ||||
| bool PIRsensorSwitch::updatePIRsensorState() | ||||
| { | ||||
|   bool pinState = digitalRead(PIRsensorPin); | ||||
|   if (pinState != sensorPinState) { | ||||
|     sensorPinState = pinState; // change previous state | ||||
|  | ||||
|     if (sensorPinState == HIGH) { | ||||
|       offTimerStart = 0; | ||||
|       if (!m_mqttOnly && (!m_nightTimeOnly || (m_nightTimeOnly && !isDayTime()))) switchStrip(true); | ||||
|       else if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); | ||||
|       publishMqtt("on"); | ||||
|     } else { | ||||
|       // start switch off timer | ||||
|       offTimerStart = millis(); | ||||
|       if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); | ||||
|     } | ||||
|     return true; | ||||
|   } | ||||
|   return false; | ||||
| } | ||||
|  | ||||
| bool PIRsensorSwitch::handleOffTimer() | ||||
| { | ||||
|   if (offTimerStart > 0 && millis() - offTimerStart > m_switchOffDelay) { | ||||
|     offTimerStart = 0; | ||||
|     if (enabled == true) { | ||||
|       if (!m_mqttOnly && (!m_nightTimeOnly || (m_nightTimeOnly && !isDayTime()) || PIRtriggered)) switchStrip(false); | ||||
|       else if (NotifyUpdateMode != CALL_MODE_NO_NOTIFY) updateInterfaces(CALL_MODE_WS_SEND); | ||||
|       publishMqtt("off"); | ||||
|     } | ||||
|     return true; | ||||
|   } | ||||
|   return false; | ||||
| } | ||||
|  | ||||
| //Functions called by WLED | ||||
|  | ||||
| void PIRsensorSwitch::setup() | ||||
| { | ||||
|   if (enabled) { | ||||
|     // pin retrieved from cfg.json (readFromConfig()) prior to running setup() | ||||
|     if (PIRsensorPin >= 0 && pinManager.allocatePin(PIRsensorPin, false, PinOwner::UM_PIR)) { | ||||
|       // PIR Sensor mode INPUT_PULLUP | ||||
|       pinMode(PIRsensorPin, INPUT_PULLUP); | ||||
|       sensorPinState = digitalRead(PIRsensorPin); | ||||
|     } else { | ||||
|       if (PIRsensorPin >= 0) { | ||||
|         DEBUG_PRINTLN(F("PIRSensorSwitch pin allocation failed.")); | ||||
|       } | ||||
|       PIRsensorPin = -1;  // allocation failed | ||||
|       enabled = false; | ||||
|     } | ||||
|   } | ||||
|   initDone = true; | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::onMqttConnect(bool sessionPresent) | ||||
| { | ||||
|   if (HomeAssistantDiscovery) { | ||||
|     publishHomeAssistantAutodiscovery(); | ||||
|   } | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::loop() | ||||
| { | ||||
|   // only check sensors 4x/s | ||||
|   if (!enabled || millis() - lastLoop < 250 || strip.isUpdating()) return; | ||||
|   lastLoop = millis(); | ||||
|  | ||||
|   if (!updatePIRsensorState()) { | ||||
|     handleOffTimer(); | ||||
|   } | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::addToJsonInfo(JsonObject &root) | ||||
| { | ||||
|   JsonObject user = root["u"]; | ||||
|   if (user.isNull()) user = root.createNestedObject("u"); | ||||
|  | ||||
|   JsonArray infoArr = user.createNestedArray(FPSTR(_name)); | ||||
|  | ||||
|   String uiDomString; | ||||
|   if (enabled) { | ||||
|     if (offTimerStart > 0) | ||||
|     { | ||||
|       uiDomString = ""; | ||||
|       unsigned int offSeconds = (m_switchOffDelay - (millis() - offTimerStart)) / 1000; | ||||
|       if (offSeconds >= 3600) | ||||
|       { | ||||
|         uiDomString += (offSeconds / 3600); | ||||
|         uiDomString += F("h "); | ||||
|         offSeconds %= 3600; | ||||
|       } | ||||
|       if (offSeconds >= 60) | ||||
|       { | ||||
|         uiDomString += (offSeconds / 60); | ||||
|         offSeconds %= 60; | ||||
|       } | ||||
|       else if (uiDomString.length() > 0) | ||||
|       { | ||||
|         uiDomString += 0; | ||||
|       } | ||||
|       if (uiDomString.length() > 0) | ||||
|       { | ||||
|         uiDomString += F("min "); | ||||
|       } | ||||
|       uiDomString += (offSeconds); | ||||
|       infoArr.add(uiDomString + F("s")); | ||||
|     } else { | ||||
|       infoArr.add(sensorPinState ? F("sensor on") : F("inactive")); | ||||
|     } | ||||
|   } else { | ||||
|     infoArr.add(F("disabled")); | ||||
|   } | ||||
|  | ||||
|   uiDomString  = F(" <button class=\"btn btn-xs\" onclick=\"requestJson({"); | ||||
|   uiDomString += FPSTR(_name); | ||||
|   uiDomString += F(":{"); | ||||
|   uiDomString += FPSTR(_enabled); | ||||
|   if (enabled) { | ||||
|     uiDomString += F(":false}});\">"); | ||||
|     uiDomString += F("<i class=\"icons on\"></i>"); | ||||
|   } else { | ||||
|     uiDomString += F(":true}});\">"); | ||||
|     uiDomString += F("<i class=\"icons off\"></i>"); | ||||
|   } | ||||
|   uiDomString += F("</button>"); | ||||
|   infoArr.add(uiDomString); | ||||
|  | ||||
|   JsonObject sensor = root[F("sensor")]; | ||||
|   if (sensor.isNull()) sensor = root.createNestedObject(F("sensor")); | ||||
|   sensor[F("motion")] = sensorPinState || offTimerStart>0 ? true : false; | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::onStateChange(uint8_t mode) { | ||||
|   if (!initDone) return; | ||||
|   DEBUG_PRINT(F("PIR: offTimerStart=")); DEBUG_PRINTLN(offTimerStart); | ||||
|   if (m_override && PIRtriggered && offTimerStart) { // debounce | ||||
|     // checking PIRtriggered and offTimerStart will prevent cancellation upon On trigger | ||||
|     DEBUG_PRINTLN(F("PIR: Canceled.")); | ||||
|     offTimerStart = 0; | ||||
|     PIRtriggered = false; | ||||
|   } | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::readFromJsonState(JsonObject &root) | ||||
| { | ||||
|   if (!initDone) return;  // prevent crash on boot applyPreset() | ||||
|   JsonObject usermod = root[FPSTR(_name)]; | ||||
|   if (!usermod.isNull()) { | ||||
|     if (usermod[FPSTR(_enabled)].is<bool>()) { | ||||
|       enabled = usermod[FPSTR(_enabled)].as<bool>(); | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::addToConfig(JsonObject &root) | ||||
| { | ||||
|   JsonObject top = root.createNestedObject(FPSTR(_name)); | ||||
|   top[FPSTR(_enabled)]        = enabled; | ||||
|   top[FPSTR(_switchOffDelay)] = m_switchOffDelay / 1000; | ||||
|   top["pin"]                  = PIRsensorPin; | ||||
|   top[FPSTR(_onPreset)]       = m_onPreset; | ||||
|   top[FPSTR(_offPreset)]      = m_offPreset; | ||||
|   top[FPSTR(_nightTime)]      = m_nightTimeOnly; | ||||
|   top[FPSTR(_mqttOnly)]       = m_mqttOnly; | ||||
|   top[FPSTR(_offOnly)]        = m_offOnly; | ||||
|   top[FPSTR(_override)]       = m_override; | ||||
|   top[FPSTR(_haDiscovery)]    = HomeAssistantDiscovery; | ||||
|   top[FPSTR(_notify)]         = (NotifyUpdateMode != CALL_MODE_NO_NOTIFY); | ||||
|   DEBUG_PRINTLN(F("PIR config saved.")); | ||||
| } | ||||
|  | ||||
| void PIRsensorSwitch::appendConfigData() | ||||
| { | ||||
|   oappend(SET_F("addInfo('PIRsensorSwitch:HA-discovery',1,'HA=Home Assistant');"));     // 0 is field type, 1 is actual field | ||||
|   oappend(SET_F("addInfo('PIRsensorSwitch:notifications',1,'Periodic WS updates');"));  // 0 is field type, 1 is actual field | ||||
|   oappend(SET_F("addInfo('PIRsensorSwitch:override',1,'Cancel timer on change');"));    // 0 is field type, 1 is actual field | ||||
| } | ||||
|  | ||||
| bool PIRsensorSwitch::readFromConfig(JsonObject &root) | ||||
| { | ||||
|   bool oldEnabled = enabled; | ||||
|   int8_t oldPin = PIRsensorPin; | ||||
|  | ||||
|   DEBUG_PRINT(FPSTR(_name)); | ||||
|   JsonObject top = root[FPSTR(_name)]; | ||||
|   if (top.isNull()) { | ||||
|     DEBUG_PRINTLN(F(": No config found. (Using defaults.)")); | ||||
|     return false; | ||||
|   } | ||||
|  | ||||
|   PIRsensorPin = top["pin"] | PIRsensorPin; | ||||
|  | ||||
|   enabled = top[FPSTR(_enabled)] | enabled; | ||||
|  | ||||
|   m_switchOffDelay = (top[FPSTR(_switchOffDelay)] | m_switchOffDelay/1000) * 1000; | ||||
|  | ||||
|   m_onPreset = top[FPSTR(_onPreset)] | m_onPreset; | ||||
|   m_onPreset = max(0,min(250,(int)m_onPreset)); | ||||
|   m_offPreset = top[FPSTR(_offPreset)] | m_offPreset; | ||||
|   m_offPreset = max(0,min(250,(int)m_offPreset)); | ||||
|  | ||||
|   m_nightTimeOnly = top[FPSTR(_nightTime)] | m_nightTimeOnly; | ||||
|   m_mqttOnly      = top[FPSTR(_mqttOnly)] | m_mqttOnly; | ||||
|   m_offOnly       = top[FPSTR(_offOnly)] | m_offOnly; | ||||
|   m_override      = top[FPSTR(_override)] | m_override; | ||||
|   HomeAssistantDiscovery = top[FPSTR(_haDiscovery)] | HomeAssistantDiscovery; | ||||
|  | ||||
|   NotifyUpdateMode = top[FPSTR(_notify)] ? CALL_MODE_DIRECT_CHANGE : CALL_MODE_NO_NOTIFY; | ||||
|  | ||||
|   if (!initDone) { | ||||
|     // reading config prior to setup() | ||||
|     DEBUG_PRINTLN(F(" config loaded.")); | ||||
|   } else { | ||||
|     if (oldPin != PIRsensorPin || oldEnabled != enabled) { | ||||
|       // check if pin is OK | ||||
|       if (oldPin != PIRsensorPin && oldPin >= 0) { | ||||
|         // if we are changing pin in settings page | ||||
|         // deallocate old pin | ||||
|         pinManager.deallocatePin(oldPin, PinOwner::UM_PIR); | ||||
|         if (pinManager.allocatePin(PIRsensorPin, false, PinOwner::UM_PIR)) { | ||||
|           pinMode(PIRsensorPin, INPUT_PULLUP); | ||||
|         } else { | ||||
|           // allocation failed | ||||
|           PIRsensorPin = -1; | ||||
|           enabled = false; | ||||
|         } | ||||
|       } | ||||
|       if (enabled) { | ||||
|         sensorPinState = digitalRead(PIRsensorPin); | ||||
|       } | ||||
|     } | ||||
|     DEBUG_PRINTLN(F(" config (re)loaded.")); | ||||
|   } | ||||
|   // use "return !top["newestParameter"].isNull();" when updating Usermod with new features | ||||
|   return !top[FPSTR(_override)].isNull(); | ||||
| } | ||||
|   | ||||
| @@ -5,7 +5,7 @@ v2 Usermod to to control PWM fan with RPM feedback and temperature control | ||||
| This usermod requires the Dallas Temperature usermod to obtain temperature information. If it's not available, the fan will run at 100% speed. | ||||
| If the fan does not have _tachometer_ (RPM) output you can set the _tachometer-pin_ to -1 to disable that feature. | ||||
|  | ||||
| You can also set the thershold temperature at which fan runs at lowest speed. If the measured temperature is 3°C greater than the threshold temperature, the fan will run at 100%. | ||||
| You can also set the threshold temperature at which fan runs at lowest speed. If the measured temperature is 3°C greater than the threshold temperature, the fan will run at 100%. | ||||
|  | ||||
| If the _tachometer_ is supported, the current speed (in RPM) will be displayed on the WLED Info page. | ||||
|  | ||||
| @@ -22,7 +22,7 @@ This includes: | ||||
| * PWM output pin (can be configured at compile time `-D PWM_PIN=xx`) | ||||
| * tachometer input pin (can be configured at compile time `-D TACHO_PIN=xx`) | ||||
| * sampling frequency in seconds | ||||
| * threshold temperature in degees C | ||||
| * threshold temperature in degrees Celsius | ||||
|  | ||||
| _NOTE:_ You may also need to tweak Dallas Temperature usermod sampling frequency to match PWM fan sampling frequency. | ||||
|  | ||||
|   | ||||
| @@ -1,7 +1,7 @@ | ||||
| #pragma once | ||||
|  | ||||
| #ifndef USERMOD_DALLASTEMPERATURE | ||||
| #error The "PWM fan" usermod requires "Dallas Temeprature" usermod to function properly. | ||||
| #if !defined(USERMOD_DALLASTEMPERATURE) && !defined(USERMOD_SHT) | ||||
| #error The "PWM fan" usermod requires "Dallas Temeprature" or "SHT" usermod to function properly. | ||||
| #endif | ||||
|  | ||||
| #include "wled.h" | ||||
| @@ -42,6 +42,8 @@ class PWMFanUsermod : public Usermod { | ||||
|  | ||||
|     #ifdef USERMOD_DALLASTEMPERATURE | ||||
|     UsermodTemperature* tempUM; | ||||
|     #elif defined(USERMOD_SHT) | ||||
|     ShtUsermod* tempUM; | ||||
|     #endif | ||||
|  | ||||
|     // configurable parameters | ||||
| @@ -50,9 +52,15 @@ class PWMFanUsermod : public Usermod { | ||||
|     uint8_t tachoUpdateSec    = 30; | ||||
|     float   targetTemperature = 35.0; | ||||
|     uint8_t minPWMValuePct    = 0; | ||||
|     uint8_t maxPWMValuePct    = 100; | ||||
|     uint8_t numberOfInterrupsInOneSingleRotation = 2;     // Number of interrupts ESP32 sees on tacho signal on a single fan rotation. All the fans I've seen trigger two interrups. | ||||
|     uint8_t pwmValuePct       = 0; | ||||
|  | ||||
|     // constant values | ||||
|     static const uint8_t _pwmMaxValue     = 255; | ||||
|     static const uint8_t _pwmMaxStepCount = 7; | ||||
|     float _pwmTempStepSize = 0.5f; | ||||
|  | ||||
|     // strings to reduce flash memory usage (used more than twice) | ||||
|     static const char _name[]; | ||||
|     static const char _enabled[]; | ||||
| @@ -61,6 +69,7 @@ class PWMFanUsermod : public Usermod { | ||||
|     static const char _temperature[]; | ||||
|     static const char _tachoUpdateSec[]; | ||||
|     static const char _minPWMValuePct[]; | ||||
|     static const char _maxPWMValuePct[]; | ||||
|     static const char _IRQperRotation[]; | ||||
|     static const char _speed[]; | ||||
|     static const char _lock[]; | ||||
| @@ -145,7 +154,7 @@ class PWMFanUsermod : public Usermod { | ||||
|     } | ||||
|  | ||||
|     float getActualTemperature(void) { | ||||
|       #ifdef USERMOD_DALLASTEMPERATURE | ||||
|       #if defined(USERMOD_DALLASTEMPERATURE) || defined(USERMOD_SHT) | ||||
|       if (tempUM != nullptr) | ||||
|         return tempUM->getTemperatureC(); | ||||
|       #endif | ||||
| @@ -154,31 +163,25 @@ class PWMFanUsermod : public Usermod { | ||||
|  | ||||
|     void setFanPWMbasedOnTemperature(void) { | ||||
|       float temp = getActualTemperature(); | ||||
|       float difftemp = temp - targetTemperature; | ||||
|       // Default to run fan at full speed. | ||||
|       int newPWMvalue = 255; | ||||
|       int pwmStep = ((100 - minPWMValuePct) * newPWMvalue) / (7*100); | ||||
|       int pwmMinimumValue = (minPWMValuePct * newPWMvalue) / 100; | ||||
|       // dividing minPercent and maxPercent into equal pwmvalue sizes | ||||
|       int pwmStepSize = ((maxPWMValuePct - minPWMValuePct) * _pwmMaxValue) / (_pwmMaxStepCount*100); | ||||
|       int pwmStep = calculatePwmStep(temp - targetTemperature); | ||||
|       // minimum based on full speed - not entered MaxPercent  | ||||
|       int pwmMinimumValue = (minPWMValuePct * _pwmMaxValue) / 100; | ||||
|       updateFanSpeed(pwmMinimumValue + pwmStep*pwmStepSize); | ||||
|     } | ||||
|  | ||||
|       if ((temp == NAN) || (temp <= -100.0)) { | ||||
|     uint8_t calculatePwmStep(float diffTemp){ | ||||
|       if ((diffTemp == NAN) || (diffTemp <= -100.0)) { | ||||
|         DEBUG_PRINTLN(F("WARNING: no temperature value available. Cannot do temperature control. Will set PWM fan to 255.")); | ||||
|       } else if (difftemp <= 0.0) { | ||||
|         // Temperature is below target temperature. Run fan at minimum speed. | ||||
|         newPWMvalue = pwmMinimumValue; | ||||
|       } else if (difftemp <= 0.5) { | ||||
|         newPWMvalue = pwmMinimumValue + pwmStep; | ||||
|       } else if (difftemp <= 1.0) { | ||||
|         newPWMvalue = pwmMinimumValue + 2*pwmStep; | ||||
|       } else if (difftemp <= 1.5) { | ||||
|         newPWMvalue = pwmMinimumValue + 3*pwmStep; | ||||
|       } else if (difftemp <= 2.0) { | ||||
|         newPWMvalue = pwmMinimumValue + 4*pwmStep; | ||||
|       } else if (difftemp <= 2.5) { | ||||
|         newPWMvalue = pwmMinimumValue + 5*pwmStep; | ||||
|       } else if (difftemp <= 3.0) { | ||||
|         newPWMvalue = pwmMinimumValue + 6*pwmStep; | ||||
|         return _pwmMaxStepCount; | ||||
|       } | ||||
|       updateFanSpeed(newPWMvalue); | ||||
|       if(diffTemp <=0){ | ||||
|         return 0; | ||||
|       } | ||||
|       int calculatedStep = (diffTemp / _pwmTempStepSize)+1; | ||||
|       // anything greater than max stepcount gets max  | ||||
|       return (uint8_t)min((int)_pwmMaxStepCount,calculatedStep);       | ||||
|     } | ||||
|  | ||||
|   public: | ||||
| @@ -189,6 +192,8 @@ class PWMFanUsermod : public Usermod { | ||||
|       #ifdef USERMOD_DALLASTEMPERATURE    | ||||
|       // This Usermod requires Temperature usermod | ||||
|       tempUM = (UsermodTemperature*) usermods.lookup(USERMOD_ID_TEMPERATURE); | ||||
|       #elif defined(USERMOD_SHT) | ||||
|       tempUM = (ShtUsermod*) usermods.lookup(USERMOD_ID_SHT); | ||||
|       #endif | ||||
|       initTacho(); | ||||
|       initPWMfan(); | ||||
| @@ -308,6 +313,7 @@ class PWMFanUsermod : public Usermod { | ||||
|       top[FPSTR(_tachoUpdateSec)] = tachoUpdateSec; | ||||
|       top[FPSTR(_temperature)]    = targetTemperature; | ||||
|       top[FPSTR(_minPWMValuePct)] = minPWMValuePct; | ||||
|       top[FPSTR(_maxPWMValuePct)] = maxPWMValuePct; | ||||
|       top[FPSTR(_IRQperRotation)] = numberOfInterrupsInOneSingleRotation; | ||||
|       DEBUG_PRINTLN(F("Autosave config saved.")); | ||||
|     } | ||||
| @@ -341,6 +347,8 @@ class PWMFanUsermod : public Usermod { | ||||
|       targetTemperature = top[FPSTR(_temperature)] | targetTemperature; | ||||
|       minPWMValuePct    = top[FPSTR(_minPWMValuePct)] | minPWMValuePct; | ||||
|       minPWMValuePct    = (uint8_t) min(100,max(0,(int)minPWMValuePct)); // bounds checking | ||||
|       maxPWMValuePct    = top[FPSTR(_maxPWMValuePct)] | maxPWMValuePct; | ||||
|       maxPWMValuePct    = (uint8_t) min(100,max((int)minPWMValuePct,(int)maxPWMValuePct)); // bounds checking | ||||
|       numberOfInterrupsInOneSingleRotation = top[FPSTR(_IRQperRotation)] | numberOfInterrupsInOneSingleRotation; | ||||
|       numberOfInterrupsInOneSingleRotation = (uint8_t) max(1,(int)numberOfInterrupsInOneSingleRotation); // bounds checking | ||||
|  | ||||
| @@ -385,6 +393,7 @@ const char PWMFanUsermod::_pwmPin[]         PROGMEM = "PWM-pin"; | ||||
| const char PWMFanUsermod::_temperature[]    PROGMEM = "target-temp-C"; | ||||
| const char PWMFanUsermod::_tachoUpdateSec[] PROGMEM = "tacho-update-s"; | ||||
| const char PWMFanUsermod::_minPWMValuePct[] PROGMEM = "min-PWM-percent"; | ||||
| const char PWMFanUsermod::_maxPWMValuePct[] PROGMEM = "max-PWM-percent"; | ||||
| const char PWMFanUsermod::_IRQperRotation[] PROGMEM = "IRQs-per-rotation"; | ||||
| const char PWMFanUsermod::_speed[]          PROGMEM = "speed"; | ||||
| const char PWMFanUsermod::_lock[]           PROGMEM = "lock"; | ||||
|   | ||||
| @@ -12,8 +12,7 @@ class RTCUsermod : public Usermod { | ||||
|   public: | ||||
|  | ||||
|     void setup() { | ||||
|       PinManagerPinType pins[2] = { { i2c_scl, true }, { i2c_sda, true } }; | ||||
|       if (!pinManager.allocateMultiplePins(pins, 2, PinOwner::HW_I2C)) { disabled = true; return; } | ||||
|       if (i2c_scl<0 || i2c_sda<0) { disabled = true; return; } | ||||
|       RTC.begin(); | ||||
|       time_t rtcTime = RTC.get(); | ||||
|       if (rtcTime) { | ||||
| @@ -25,8 +24,8 @@ class RTCUsermod : public Usermod { | ||||
|     } | ||||
|  | ||||
|     void loop() { | ||||
|       if (strip.isUpdating()) return; | ||||
|       if (!disabled && toki.isTick()) { | ||||
|       if (disabled || strip.isUpdating()) return; | ||||
|       if (toki.isTick()) { | ||||
|         time_t t = toki.second(); | ||||
|         if (t != RTC.get()) RTC.set(t); //set RTC to NTP/UI-provided value | ||||
|       } | ||||
|   | ||||
| @@ -30,7 +30,7 @@ | ||||
| #define USERMOD_SN_PHOTORESISTOR_RESISTOR_VALUE 10000.0f | ||||
| #endif | ||||
|  | ||||
| // only report if differance grater than offset value | ||||
| // only report if difference grater than offset value | ||||
| #ifndef USERMOD_SN_PHOTORESISTOR_OFFSET_VALUE | ||||
| #define USERMOD_SN_PHOTORESISTOR_OFFSET_VALUE 5 | ||||
| #endif | ||||
| @@ -109,6 +109,7 @@ public: | ||||
|     { | ||||
|       lastLDRValue = currentLDRValue; | ||||
|  | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|       if (WLED_MQTT_CONNECTED) | ||||
|       { | ||||
|         char subuf[45]; | ||||
| @@ -121,6 +122,7 @@ public: | ||||
|         DEBUG_PRINTLN("Missing MQTT connection. Not publishing data"); | ||||
|       } | ||||
|     } | ||||
| #endif | ||||
|   } | ||||
|  | ||||
|   uint16_t getLastLDRValue() | ||||
|   | ||||
| @@ -17,12 +17,6 @@ | ||||
|     #ifndef TFT_HEIGHT | ||||
|         #error Please define TFT_HEIGHT | ||||
|     #endif | ||||
|     #ifndef TFT_MOSI | ||||
|         #error Please define TFT_MOSI | ||||
|     #endif | ||||
|     #ifndef TFT_SCLK | ||||
|         #error Please define TFT_SCLK | ||||
|     #endif | ||||
|     #ifndef TFT_DC | ||||
|         #error Please define TFT_DC | ||||
|     #endif | ||||
| @@ -140,8 +134,14 @@ class St7789DisplayUsermod : public Usermod { | ||||
|      */ | ||||
|     void setup() | ||||
|     { | ||||
|         PinManagerPinType pins[] = { { TFT_MOSI, true }, { TFT_MISO, false}, { TFT_SCLK, true }, { TFT_CS, true}, { TFT_DC, true}, { TFT_RST, true }, { TFT_BL, true } }; | ||||
|         if (!pinManager.allocateMultiplePins(pins, 7, PinOwner::UM_FourLineDisplay)) { enabled = false; return; } | ||||
|         PinManagerPinType spiPins[] = { { spi_mosi, true }, { spi_miso, false}, { spi_sclk, true } }; | ||||
|         if (!pinManager.allocateMultiplePins(spiPins, 3, PinOwner::HW_SPI)) { enabled = false; return; } | ||||
|         PinManagerPinType displayPins[] = { { TFT_CS, true}, { TFT_DC, true}, { TFT_RST, true }, { TFT_BL, true } }; | ||||
|         if (!pinManager.allocateMultiplePins(displayPins, sizeof(displayPins)/sizeof(PinManagerPinType), PinOwner::UM_FourLineDisplay)) { | ||||
|             pinManager.deallocateMultiplePins(spiPins, 3, PinOwner::HW_SPI); | ||||
|             enabled = false; | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         tft.init(); | ||||
|         tft.setRotation(0);  //Rotation here is set up for the text to be readable with the port on the left. Use 1 to flip. | ||||
| @@ -365,9 +365,6 @@ class St7789DisplayUsermod : public Usermod { | ||||
|     { | ||||
|       JsonObject top = root.createNestedObject("ST7789"); | ||||
|       JsonArray pins = top.createNestedArray("pin"); | ||||
|       pins.add(TFT_MOSI); | ||||
|       pins.add(TFT_MISO); | ||||
|       pins.add(TFT_SCLK); | ||||
|       pins.add(TFT_CS); | ||||
|       pins.add(TFT_DC); | ||||
|       pins.add(TFT_RST); | ||||
| @@ -376,6 +373,13 @@ class St7789DisplayUsermod : public Usermod { | ||||
|     } | ||||
|  | ||||
|  | ||||
|     void appendConfigData() { | ||||
|       oappend(SET_F("addInfo('ST7789:pin[]',0,'','SPI CS');")); | ||||
|       oappend(SET_F("addInfo('ST7789:pin[]',1,'','SPI DC');")); | ||||
|       oappend(SET_F("addInfo('ST7789:pin[]',2,'','SPI RST');")); | ||||
|       oappend(SET_F("addInfo('ST7789:pin[]',2,'','SPI BL');")); | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * readFromConfig() can be used to read back the custom settings you added with addToConfig(). | ||||
|      * This is called by WLED when settings are loaded (currently this only happens once immediately after boot) | ||||
|   | ||||
| @@ -1,3 +1,7 @@ | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #pragma once | ||||
|  | ||||
| // this is remixed from usermod_v2_SensorsToMqtt.h (sensors_to_mqtt usermod) | ||||
| @@ -9,14 +13,6 @@ | ||||
|  | ||||
| Adafruit_Si7021 si7021; | ||||
|  | ||||
| #ifdef ARDUINO_ARCH_ESP32 //ESP32 boards | ||||
| uint8_t SCL_PIN = 22; | ||||
| uint8_t SDA_PIN = 21; | ||||
| #else //ESP8266 boards | ||||
| uint8_t SCL_PIN = 5; | ||||
| uint8_t SDA_PIN = 4; | ||||
| #endif | ||||
|  | ||||
| class Si7021_MQTT_HA : public Usermod | ||||
| { | ||||
|   private: | ||||
| @@ -180,7 +176,6 @@ class Si7021_MQTT_HA : public Usermod | ||||
|     { | ||||
|       if (enabled) { | ||||
|         Serial.println("Si7021_MQTT_HA: Starting!"); | ||||
|         Wire.begin(SDA_PIN, SCL_PIN); | ||||
|         Serial.println("Si7021_MQTT_HA: Initializing sensors.. "); | ||||
|         _initializeSensor(); | ||||
|       } | ||||
|   | ||||
| @@ -3,7 +3,7 @@ | ||||
|  * This file allows you to add own functionality to WLED more easily | ||||
|  * See: https://github.com/Aircoookie/WLED/wiki/Add-own-functionality | ||||
|  * EEPROM bytes 2750+ are reserved for your custom use case. (if you extend #define EEPSIZE in const.h) | ||||
|  * bytes 2400+ are currently ununsed, but might be used for future wled features | ||||
|  * bytes 2400+ are currently unused, but might be used for future wled features | ||||
|  */ | ||||
|  | ||||
| /* | ||||
| @@ -144,7 +144,7 @@ void userLoop() { | ||||
|   // First row with Wifi name | ||||
|   tft.setCursor(1, 1); | ||||
|   tft.print(knownSsid.substring(0, tftcharwidth > 1 ? tftcharwidth - 1 : 0)); | ||||
|   // Print `~` char to indicate that SSID is longer, than our dicplay | ||||
|   // Print `~` char to indicate that SSID is longer than our display | ||||
|   if (knownSsid.length() > tftcharwidth) | ||||
|     tft.print("~"); | ||||
|  | ||||
|   | ||||
| @@ -1,13 +1,12 @@ | ||||
| ; Options | ||||
| ; ------- | ||||
| ; USERMOD_DALLASTEMPERATURE                      - define this to have this user mod included wled00\usermods_list.cpp | ||||
| ; USERMOD_DALLASTEMPERATURE_CELSIUS              - define this to report temperatures in degrees celsius, otherwise fahrenheit will be reported | ||||
| ; USERMOD_DALLASTEMPERATURE_MEASUREMENT_INTERVAL - the number of milliseconds between measurements, defaults to 60 seconds | ||||
| ; USERMOD_DALLASTEMPERATURE_FIRST_MEASUREMENT_AT - the number of milliseconds after boot to take first measurement, defaults to 20 seconds | ||||
| ; | ||||
| [env:d1_mini_usermod_dallas_temperature_C] | ||||
| extends = env:d1_mini | ||||
| build_flags = ${common.build_flags_esp8266} -D USERMOD_DALLASTEMPERATURE -D USERMOD_DALLASTEMPERATURE_CELSIUS | ||||
| build_flags = ${common.build_flags_esp8266} -D USERMOD_DALLASTEMPERATURE | ||||
| lib_deps = ${env.lib_deps} | ||||
|     milesburton/DallasTemperature@^3.9.0 | ||||
|     OneWire@~2.3.5 | ||||
|   paulstoffregen/OneWire@~2.3.7 | ||||
| # you may want to use following with ESP32 | ||||
| ;  https://github.com/blazoncek/OneWire.git # fixes Sensor error on ESP32 | ||||
| @@ -7,6 +7,8 @@ May be expanded with support for different sensor types in the future. | ||||
|  | ||||
| If temperature sensor is not detected during boot, this usermod will be disabled. | ||||
|  | ||||
| Maintained by @blazoncek | ||||
|  | ||||
| ## Installation | ||||
|  | ||||
| Copy the example `platformio_override.ini` to the root directory.  This file should be placed in the same directory as `platformio.ini`. | ||||
| @@ -14,9 +16,9 @@ Copy the example `platformio_override.ini` to the root directory.  This file sho | ||||
| ### Define Your Options | ||||
|  | ||||
| * `USERMOD_DALLASTEMPERATURE`                      - enables this user mod wled00/usermods_list.cpp | ||||
| * `USERMOD_DALLASTEMPERATURE_FIRST_MEASUREMENT_AT` - umber of milliseconds after boot to take first measurement, defaults to 20000 ms | ||||
| * `USERMOD_DALLASTEMPERATURE_MEASUREMENT_INTERVAL` - number of milliseconds between measurements, defaults to 60000 ms (60s) | ||||
|  | ||||
| All parameters can be configured at runtime via the Usermods settings page, including pin, temperature in degrees Celsius or Farenheit and measurement interval. | ||||
| All parameters can be configured at runtime via the Usermods settings page, including pin, temperature in degrees Celsius or Fahrenheit and measurement interval. | ||||
|  | ||||
| ## Project link | ||||
|  | ||||
| @@ -27,7 +29,6 @@ All parameters can be configured at runtime via the Usermods settings page, incl | ||||
|  | ||||
| If you are using `platformio_override.ini`, you should be able to refresh the task list and see your custom task, for example `env:d1_mini_usermod_dallas_temperature_C`. | ||||
|  | ||||
|  | ||||
| If you are not using `platformio_override.ini`, you might have to uncomment `OneWire@~2.3.5 under` `[common]` section in `platformio.ini`: | ||||
|  | ||||
| ```ini | ||||
| @@ -43,8 +44,9 @@ default_envs = d1_mini | ||||
| lib_deps = | ||||
|   ... | ||||
|   #For Dallas sensor uncomment following line | ||||
|   OneWire@~2.3.5 | ||||
| ... | ||||
|   OneWire@~2.3.7 | ||||
|   # ... or you may want to use following with ESP32 | ||||
| ;  https://github.com/blazoncek/OneWire.git # fixes Sensor error on ESP32... | ||||
| ``` | ||||
|  | ||||
| ## Change Log | ||||
| @@ -56,3 +58,6 @@ lib_deps = | ||||
| * Report the number of seconds until the first read in the info screen instead of sensor error | ||||
| 2021-04 | ||||
| * Adaptation for runtime configuration. | ||||
| 2023-05 | ||||
| * Rewrite to conform to newer recommendations. | ||||
| * Recommended @blazoncek fork of OneWire for ESP32 to avoid Sensor error | ||||
| @@ -29,6 +29,7 @@ class UsermodTemperature : public Usermod { | ||||
|     bool degC = true; | ||||
|     // using parasite power on the sensor | ||||
|     bool parasite = false; | ||||
|     int8_t parasitePin = -1; | ||||
|     // how often do we read from sensor? | ||||
|     unsigned long readingInterval = USERMOD_DALLASTEMPERATURE_MEASUREMENT_INTERVAL; | ||||
|     // set last reading as "40 sec before boot", so first reading is taken after 20 sec | ||||
| @@ -53,323 +54,379 @@ class UsermodTemperature : public Usermod { | ||||
|     static const char _enabled[]; | ||||
|     static const char _readInterval[]; | ||||
|     static const char _parasite[]; | ||||
|     static const char _parasitePin[]; | ||||
|  | ||||
|     //Dallas sensor quick (& dirty) reading. Credit to - Author: Peter Scargill, August 17th, 2013 | ||||
|     float readDallas() { | ||||
|       byte data[9]; | ||||
|       int16_t result;                         // raw data from sensor | ||||
|       float retVal = -127.0f; | ||||
|       if (oneWire->reset()) {                 // if reset() fails there are no OneWire devices | ||||
|         oneWire->skip();                      // skip ROM | ||||
|         oneWire->write(0xBE);                 // read (temperature) from EEPROM | ||||
|         oneWire->read_bytes(data, 9);         // first 2 bytes contain temperature | ||||
|         #ifdef WLED_DEBUG | ||||
|         if (OneWire::crc8(data,8) != data[8]) { | ||||
|           DEBUG_PRINTLN(F("CRC error reading temperature.")); | ||||
|           for (byte i=0; i < 9; i++) DEBUG_PRINTF("0x%02X ", data[i]); | ||||
|           DEBUG_PRINT(F(" => ")); | ||||
|           DEBUG_PRINTF("0x%02X\n", OneWire::crc8(data,8)); | ||||
|         } | ||||
|         #endif | ||||
|         switch(sensorFound) { | ||||
|           case 0x10:  // DS18S20 has 9-bit precision | ||||
|             result = (data[1] << 8) | data[0]; | ||||
|             retVal = float(result) * 0.5f; | ||||
|             break; | ||||
|           case 0x22:  // DS18B20 | ||||
|           case 0x28:  // DS1822 | ||||
|           case 0x3B:  // DS1825 | ||||
|           case 0x42:  // DS28EA00 | ||||
|             result = (data[1]<<4) | (data[0]>>4);   // we only need whole part, we will add fraction when returning | ||||
|             if (data[1] & 0x80) result |= 0xF000;   // fix negative value | ||||
|             retVal = float(result) + ((data[0] & 0x08) ? 0.5f : 0.0f); | ||||
|             break; | ||||
|         } | ||||
|       } | ||||
|       for (byte i=1; i<9; i++) data[0] &= data[i]; | ||||
|       return data[0]==0xFF ? -127.0f : retVal; | ||||
|     } | ||||
|  | ||||
|     void requestTemperatures() { | ||||
|       DEBUG_PRINTLN(F("Requesting temperature.")); | ||||
|       oneWire->reset(); | ||||
|       oneWire->skip();                        // skip ROM | ||||
|       oneWire->write(0x44,parasite);          // request new temperature reading (TODO: parasite would need special handling) | ||||
|       lastTemperaturesRequest = millis(); | ||||
|       waitingForConversion = true; | ||||
|     } | ||||
|  | ||||
|     void readTemperature() { | ||||
|       temperature = readDallas(); | ||||
|       lastMeasurement = millis(); | ||||
|       waitingForConversion = false; | ||||
|       //DEBUG_PRINTF("Read temperature %2.1f.\n", temperature); // does not work properly on 8266 | ||||
|       DEBUG_PRINT(F("Read temperature ")); | ||||
|       DEBUG_PRINTLN(temperature); | ||||
|     } | ||||
|  | ||||
|     bool findSensor() { | ||||
|       DEBUG_PRINTLN(F("Searching for sensor...")); | ||||
|       uint8_t deviceAddress[8] = {0,0,0,0,0,0,0,0}; | ||||
|       // find out if we have DS18xxx sensor attached | ||||
|       oneWire->reset_search(); | ||||
|       delay(10); | ||||
|       while (oneWire->search(deviceAddress)) { | ||||
|         DEBUG_PRINTLN(F("Found something...")); | ||||
|         if (oneWire->crc8(deviceAddress, 7) == deviceAddress[7]) { | ||||
|           switch (deviceAddress[0]) { | ||||
|             case 0x10:  // DS18S20 | ||||
|             case 0x22:  // DS18B20 | ||||
|             case 0x28:  // DS1822 | ||||
|             case 0x3B:  // DS1825 | ||||
|             case 0x42:  // DS28EA00 | ||||
|               DEBUG_PRINTLN(F("Sensor found.")); | ||||
|               sensorFound = deviceAddress[0]; | ||||
|               DEBUG_PRINTF("0x%02X\n", sensorFound); | ||||
|               return true; | ||||
|           } | ||||
|         } | ||||
|       } | ||||
|       DEBUG_PRINTLN(F("Sensor NOT found.")); | ||||
|       return false; | ||||
|     } | ||||
|  | ||||
|     void publishHomeAssistantAutodiscovery() { | ||||
|       if (!WLED_MQTT_CONNECTED) return; | ||||
|  | ||||
|       char json_str[1024], buf[128]; | ||||
|       size_t payload_size; | ||||
|       StaticJsonDocument<1024> json; | ||||
|  | ||||
|       sprintf_P(buf, PSTR("%s Temperature"), serverDescription); | ||||
|       json[F("name")] = buf; | ||||
|       strcpy(buf, mqttDeviceTopic); | ||||
|       strcat_P(buf, PSTR("/temperature")); | ||||
|       json[F("state_topic")] = buf; | ||||
|       json[F("device_class")] = F("temperature"); | ||||
|       json[F("unique_id")] = escapedMac.c_str(); | ||||
|       json[F("unit_of_measurement")] = F("°C"); | ||||
|       payload_size = serializeJson(json, json_str); | ||||
|  | ||||
|       sprintf_P(buf, PSTR("homeassistant/sensor/%s/config"), escapedMac.c_str()); | ||||
|       mqtt->publish(buf, 0, true, json_str, payload_size); | ||||
|       HApublished = true; | ||||
|     } | ||||
|     float readDallas(); | ||||
|     void requestTemperatures(); | ||||
|     void readTemperature(); | ||||
|     bool findSensor(); | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|     void publishHomeAssistantAutodiscovery(); | ||||
| #endif | ||||
|  | ||||
|   public: | ||||
|  | ||||
|     void setup() { | ||||
|       int retries = 10; | ||||
|       sensorFound = 0; | ||||
|       temperature = -127.0f; // default to -127, DS18B20 only goes down to -50C | ||||
|       if (enabled) { | ||||
|         // config says we are enabled | ||||
|         DEBUG_PRINTLN(F("Allocating temperature pin...")); | ||||
|         // pin retrieved from cfg.json (readFromConfig()) prior to running setup() | ||||
|         if (temperaturePin >= 0 && pinManager.allocatePin(temperaturePin, true, PinOwner::UM_Temperature)) { | ||||
|           oneWire = new OneWire(temperaturePin); | ||||
|           if (oneWire->reset()) { | ||||
|             while (!findSensor() && retries--) { | ||||
|               delay(25); // try to find sensor | ||||
|             } | ||||
|           } | ||||
|         } else { | ||||
|           if (temperaturePin >= 0) { | ||||
|             DEBUG_PRINTLN(F("Temperature pin allocation failed.")); | ||||
|           } | ||||
|           temperaturePin = -1;  // allocation failed | ||||
|         } | ||||
|       } | ||||
|       lastMeasurement = millis() - readingInterval + 10000; | ||||
|       initDone = true; | ||||
|     } | ||||
|  | ||||
|     void loop() { | ||||
|       if (!enabled || !sensorFound || strip.isUpdating()) return; | ||||
|  | ||||
|       static uint8_t errorCount = 0; | ||||
|       unsigned long now = millis(); | ||||
|  | ||||
|       // check to see if we are due for taking a measurement | ||||
|       // lastMeasurement will not be updated until the conversion | ||||
|       // is complete the the reading is finished | ||||
|       if (now - lastMeasurement < readingInterval) return; | ||||
|  | ||||
|       // we are due for a measurement, if we are not already waiting | ||||
|       // for a conversion to complete, then make a new request for temps | ||||
|       if (!waitingForConversion) { | ||||
|         requestTemperatures(); | ||||
|         return; | ||||
|       } | ||||
|  | ||||
|       // we were waiting for a conversion to complete, have we waited log enough? | ||||
|       if (now - lastTemperaturesRequest >= 750 /* 93.75ms per the datasheet but can be up to 750ms */) { | ||||
|         readTemperature(); | ||||
|         if (getTemperatureC() < -100.0f) { | ||||
|           if (++errorCount > 10) sensorFound = 0; | ||||
|           lastMeasurement = now - readingInterval + 300; // force new measurement in 300ms | ||||
|           return; | ||||
|         } | ||||
|         errorCount = 0; | ||||
|  | ||||
|         if (WLED_MQTT_CONNECTED) { | ||||
|           char subuf[64]; | ||||
|           strcpy(subuf, mqttDeviceTopic); | ||||
|           if (temperature > -100.0f) { | ||||
|             // dont publish super low temperature as the graph will get messed up | ||||
|             // the DallasTemperature library returns -127C or -196.6F when problem | ||||
|             // reading the sensor | ||||
|             strcat_P(subuf, PSTR("/temperature")); | ||||
|             mqtt->publish(subuf, 0, false, String(getTemperatureC()).c_str()); | ||||
|             strcat_P(subuf, PSTR("_f")); | ||||
|             mqtt->publish(subuf, 0, false, String(getTemperatureF()).c_str()); | ||||
|           } else { | ||||
|             // publish something else to indicate status? | ||||
|           } | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * connected() is called every time the WiFi is (re)connected | ||||
|      * Use it to initialize network interfaces | ||||
|      */ | ||||
|     //void connected() {} | ||||
|  | ||||
|     /** | ||||
|      * subscribe to MQTT topic if needed | ||||
|      */ | ||||
|     void onMqttConnect(bool sessionPresent) { | ||||
|       //(re)subscribe to required topics | ||||
|       //char subuf[64]; | ||||
|       if (mqttDeviceTopic[0] != 0) { | ||||
|         publishHomeAssistantAutodiscovery(); | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     /* | ||||
|      * API calls te enable data exchange between WLED modules | ||||
|      */ | ||||
|     inline float getTemperatureC() { | ||||
|       return (float)temperature; | ||||
|     inline float getTemperatureC() { return temperature; } | ||||
|     inline float getTemperatureF() { return temperature * 1.8f + 32.0f; } | ||||
|     float getTemperature(); | ||||
|     const char *getTemperatureUnit(); | ||||
|     uint16_t getId() { return USERMOD_ID_TEMPERATURE; } | ||||
|  | ||||
|     void setup(); | ||||
|     void loop(); | ||||
|     //void connected(); | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|     void onMqttConnect(bool sessionPresent); | ||||
| #endif | ||||
|     //void onUpdateBegin(bool init); | ||||
|  | ||||
|     //bool handleButton(uint8_t b); | ||||
|     //void handleOverlayDraw(); | ||||
|  | ||||
|     void addToJsonInfo(JsonObject& root); | ||||
|     //void addToJsonState(JsonObject &root); | ||||
|     //void readFromJsonState(JsonObject &root); | ||||
|     void addToConfig(JsonObject &root); | ||||
|     bool readFromConfig(JsonObject &root); | ||||
|  | ||||
|     void appendConfigData(); | ||||
| }; | ||||
|  | ||||
| //Dallas sensor quick (& dirty) reading. Credit to - Author: Peter Scargill, August 17th, 2013 | ||||
| float UsermodTemperature::readDallas() { | ||||
|   byte data[9]; | ||||
|   int16_t result;                         // raw data from sensor | ||||
|   float retVal = -127.0f; | ||||
|   if (oneWire->reset()) {                 // if reset() fails there are no OneWire devices | ||||
|     oneWire->skip();                      // skip ROM | ||||
|     oneWire->write(0xBE);                 // read (temperature) from EEPROM | ||||
|     oneWire->read_bytes(data, 9);         // first 2 bytes contain temperature | ||||
|     #ifdef WLED_DEBUG | ||||
|     if (OneWire::crc8(data,8) != data[8]) { | ||||
|       DEBUG_PRINTLN(F("CRC error reading temperature.")); | ||||
|       for (byte i=0; i < 9; i++) DEBUG_PRINTF("0x%02X ", data[i]); | ||||
|       DEBUG_PRINT(F(" => ")); | ||||
|       DEBUG_PRINTF("0x%02X\n", OneWire::crc8(data,8)); | ||||
|     } | ||||
|     inline float getTemperatureF() { | ||||
|       return (float)temperature * 1.8f + 32; | ||||
|     #endif | ||||
|     switch(sensorFound) { | ||||
|       case 0x10:  // DS18S20 has 9-bit precision | ||||
|         result = (data[1] << 8) | data[0]; | ||||
|         retVal = float(result) * 0.5f; | ||||
|         break; | ||||
|       case 0x22:  // DS18B20 | ||||
|       case 0x28:  // DS1822 | ||||
|       case 0x3B:  // DS1825 | ||||
|       case 0x42:  // DS28EA00 | ||||
|         result = (data[1]<<4) | (data[0]>>4);   // we only need whole part, we will add fraction when returning | ||||
|         if (data[1] & 0x80) result |= 0xF000;   // fix negative value | ||||
|         retVal = float(result) + ((data[0] & 0x08) ? 0.5f : 0.0f); | ||||
|         break; | ||||
|     } | ||||
|   } | ||||
|   for (byte i=1; i<9; i++) data[0] &= data[i]; | ||||
|   return data[0]==0xFF ? -127.0f : retVal; | ||||
| } | ||||
|  | ||||
|     /* | ||||
|      * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. | ||||
|      * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. | ||||
|      * Below it is shown how this could be used for e.g. a light sensor | ||||
|      */ | ||||
|     void addToJsonInfo(JsonObject& root) { | ||||
|       // dont add temperature to info if we are disabled | ||||
|       if (!enabled) return; | ||||
| void UsermodTemperature::requestTemperatures() { | ||||
|   DEBUG_PRINTLN(F("Requesting temperature.")); | ||||
|   oneWire->reset(); | ||||
|   oneWire->skip();                        // skip ROM | ||||
|   oneWire->write(0x44,parasite);          // request new temperature reading | ||||
|   if (parasite && parasitePin >=0 ) digitalWrite(parasitePin, HIGH); // has to happen within 10us (open MOSFET) | ||||
|   lastTemperaturesRequest = millis(); | ||||
|   waitingForConversion = true; | ||||
| } | ||||
|  | ||||
|       JsonObject user = root["u"]; | ||||
|       if (user.isNull()) user = root.createNestedObject("u"); | ||||
| void UsermodTemperature::readTemperature() { | ||||
|   if (parasite && parasitePin >=0 ) digitalWrite(parasitePin, LOW); // deactivate power (close MOSFET) | ||||
|   temperature = readDallas(); | ||||
|   lastMeasurement = millis(); | ||||
|   waitingForConversion = false; | ||||
|   //DEBUG_PRINTF("Read temperature %2.1f.\n", temperature); // does not work properly on 8266 | ||||
|   DEBUG_PRINT(F("Read temperature ")); | ||||
|   DEBUG_PRINTLN(temperature); | ||||
| } | ||||
|  | ||||
|       JsonArray temp = user.createNestedArray(FPSTR(_name)); | ||||
|  | ||||
|       if (temperature <= -100.0f) { | ||||
|         temp.add(0); | ||||
|         temp.add(F(" Sensor Error!")); | ||||
|         return; | ||||
| bool UsermodTemperature::findSensor() { | ||||
|   DEBUG_PRINTLN(F("Searching for sensor...")); | ||||
|   uint8_t deviceAddress[8] = {0,0,0,0,0,0,0,0}; | ||||
|   // find out if we have DS18xxx sensor attached | ||||
|   oneWire->reset_search(); | ||||
|   delay(10); | ||||
|   while (oneWire->search(deviceAddress)) { | ||||
|     DEBUG_PRINTLN(F("Found something...")); | ||||
|     if (oneWire->crc8(deviceAddress, 7) == deviceAddress[7]) { | ||||
|       switch (deviceAddress[0]) { | ||||
|         case 0x10:  // DS18S20 | ||||
|         case 0x22:  // DS18B20 | ||||
|         case 0x28:  // DS1822 | ||||
|         case 0x3B:  // DS1825 | ||||
|         case 0x42:  // DS28EA00 | ||||
|           DEBUG_PRINTLN(F("Sensor found.")); | ||||
|           sensorFound = deviceAddress[0]; | ||||
|           DEBUG_PRINTF("0x%02X\n", sensorFound); | ||||
|           return true; | ||||
|       } | ||||
|  | ||||
|       temp.add(degC ? getTemperatureC() : getTemperatureF()); | ||||
|       temp.add(degC ? F("°C") : F("°F")); | ||||
|  | ||||
|       JsonObject sensor = root[F("sensor")]; | ||||
|       if (sensor.isNull()) sensor = root.createNestedObject(F("sensor")); | ||||
|       temp = sensor.createNestedArray(F("temp")); | ||||
|       temp.add(degC ? temperature : (float)temperature * 1.8f + 32); | ||||
|       temp.add(degC ? F("°C") : F("°F")); | ||||
|     } | ||||
|   } | ||||
|   DEBUG_PRINTLN(F("Sensor NOT found.")); | ||||
|   return false; | ||||
| } | ||||
|  | ||||
|     /** | ||||
|      * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). | ||||
|      * Values in the state object may be modified by connected clients | ||||
|      */ | ||||
|     //void addToJsonState(JsonObject &root) | ||||
|     //{ | ||||
|     //} | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
| void UsermodTemperature::publishHomeAssistantAutodiscovery() { | ||||
|   if (!WLED_MQTT_CONNECTED) return; | ||||
|  | ||||
|     /** | ||||
|      * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). | ||||
|      * Values in the state object may be modified by connected clients | ||||
|      * Read "<usermodname>_<usermodparam>" from json state and and change settings (i.e. GPIO pin) used. | ||||
|      */ | ||||
|     //void readFromJsonState(JsonObject &root) { | ||||
|     //  if (!initDone) return;  // prevent crash on boot applyPreset() | ||||
|     //} | ||||
|   char json_str[1024], buf[128]; | ||||
|   size_t payload_size; | ||||
|   StaticJsonDocument<1024> json; | ||||
|  | ||||
|     /** | ||||
|      * addToConfig() (called from set.cpp) stores persistent properties to cfg.json | ||||
|      */ | ||||
|     void addToConfig(JsonObject &root) { | ||||
|       // we add JSON object: {"Temperature": {"pin": 0, "degC": true}} | ||||
|       JsonObject top = root.createNestedObject(FPSTR(_name)); // usermodname | ||||
|       top[FPSTR(_enabled)] = enabled; | ||||
|       top["pin"]  = temperaturePin;     // usermodparam | ||||
|       top["degC"] = degC;  // usermodparam | ||||
|       top[FPSTR(_readInterval)] = readingInterval / 1000; | ||||
|       top[FPSTR(_parasite)] = parasite; | ||||
|       DEBUG_PRINTLN(F("Temperature config saved.")); | ||||
|     } | ||||
|   sprintf_P(buf, PSTR("%s Temperature"), serverDescription); | ||||
|   json[F("name")] = buf; | ||||
|   strcpy(buf, mqttDeviceTopic); | ||||
|   strcat_P(buf, PSTR("/temperature")); | ||||
|   json[F("state_topic")] = buf; | ||||
|   json[F("device_class")] = F("temperature"); | ||||
|   json[F("unique_id")] = escapedMac.c_str(); | ||||
|   json[F("unit_of_measurement")] = F("°C"); | ||||
|   payload_size = serializeJson(json, json_str); | ||||
|  | ||||
|     /** | ||||
|      * readFromConfig() is called before setup() to populate properties from values stored in cfg.json | ||||
|      * | ||||
|      * The function should return true if configuration was successfully loaded or false if there was no configuration. | ||||
|      */ | ||||
|     bool readFromConfig(JsonObject &root) { | ||||
|       // we look for JSON object: {"Temperature": {"pin": 0, "degC": true}} | ||||
|       int8_t newTemperaturePin = temperaturePin; | ||||
|       DEBUG_PRINT(FPSTR(_name)); | ||||
|   sprintf_P(buf, PSTR("homeassistant/sensor/%s/config"), escapedMac.c_str()); | ||||
|   mqtt->publish(buf, 0, true, json_str, payload_size); | ||||
|   HApublished = true; | ||||
| } | ||||
| #endif | ||||
|  | ||||
|       JsonObject top = root[FPSTR(_name)]; | ||||
|       if (top.isNull()) { | ||||
|         DEBUG_PRINTLN(F(": No config found. (Using defaults.)")); | ||||
|         return false; | ||||
|       } | ||||
|  | ||||
|       enabled           = top[FPSTR(_enabled)] | enabled; | ||||
|       newTemperaturePin = top["pin"] | newTemperaturePin; | ||||
|       degC              = top["degC"] | degC; | ||||
|       readingInterval   = top[FPSTR(_readInterval)] | readingInterval/1000; | ||||
|       readingInterval   = min(120,max(10,(int)readingInterval)) * 1000;  // convert to ms | ||||
|       parasite          = top[FPSTR(_parasite)] | parasite; | ||||
|  | ||||
|       if (!initDone) { | ||||
|         // first run: reading from cfg.json | ||||
|         temperaturePin = newTemperaturePin; | ||||
|         DEBUG_PRINTLN(F(" config loaded.")); | ||||
|       } else { | ||||
|         DEBUG_PRINTLN(F(" config (re)loaded.")); | ||||
|         // changing paramters from settings page | ||||
|         if (newTemperaturePin != temperaturePin) { | ||||
|           DEBUG_PRINTLN(F("Re-init temperature.")); | ||||
|           // deallocate pin and release memory | ||||
|           delete oneWire; | ||||
|           pinManager.deallocatePin(temperaturePin, PinOwner::UM_Temperature); | ||||
|           temperaturePin = newTemperaturePin; | ||||
|           // initialise | ||||
|           setup(); | ||||
| void UsermodTemperature::setup() { | ||||
|   int retries = 10; | ||||
|   sensorFound = 0; | ||||
|   temperature = -127.0f; // default to -127, DS18B20 only goes down to -50C | ||||
|   if (enabled) { | ||||
|     // config says we are enabled | ||||
|     DEBUG_PRINTLN(F("Allocating temperature pin...")); | ||||
|     // pin retrieved from cfg.json (readFromConfig()) prior to running setup() | ||||
|     if (temperaturePin >= 0 && pinManager.allocatePin(temperaturePin, true, PinOwner::UM_Temperature)) { | ||||
|       oneWire = new OneWire(temperaturePin); | ||||
|       if (oneWire->reset()) { | ||||
|         while (!findSensor() && retries--) { | ||||
|           delay(25); // try to find sensor | ||||
|         } | ||||
|       } | ||||
|       // use "return !top["newestParameter"].isNull();" when updating Usermod with new features | ||||
|       return !top[FPSTR(_parasite)].isNull(); | ||||
|       if (parasite && pinManager.allocatePin(parasitePin, true, PinOwner::UM_Temperature)) { | ||||
|         pinMode(parasitePin, OUTPUT); | ||||
|         digitalWrite(parasitePin, LOW); // deactivate power (close MOSFET) | ||||
|       } else { | ||||
|         parasitePin = -1; | ||||
|       } | ||||
|     } else { | ||||
|       if (temperaturePin >= 0) { | ||||
|         DEBUG_PRINTLN(F("Temperature pin allocation failed.")); | ||||
|       } | ||||
|       temperaturePin = -1;  // allocation failed | ||||
|     } | ||||
|   } | ||||
|   lastMeasurement = millis() - readingInterval + 10000; | ||||
|   initDone = true; | ||||
| } | ||||
|  | ||||
|     uint16_t getId() | ||||
|     { | ||||
|       return USERMOD_ID_TEMPERATURE; | ||||
| void UsermodTemperature::loop() { | ||||
|   if (!enabled || !sensorFound || strip.isUpdating()) return; | ||||
|  | ||||
|   static uint8_t errorCount = 0; | ||||
|   unsigned long now = millis(); | ||||
|  | ||||
|   // check to see if we are due for taking a measurement | ||||
|   // lastMeasurement will not be updated until the conversion | ||||
|   // is complete the the reading is finished | ||||
|   if (now - lastMeasurement < readingInterval) return; | ||||
|  | ||||
|   // we are due for a measurement, if we are not already waiting | ||||
|   // for a conversion to complete, then make a new request for temps | ||||
|   if (!waitingForConversion) { | ||||
|     requestTemperatures(); | ||||
|     return; | ||||
|   } | ||||
|  | ||||
|   // we were waiting for a conversion to complete, have we waited log enough? | ||||
|   if (now - lastTemperaturesRequest >= 750 /* 93.75ms per the datasheet but can be up to 750ms */) { | ||||
|     readTemperature(); | ||||
|     if (getTemperatureC() < -100.0f) { | ||||
|       if (++errorCount > 10) sensorFound = 0; | ||||
|       lastMeasurement = now - readingInterval + 300; // force new measurement in 300ms | ||||
|       return; | ||||
|     } | ||||
| }; | ||||
|     errorCount = 0; | ||||
|  | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|     if (WLED_MQTT_CONNECTED) { | ||||
|       char subuf[64]; | ||||
|       strcpy(subuf, mqttDeviceTopic); | ||||
|       if (temperature > -100.0f) { | ||||
|         // dont publish super low temperature as the graph will get messed up | ||||
|         // the DallasTemperature library returns -127C or -196.6F when problem | ||||
|         // reading the sensor | ||||
|         strcat_P(subuf, PSTR("/temperature")); | ||||
|         mqtt->publish(subuf, 0, false, String(getTemperatureC()).c_str()); | ||||
|         strcat_P(subuf, PSTR("_f")); | ||||
|         mqtt->publish(subuf, 0, false, String(getTemperatureF()).c_str()); | ||||
|       } else { | ||||
|         // publish something else to indicate status? | ||||
|       } | ||||
|     } | ||||
| #endif | ||||
|   } | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * connected() is called every time the WiFi is (re)connected | ||||
|  * Use it to initialize network interfaces | ||||
|  */ | ||||
| //void UsermodTemperature::connected() {} | ||||
|  | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
| /** | ||||
|  * subscribe to MQTT topic if needed | ||||
|  */ | ||||
| void UsermodTemperature::onMqttConnect(bool sessionPresent) { | ||||
|   //(re)subscribe to required topics | ||||
|   //char subuf[64]; | ||||
|   if (mqttDeviceTopic[0] != 0) { | ||||
|     publishHomeAssistantAutodiscovery(); | ||||
|   } | ||||
| } | ||||
| #endif | ||||
|  | ||||
| /* | ||||
|   * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. | ||||
|   * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. | ||||
|   * Below it is shown how this could be used for e.g. a light sensor | ||||
|   */ | ||||
| void UsermodTemperature::addToJsonInfo(JsonObject& root) { | ||||
|   // dont add temperature to info if we are disabled | ||||
|   if (!enabled) return; | ||||
|  | ||||
|   JsonObject user = root["u"]; | ||||
|   if (user.isNull()) user = root.createNestedObject("u"); | ||||
|  | ||||
|   JsonArray temp = user.createNestedArray(FPSTR(_name)); | ||||
|  | ||||
|   if (temperature <= -100.0f) { | ||||
|     temp.add(0); | ||||
|     temp.add(F(" Sensor Error!")); | ||||
|     return; | ||||
|   } | ||||
|  | ||||
|   temp.add(getTemperature()); | ||||
|   temp.add(getTemperatureUnit()); | ||||
|  | ||||
|   JsonObject sensor = root[F("sensor")]; | ||||
|   if (sensor.isNull()) sensor = root.createNestedObject(F("sensor")); | ||||
|   temp = sensor.createNestedArray(F("temperature")); | ||||
|   temp.add(getTemperature()); | ||||
|   temp.add(getTemperatureUnit()); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). | ||||
|  * Values in the state object may be modified by connected clients | ||||
|  */ | ||||
| //void UsermodTemperature::addToJsonState(JsonObject &root) | ||||
| //{ | ||||
| //} | ||||
|  | ||||
| /** | ||||
|  * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). | ||||
|  * Values in the state object may be modified by connected clients | ||||
|  * Read "<usermodname>_<usermodparam>" from json state and and change settings (i.e. GPIO pin) used. | ||||
|  */ | ||||
| //void UsermodTemperature::readFromJsonState(JsonObject &root) { | ||||
| //  if (!initDone) return;  // prevent crash on boot applyPreset() | ||||
| //} | ||||
|  | ||||
| /** | ||||
|  * addToConfig() (called from set.cpp) stores persistent properties to cfg.json | ||||
|  */ | ||||
| void UsermodTemperature::addToConfig(JsonObject &root) { | ||||
|   // we add JSON object: {"Temperature": {"pin": 0, "degC": true}} | ||||
|   JsonObject top = root.createNestedObject(FPSTR(_name)); // usermodname | ||||
|   top[FPSTR(_enabled)] = enabled; | ||||
|   top["pin"]  = temperaturePin;     // usermodparam | ||||
|   top["degC"] = degC;  // usermodparam | ||||
|   top[FPSTR(_readInterval)] = readingInterval / 1000; | ||||
|   top[FPSTR(_parasite)] = parasite; | ||||
|   top[FPSTR(_parasitePin)] = parasitePin; | ||||
|   DEBUG_PRINTLN(F("Temperature config saved.")); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * readFromConfig() is called before setup() to populate properties from values stored in cfg.json | ||||
|  * | ||||
|  * The function should return true if configuration was successfully loaded or false if there was no configuration. | ||||
|  */ | ||||
| bool UsermodTemperature::readFromConfig(JsonObject &root) { | ||||
|   // we look for JSON object: {"Temperature": {"pin": 0, "degC": true}} | ||||
|   int8_t newTemperaturePin = temperaturePin; | ||||
|   DEBUG_PRINT(FPSTR(_name)); | ||||
|  | ||||
|   JsonObject top = root[FPSTR(_name)]; | ||||
|   if (top.isNull()) { | ||||
|     DEBUG_PRINTLN(F(": No config found. (Using defaults.)")); | ||||
|     return false; | ||||
|   } | ||||
|  | ||||
|   enabled           = top[FPSTR(_enabled)] | enabled; | ||||
|   newTemperaturePin = top["pin"] | newTemperaturePin; | ||||
|   degC              = top["degC"] | degC; | ||||
|   readingInterval   = top[FPSTR(_readInterval)] | readingInterval/1000; | ||||
|   readingInterval   = min(120,max(10,(int)readingInterval)) * 1000;  // convert to ms | ||||
|   parasite          = top[FPSTR(_parasite)] | parasite; | ||||
|   parasitePin       = top[FPSTR(_parasitePin)] | parasitePin; | ||||
|  | ||||
|   if (!initDone) { | ||||
|     // first run: reading from cfg.json | ||||
|     temperaturePin = newTemperaturePin; | ||||
|     DEBUG_PRINTLN(F(" config loaded.")); | ||||
|   } else { | ||||
|     DEBUG_PRINTLN(F(" config (re)loaded.")); | ||||
|     // changing paramters from settings page | ||||
|     if (newTemperaturePin != temperaturePin) { | ||||
|       DEBUG_PRINTLN(F("Re-init temperature.")); | ||||
|       // deallocate pin and release memory | ||||
|       delete oneWire; | ||||
|       pinManager.deallocatePin(temperaturePin, PinOwner::UM_Temperature); | ||||
|       temperaturePin = newTemperaturePin; | ||||
|       pinManager.deallocatePin(parasitePin, PinOwner::UM_Temperature); | ||||
|       // initialise | ||||
|       setup(); | ||||
|     } | ||||
|   } | ||||
|   // use "return !top["newestParameter"].isNull();" when updating Usermod with new features | ||||
|   return !top[FPSTR(_parasitePin)].isNull(); | ||||
| } | ||||
|  | ||||
| void UsermodTemperature::appendConfigData() { | ||||
|   oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":")); oappend(String(FPSTR(_parasite)).c_str()); | ||||
|   oappend(SET_F("',1,'<i>(if no Vcc connected)</i>');"));  // 0 is field type, 1 is actual field | ||||
|   oappend(SET_F("addInfo('")); oappend(String(FPSTR(_name)).c_str()); oappend(SET_F(":")); oappend(String(FPSTR(_parasitePin)).c_str()); | ||||
|   oappend(SET_F("',1,'<i>(for external MOSFET)</i>');"));  // 0 is field type, 1 is actual field | ||||
| } | ||||
|  | ||||
| float UsermodTemperature::getTemperature() { | ||||
|   return degC ? getTemperatureC() : getTemperatureF(); | ||||
| } | ||||
|  | ||||
| const char *UsermodTemperature::getTemperatureUnit() { | ||||
|   return degC ? "°C" : "°F"; | ||||
| } | ||||
|  | ||||
| // strings to reduce flash memory usage (used more than twice) | ||||
| const char UsermodTemperature::_name[]         PROGMEM = "Temperature"; | ||||
| const char UsermodTemperature::_enabled[]      PROGMEM = "enabled"; | ||||
| const char UsermodTemperature::_readInterval[] PROGMEM = "read-interval-s"; | ||||
| const char UsermodTemperature::_parasite[]     PROGMEM = "parasite-pwr"; | ||||
| const char UsermodTemperature::_parasitePin[]  PROGMEM = "parasite-pwr-pin"; | ||||
|   | ||||
| @@ -1,31 +0,0 @@ | ||||
| #include "wled.h" | ||||
| /* | ||||
|  * Register your v2 usermods here! | ||||
|  */ | ||||
|  | ||||
| /* | ||||
|  * Add/uncomment your usermod filename here (and once more below) | ||||
|  * || || || | ||||
|  * \/ \/ \/ | ||||
|  */ | ||||
| //#include "usermod_v2_example.h" | ||||
| #ifdef USERMOD_DALLASTEMPERATURE | ||||
| #include "../usermods/Temperature/usermod_temperature.h" | ||||
| #endif | ||||
|  | ||||
| //#include "usermod_v2_empty.h" | ||||
|  | ||||
| void registerUsermods() | ||||
| { | ||||
|   /* | ||||
|    * Add your usermod class name here | ||||
|    * || || || | ||||
|    * \/ \/ \/ | ||||
|    */ | ||||
|   //usermods.add(new MyExampleUsermod()); | ||||
| #ifdef USERMOD_DALLASTEMPERATURE | ||||
|   usermods.add(new UsermodTemperature()); | ||||
| #endif | ||||
|  | ||||
|   //usermods.add(new UsermodRenameMe()); | ||||
| } | ||||
| @@ -50,9 +50,7 @@ class UsermodVL53L0XGestures : public Usermod { | ||||
|   public: | ||||
|  | ||||
|     void setup() { | ||||
|       PinManagerPinType pins[2] = { { i2c_scl, true }, { i2c_sda, true } }; | ||||
|       if (!pinManager.allocateMultiplePins(pins, 2, PinOwner::HW_I2C)) { enabled = false; return; } | ||||
|       Wire.begin(); | ||||
|       if (i2c_scl<0 || i2c_sda<0) { enabled = false; return; } | ||||
|  | ||||
|       sensor.setTimeout(150); | ||||
|       if (!sensor.init()) | ||||
|   | ||||
| @@ -34,30 +34,30 @@ uint8_t DALLAS_PIN =23; | ||||
| uint8_t SCL_PIN = 5; | ||||
| uint8_t SDA_PIN = 4; | ||||
| uint8_t DALLAS_PIN =13; | ||||
| // uint8_t RST_PIN = 16; // Uncoment for Heltec WiFi-Kit-8 | ||||
| // uint8_t RST_PIN = 16; // Un-comment for Heltec WiFi-Kit-8 | ||||
| #endif | ||||
|  | ||||
| //The SCL and SDA pins are defined here. | ||||
| //ESP8266 Wemos D1 mini board use SCL=5 SDA=4 while ESP32 Wemos32 mini board use SCL=22 SDA=21 | ||||
| #define U8X8_PIN_SCL SCL_PIN | ||||
| #define U8X8_PIN_SDA SDA_PIN | ||||
| //#define U8X8_PIN_RESET RST_PIN // Uncoment for Heltec WiFi-Kit-8 | ||||
| //#define U8X8_PIN_RESET RST_PIN // Un-comment for Heltec WiFi-Kit-8 | ||||
|  | ||||
| // Dallas sensor reading timer | ||||
| long temptimer = millis(); | ||||
| long lastMeasure = 0; | ||||
| #define Celsius // Show temperature mesaurement in Celcius otherwise is in Fahrenheit  | ||||
| #define Celsius // Show temperature measurement in Celsius otherwise is in Fahrenheit  | ||||
|  | ||||
| // If display does not work or looks corrupted check the | ||||
| // constructor reference: | ||||
| // https://github.com/olikraus/u8g2/wiki/u8x8setupcpp | ||||
| // or check the gallery: | ||||
| // https://github.com/olikraus/u8g2/wiki/gallery | ||||
| // --> First choise of cheap I2C OLED 128X32 0.91" | ||||
| // --> First choice of cheap I2C OLED 128X32 0.91" | ||||
| U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA | ||||
| // --> Second choise of cheap I2C OLED 128X64 0.96" or 1.3" | ||||
| // --> Second choice of cheap I2C OLED 128X64 0.96" or 1.3" | ||||
| //U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA | ||||
| // --> Third choise of Heltec WiFi-Kit-8 OLED 128X32 0.91" | ||||
| // --> Third choice of Heltec WiFi-Kit-8 OLED 128X32 0.91" | ||||
| //U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_RESET, U8X8_PIN_SCL, U8X8_PIN_SDA); // Constructor for Heltec WiFi-Kit-8 | ||||
| // gets called once at boot. Do all initialization that doesn't depend on network here | ||||
| void userSetup() { | ||||
| @@ -97,15 +97,16 @@ void userLoop() { | ||||
|  | ||||
| //----> Dallas temperature sensor MQTT publishing | ||||
|   temptimer = millis();   | ||||
| // Timer to publishe new temperature every 60 seconds | ||||
| // Timer to publish new temperature every 60 seconds | ||||
|   if (temptimer - lastMeasure > 60000)  | ||||
|   { | ||||
|     lastMeasure = temptimer;     | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
| //Check if MQTT Connected, otherwise it will crash the 8266 | ||||
|     if (mqtt != nullptr) | ||||
|     { | ||||
| //      Serial.println(Dallas(DALLAS_PIN,0)); | ||||
| //Gets prefered temperature scale based on selection in definitions section | ||||
| //Gets preferred temperature scale based on selection in definitions section | ||||
|         #ifdef Celsius | ||||
|         int16_t board_temperature = Dallas(DALLAS_PIN,0); | ||||
|         #else | ||||
| @@ -116,6 +117,7 @@ void userLoop() { | ||||
|         t += "/temperature"; | ||||
|         mqtt->publish(t.c_str(), 0, true, String(board_temperature).c_str()); | ||||
|     } | ||||
|   #endif | ||||
|   } | ||||
|  | ||||
|   // Check if we time interval for redrawing passes. | ||||
| @@ -171,11 +173,11 @@ void userLoop() { | ||||
|   // First row with Wifi name | ||||
|   u8x8.setCursor(1, 0); | ||||
|   u8x8.print(knownSsid.substring(0, u8x8.getCols() > 1 ? u8x8.getCols() - 2 : 0)); | ||||
|   // Print `~` char to indicate that SSID is longer, than owr dicplay | ||||
|   // Print `~` char to indicate that SSID is longer than our display | ||||
|   if (knownSsid.length() > u8x8.getCols()) | ||||
|     u8x8.print("~"); | ||||
|  | ||||
|   // Second row with IP or Psssword | ||||
|   // Second row with IP or Password | ||||
|   u8x8.setCursor(1, 1); | ||||
|   // Print password in AP mode and if led is OFF. | ||||
|   if (apActive && bri == 0) | ||||
|   | ||||
| @@ -6,7 +6,7 @@ | ||||
|  | ||||
| void UpdateBME280Data(); | ||||
|  | ||||
| #define Celsius // Show temperature mesaurement in Celcius otherwise is in Fahrenheit  | ||||
| #define Celsius // Show temperature measurement in Celsius otherwise is in Fahrenheit  | ||||
| BME280I2C bme;    // Default : forced mode, standby time = 1000 ms | ||||
|                   // Oversampling = pressure ×1, temperature ×1, humidity ×1, filter off, | ||||
|  | ||||
| @@ -16,25 +16,25 @@ uint8_t SDA_PIN = 21; | ||||
| #else //ESP8266 boards | ||||
| uint8_t SCL_PIN = 5; | ||||
| uint8_t SDA_PIN = 4; | ||||
| // uint8_t RST_PIN = 16; // Uncoment for Heltec WiFi-Kit-8 | ||||
| // uint8_t RST_PIN = 16; // Un-comment for Heltec WiFi-Kit-8 | ||||
| #endif | ||||
|  | ||||
| //The SCL and SDA pins are defined here. | ||||
| //ESP8266 Wemos D1 mini board use SCL=5 SDA=4 while ESP32 Wemos32 mini board use SCL=22 SDA=21 | ||||
| #define U8X8_PIN_SCL SCL_PIN | ||||
| #define U8X8_PIN_SDA SDA_PIN | ||||
| //#define U8X8_PIN_RESET RST_PIN // Uncoment for Heltec WiFi-Kit-8 | ||||
| //#define U8X8_PIN_RESET RST_PIN // Un-comment for Heltec WiFi-Kit-8 | ||||
|  | ||||
| // If display does not work or looks corrupted check the | ||||
| // constructor reference: | ||||
| // https://github.com/olikraus/u8g2/wiki/u8x8setupcpp | ||||
| // or check the gallery: | ||||
| // https://github.com/olikraus/u8g2/wiki/gallery | ||||
| // --> First choise of cheap I2C OLED 128X32 0.91" | ||||
| // --> First choice of cheap I2C OLED 128X32 0.91" | ||||
| U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA | ||||
| // --> Second choise of cheap I2C OLED 128X64 0.96" or 1.3" | ||||
| // --> Second choice of cheap I2C OLED 128X64 0.96" or 1.3" | ||||
| //U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(U8X8_PIN_NONE, U8X8_PIN_SCL, U8X8_PIN_SDA); // Pins are Reset, SCL, SDA | ||||
| // --> Third choise of Heltec WiFi-Kit-8 OLED 128X32 0.91" | ||||
| // --> Third choice of Heltec WiFi-Kit-8 OLED 128X32 0.91" | ||||
| //U8X8_SSD1306_128X32_UNIVISION_HW_I2C u8x8(U8X8_PIN_RESET, U8X8_PIN_SCL, U8X8_PIN_SDA); // Constructor for Heltec WiFi-Kit-8 | ||||
| // gets called once at boot. Do all initialization that doesn't depend on network here | ||||
|  | ||||
| @@ -103,6 +103,7 @@ void userLoop() { | ||||
|   { | ||||
|     lastMeasure = tempTimer;     | ||||
|  | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
| // Check if MQTT Connected, otherwise it will crash the 8266 | ||||
|     if (mqtt != nullptr) | ||||
|     { | ||||
| @@ -122,6 +123,7 @@ void userLoop() { | ||||
|       h += "/humidity"; | ||||
|       mqtt->publish(h.c_str(), 0, true, String(board_humidity).c_str()); | ||||
|     } | ||||
|   #endif | ||||
|   } | ||||
|  | ||||
|   // Check if we time interval for redrawing passes. | ||||
| @@ -177,11 +179,11 @@ void userLoop() { | ||||
|   // First row with Wifi name | ||||
|   u8x8.setCursor(1, 0); | ||||
|   u8x8.print(knownSsid.substring(0, u8x8.getCols() > 1 ? u8x8.getCols() - 2 : 0)); | ||||
|   // Print `~` char to indicate that SSID is longer, than owr dicplay | ||||
|   // Print `~` char to indicate that SSID is longer, than our display | ||||
|   if (knownSsid.length() > u8x8.getCols()) | ||||
|     u8x8.print("~"); | ||||
|  | ||||
|   // Second row with IP or Psssword | ||||
|   // Second row with IP or Password | ||||
|   u8x8.setCursor(1, 1); | ||||
|   // Print password in AP mode and if led is OFF. | ||||
|   if (apActive && bri == 0) | ||||
|   | ||||
| @@ -20,6 +20,12 @@ | ||||
|  * .... | ||||
|  */ | ||||
|  | ||||
| #if !defined(FFTTASK_PRIORITY) | ||||
| #define FFTTASK_PRIORITY 1 // standard: looptask prio | ||||
| //#define FFTTASK_PRIORITY 2 // above looptask, below asyc_tcp | ||||
| //#define FFTTASK_PRIORITY 4 // above asyc_tcp | ||||
| #endif | ||||
|  | ||||
| // Comment/Uncomment to toggle usb serial debugging | ||||
| // #define MIC_LOGGER                   // MIC sampling & sound input debugging (serial plotter) | ||||
| // #define FFT_SAMPLING_LOG             // FFT result debugging | ||||
| @@ -71,7 +77,7 @@ static bool limiterOn = true;                 // bool: enable / disable dynamics | ||||
| static uint16_t attackTime =  80;             // int: attack time in milliseconds. Default 0.08sec | ||||
| static uint16_t decayTime = 1400;             // int: decay time in milliseconds.  Default 1.40sec | ||||
| // user settable options for FFTResult scaling | ||||
| static uint8_t FFTScalingMode = 3;            // 0 none; 1 optimized logarithmic; 2 optimized linear; 3 optimized sqare root | ||||
| static uint8_t FFTScalingMode = 3;            // 0 none; 1 optimized logarithmic; 2 optimized linear; 3 optimized square root | ||||
|  | ||||
| //  | ||||
| // AGC presets | ||||
| @@ -104,11 +110,11 @@ static float    sampleAgc = 0.0f;               // Smoothed AGC sample | ||||
|  | ||||
| // peak detection | ||||
| static bool samplePeak = false;      // Boolean flag for peak - used in effects. Responding routine may reset this flag. Auto-reset after strip.getMinShowDelay() | ||||
| static uint8_t maxVol = 10;          // Reasonable value for constant volume for 'peak detector', as it won't always trigger (deprecated) | ||||
| static uint8_t maxVol = 31;          // Reasonable value for constant volume for 'peak detector', as it won't always trigger (deprecated) | ||||
| static uint8_t binNum = 8;           // Used to select the bin for FFT based beat detection  (deprecated) | ||||
| static bool udpSamplePeak = false;   // Boolean flag for peak. Set at the same tiem as samplePeak, but reset by transmitAudioData | ||||
| static bool udpSamplePeak = false;   // Boolean flag for peak. Set at the same time as samplePeak, but reset by transmitAudioData | ||||
| static unsigned long timeOfPeak = 0; // time of last sample peak detection. | ||||
| static void detectSamplePeak(void);  // peak detection function (needs scaled FFT reasults in vReal[]) | ||||
| static void detectSamplePeak(void);  // peak detection function (needs scaled FFT results in vReal[]) | ||||
| static void autoResetPeak(void);     // peak auto-reset function | ||||
|  | ||||
|  | ||||
| @@ -173,13 +179,18 @@ static float windowWeighingFactors[samplesFFT] = {0.0f}; | ||||
|  | ||||
| // Create FFT object | ||||
| #ifdef UM_AUDIOREACTIVE_USE_NEW_FFT | ||||
| // lib_deps += https://github.com/kosme/arduinoFFT#develop @ 1.9.2 | ||||
| #define FFT_SPEED_OVER_PRECISION     // enables use of reciprocals (1/x etc), and an a few other speedups | ||||
| #define FFT_SQRT_APPROXIMATION       // enables "quake3" style inverse sqrt | ||||
| #define sqrt(x) sqrtf(x)             // little hack that reduces FFT time by 50% on ESP32 (as alternative to FFT_SQRT_APPROXIMATION) | ||||
|   // lib_deps += https://github.com/kosme/arduinoFFT#develop @ 1.9.2 | ||||
|   // these options actually cause slow-downs on all esp32 processors, don't use them. | ||||
|   // #define FFT_SPEED_OVER_PRECISION     // enables use of reciprocals (1/x etc) - not faster on ESP32 | ||||
|   // #define FFT_SQRT_APPROXIMATION       // enables "quake3" style inverse sqrt  - slower on ESP32 | ||||
|   // Below options are forcing ArduinoFFT to use sqrtf() instead of sqrt() | ||||
|   #define sqrt(x) sqrtf(x)             // little hack that reduces FFT time by 10-50% on ESP32 | ||||
|   #define sqrt_internal sqrtf          // see https://github.com/kosme/arduinoFFT/pull/83 | ||||
| #else | ||||
| // lib_deps += https://github.com/blazoncek/arduinoFFT.git | ||||
|   // around 40% slower on -S2 | ||||
|   // lib_deps += https://github.com/blazoncek/arduinoFFT.git | ||||
| #endif | ||||
|  | ||||
| #include <arduinoFFT.h> | ||||
|  | ||||
| #ifdef UM_AUDIOREACTIVE_USE_NEW_FFT | ||||
| @@ -195,7 +206,7 @@ static float mapf(float x, float in_min, float in_max, float out_min, float out_ | ||||
|   return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; | ||||
| } | ||||
|  | ||||
| // compute average of several FFT resut bins | ||||
| // compute average of several FFT result bins | ||||
| static float fftAddAvg(int from, int to) { | ||||
|   float result = 0.0f; | ||||
|   for (int i = from; i <= to; i++) { | ||||
| @@ -313,7 +324,7 @@ void FFTcode(void * parameter) | ||||
|     * | ||||
|     * Andrew's updated mapping of 256 bins down to the 16 result bins with Sample Freq = 10240, samplesFFT = 512 and some overlap. | ||||
|     * Based on testing, the lowest/Start frequency is 60 Hz (with bin 3) and a highest/End frequency of 5120 Hz in bin 255. | ||||
|     * Now, Take the 60Hz and multiply by 1.320367784 to get the next frequency and so on until the end. Then detetermine the bins. | ||||
|     * Now, Take the 60Hz and multiply by 1.320367784 to get the next frequency and so on until the end. Then determine the bins. | ||||
|     * End frequency = Start frequency * multiplier ^ 16 | ||||
|     * Multiplier = (End frequency/ Start frequency) ^ 1/16 | ||||
|     * Multiplier = 1.320367784 | ||||
| @@ -372,7 +383,7 @@ void FFTcode(void * parameter) | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     // post-processing of frequency channels (pink noise adjustment, AGC, smooting, scaling) | ||||
|     // post-processing of frequency channels (pink noise adjustment, AGC, smoothing, scaling) | ||||
|     postProcessFFTResults((fabsf(sampleAvg) > 0.25f)? true : false , NUM_GEQ_CHANNELS); | ||||
|  | ||||
| #if defined(WLED_DEBUG) || defined(SR_DEBUG) | ||||
| @@ -411,7 +422,7 @@ static void runMicFilter(uint16_t numSamples, float *sampleBuffer)          // p | ||||
|   //constexpr float beta1 = 0.8285f; // 18Khz | ||||
|   constexpr float beta1 = 0.85f;  // 20Khz | ||||
|  | ||||
|   constexpr float beta2 = (1.0f - beta1) / 2.0; | ||||
|   constexpr float beta2 = (1.0f - beta1) / 2.0f; | ||||
|   static float last_vals[2] = { 0.0f }; // FIR high freq cutoff filter | ||||
|   static float lowfilt = 0.0f;          // IIR low frequency cutoff filter | ||||
|  | ||||
| @@ -419,7 +430,7 @@ static void runMicFilter(uint16_t numSamples, float *sampleBuffer)          // p | ||||
|         // FIR lowpass, to remove high frequency noise | ||||
|         float highFilteredSample; | ||||
|         if (i < (numSamples-1)) highFilteredSample = beta1*sampleBuffer[i] + beta2*last_vals[0] + beta2*sampleBuffer[i+1];  // smooth out spikes | ||||
|         else highFilteredSample = beta1*sampleBuffer[i] + beta2*last_vals[0]  + beta2*last_vals[1];                  // spcial handling for last sample in array | ||||
|         else highFilteredSample = beta1*sampleBuffer[i] + beta2*last_vals[0]  + beta2*last_vals[1];                  // special handling for last sample in array | ||||
|         last_vals[1] = last_vals[0]; | ||||
|         last_vals[0] = sampleBuffer[i]; | ||||
|         sampleBuffer[i] = highFilteredSample; | ||||
| @@ -464,17 +475,17 @@ static void postProcessFFTResults(bool noiseGateOpen, int numberOfChannels) // p | ||||
|       switch (FFTScalingMode) { | ||||
|         case 1: | ||||
|             // Logarithmic scaling | ||||
|             currentResult *= 0.42;                      // 42 is the answer ;-) | ||||
|             currentResult -= 8.0;                       // this skips the lowest row, giving some room for peaks | ||||
|             if (currentResult > 1.0) currentResult = logf(currentResult); // log to base "e", which is the fastest log() function | ||||
|             else currentResult = 0.0;                   // special handling, because log(1) = 0; log(0) = undefined | ||||
|             currentResult *= 0.42f;                      // 42 is the answer ;-) | ||||
|             currentResult -= 8.0f;                       // this skips the lowest row, giving some room for peaks | ||||
|             if (currentResult > 1.0f) currentResult = logf(currentResult); // log to base "e", which is the fastest log() function | ||||
|             else currentResult = 0.0f;                   // special handling, because log(1) = 0; log(0) = undefined | ||||
|             currentResult *= 0.85f + (float(i)/18.0f);  // extra up-scaling for high frequencies | ||||
|             currentResult = mapf(currentResult, 0, LOG_256, 0, 255); // map [log(1) ... log(255)] to [0 ... 255] | ||||
|         break; | ||||
|         case 2: | ||||
|             // Linear scaling | ||||
|             currentResult *= 0.30f;                     // needs a bit more damping, get stay below 255 | ||||
|             currentResult -= 4.0;                       // giving a bit more room for peaks | ||||
|             currentResult -= 4.0f;                       // giving a bit more room for peaks | ||||
|             if (currentResult < 1.0f) currentResult = 0.0f; | ||||
|             currentResult *= 0.85f + (float(i)/1.8f);   // extra up-scaling for high frequencies | ||||
|         break; | ||||
| @@ -482,8 +493,8 @@ static void postProcessFFTResults(bool noiseGateOpen, int numberOfChannels) // p | ||||
|             // square root scaling | ||||
|             currentResult *= 0.38f; | ||||
|             currentResult -= 6.0f; | ||||
|             if (currentResult > 1.0) currentResult = sqrtf(currentResult); | ||||
|             else currentResult = 0.0;                   // special handling, because sqrt(0) = undefined | ||||
|             if (currentResult > 1.0f) currentResult = sqrtf(currentResult); | ||||
|             else currentResult = 0.0f;                   // special handling, because sqrt(0) = undefined | ||||
|             currentResult *= 0.85f + (float(i)/4.5f);   // extra up-scaling for high frequencies | ||||
|             currentResult = mapf(currentResult, 0.0, 16.0, 0.0, 255.0); // map [sqrt(1) ... sqrt(256)] to [0 ... 255] | ||||
|         break; | ||||
| @@ -511,11 +522,11 @@ static void postProcessFFTResults(bool noiseGateOpen, int numberOfChannels) // p | ||||
| // peak detection is called from FFT task when vReal[] contains valid FFT results | ||||
| static void detectSamplePeak(void) { | ||||
|   bool havePeak = false; | ||||
|  | ||||
|   // softhack007: this code continuously triggers while amplitude in the selected bin is above a certain threshold. So it does not detect peaks - it detects high activity in a frequency bin. | ||||
|   // Poor man's beat detection by seeing if sample > Average + some value. | ||||
|   // This goes through ALL of the 255 bins - but ignores stupid settings | ||||
|   // Then we got a peak, else we don't. The peak has to time out on its own in order to support UDP sound sync. | ||||
|   if ((sampleAvg > 1) && (maxVol > 0) && (binNum > 1) && (vReal[binNum] > maxVol) && ((millis() - timeOfPeak) > 100)) { | ||||
|   if ((sampleAvg > 1) && (maxVol > 0) && (binNum > 4) && (vReal[binNum] > maxVol) && ((millis() - timeOfPeak) > 100)) { | ||||
|     havePeak = true; | ||||
|   } | ||||
|  | ||||
| @@ -569,16 +580,6 @@ class AudioReactive : public Usermod { | ||||
|     #else | ||||
|     int8_t i2sckPin = I2S_CKPIN; | ||||
|     #endif | ||||
|     #ifndef ES7243_SDAPIN | ||||
|     int8_t sdaPin = -1; | ||||
|     #else | ||||
|     int8_t sdaPin = ES7243_SDAPIN; | ||||
|     #endif | ||||
|     #ifndef ES7243_SCLPIN | ||||
|     int8_t sclPin = -1; | ||||
|     #else | ||||
|     int8_t sclPin = ES7243_SCLPIN; | ||||
|     #endif | ||||
|     #ifndef MCLK_PIN | ||||
|     int8_t mclkPin = I2S_PIN_NO_CHANGE;  /* ESP32: only -1, 0, 1, 3 allowed*/ | ||||
|     #else | ||||
| @@ -626,7 +627,7 @@ class AudioReactive : public Usermod { | ||||
|  | ||||
|     // variables used by getSample() and agcAvg() | ||||
|     int16_t  micIn = 0;           // Current sample starts with negative values and large values, which is why it's 16 bit signed | ||||
|     double   sampleMax = 0.0;     // Max sample over a few seconds. Needed for AGC controler. | ||||
|     double   sampleMax = 0.0;     // Max sample over a few seconds. Needed for AGC controller. | ||||
|     double   micLev = 0.0;        // Used to convert returned value to have '0' as minimum. A leveller | ||||
|     float    expAdjF = 0.0f;      // Used for exponential filter. | ||||
|     float    sampleReal = 0.0f;	  // "sampleRaw" as float, to provide bits that are lost otherwise (before amplification by sampleGain or inputLevel). Needed for AGC. | ||||
| @@ -744,13 +745,13 @@ class AudioReactive : public Usermod { | ||||
|     * 2. we use two setpoints, one at ~60%, and one at ~80% of the maximum signal | ||||
|     * 3. the amplification depends on signal level: | ||||
|     *    a) normal zone - very slow adjustment | ||||
|     *    b) emergency zome (<10% or >90%) - very fast adjustment | ||||
|     *    b) emergency zone (<10% or >90%) - very fast adjustment | ||||
|     */ | ||||
|     void agcAvg(unsigned long the_time) | ||||
|     { | ||||
|       const int AGC_preset = (soundAgc > 0)? (soundAgc-1): 0; // make sure the _compiler_ knows this value will not change while we are inside the function | ||||
|  | ||||
|       float lastMultAgc = multAgc;      // last muliplier used | ||||
|       float lastMultAgc = multAgc;      // last multiplier used | ||||
|       float multAgcTemp = multAgc;      // new multiplier | ||||
|       float tmpAgc = sampleReal * multAgc;        // what-if amplified signal | ||||
|  | ||||
| @@ -768,7 +769,7 @@ class AudioReactive : public Usermod { | ||||
|       if (time_now - last_time > 2)  { | ||||
|         last_time = time_now; | ||||
|  | ||||
|         if((fabsf(sampleReal) < 2.0f) || (sampleMax < 1.0f)) { | ||||
|         if((fabsf(sampleReal) < 2.0f) || (sampleMax < 1.0)) { | ||||
|           // MIC signal is "squelched" - deliver silence | ||||
|           tmpAgc = 0; | ||||
|           // we need to "spin down" the intgrated error buffer | ||||
| @@ -790,13 +791,13 @@ class AudioReactive : public Usermod { | ||||
|          | ||||
|         if (((multAgcTemp > 0.085f) && (multAgcTemp < 6.5f))    //integrator anti-windup by clamping | ||||
|             && (multAgc*sampleMax < agcZoneStop[AGC_preset]))   //integrator ceiling (>140% of max) | ||||
|           control_integrated += control_error * 0.002 * 0.25;   // 2ms = intgration time; 0.25 for damping | ||||
|           control_integrated += control_error * 0.002 * 0.25;   // 2ms = integration time; 0.25 for damping | ||||
|         else | ||||
|           control_integrated *= 0.9;                            // spin down that beasty integrator | ||||
|  | ||||
|         // apply PI Control  | ||||
|         tmpAgc = sampleReal * lastMultAgc;                      // check "zone" of the signal using previous gain | ||||
|         if ((tmpAgc > agcZoneHigh[AGC_preset]) || (tmpAgc < soundSquelch + agcZoneLow[AGC_preset])) {  // upper/lower emergy zone | ||||
|         if ((tmpAgc > agcZoneHigh[AGC_preset]) || (tmpAgc < soundSquelch + agcZoneLow[AGC_preset])) {  // upper/lower energy zone | ||||
|           multAgcTemp = lastMultAgc + agcFollowFast[AGC_preset] * agcControlKp[AGC_preset] * control_error; | ||||
|           multAgcTemp += agcFollowFast[AGC_preset] * agcControlKi[AGC_preset] * control_integrated; | ||||
|         } else {                                                                         // "normal zone" | ||||
| @@ -804,7 +805,7 @@ class AudioReactive : public Usermod { | ||||
|           multAgcTemp += agcFollowSlow[AGC_preset] * agcControlKi[AGC_preset] * control_integrated; | ||||
|         } | ||||
|  | ||||
|         // limit amplification again - PI controler sometimes "overshoots" | ||||
|         // limit amplification again - PI controller sometimes "overshoots" | ||||
|         //multAgcTemp = constrain(multAgcTemp, 0.015625f, 32.0f); // 1/64 < multAgcTemp < 32 | ||||
|         if (multAgcTemp > 32.0f)      multAgcTemp = 32.0f; | ||||
|         if (multAgcTemp < 1.0f/64.0f) multAgcTemp = 1.0f/64.0f; | ||||
| @@ -834,7 +835,7 @@ class AudioReactive : public Usermod { | ||||
|     void getSample() | ||||
|     { | ||||
|       float    sampleAdj;           // Gain adjusted sample value | ||||
|       float    tmpSample;           // An interim sample variable used for calculatioins. | ||||
|       float    tmpSample;           // An interim sample variable used for calculations. | ||||
|       const float weighting = 0.2f; // Exponential filter weighting. Will be adjustable in a future release. | ||||
|       const int   AGC_preset = (soundAgc > 0)? (soundAgc-1): 0; // make sure the _compiler_ knows this value will not change while we are inside the function | ||||
|  | ||||
| @@ -883,8 +884,8 @@ class AudioReactive : public Usermod { | ||||
|       // keep "peak" sample, but decay value if current sample is below peak | ||||
|       if ((sampleMax < sampleReal) && (sampleReal > 0.5f)) { | ||||
|         sampleMax = sampleMax + 0.5f * (sampleReal - sampleMax);  // new peak - with some filtering | ||||
|         // another simple way to detect samplePeak | ||||
|         if ((binNum < 10) && (millis() - timeOfPeak > 80) && (sampleAvg > 1)) { | ||||
|         // another simple way to detect samplePeak - cannot detect beats, but reacts on peak volume | ||||
|         if (((binNum < 12) || ((maxVol < 1))) && (millis() - timeOfPeak > 80) && (sampleAvg > 1)) { | ||||
|           samplePeak    = true; | ||||
|           timeOfPeak    = millis(); | ||||
|           udpSamplePeak = true; | ||||
| @@ -959,6 +960,8 @@ class AudioReactive : public Usermod { | ||||
|       //DEBUGSR_PRINTLN("Transmitting UDP Mic Packet"); | ||||
|  | ||||
|       audioSyncPacket transmitData; | ||||
|       memset(reinterpret_cast<void *>(&transmitData), 0, sizeof(transmitData)); // make sure that the packet - including "invisible" padding bytes added by the compiler - is fully initialized | ||||
|  | ||||
|       strncpy_P(transmitData.header, PSTR(UDP_SYNC_HEADER), 6); | ||||
|       // transmit samples that were not modified by limitSampleDynamics() | ||||
|       transmitData.sampleRaw   = (soundAgc) ? rawSampleAgc: sampleRaw; | ||||
| @@ -974,9 +977,10 @@ class AudioReactive : public Usermod { | ||||
|       transmitData.FFT_Magnitude = my_magnitude; | ||||
|       transmitData.FFT_MajorPeak = FFT_MajorPeak; | ||||
|  | ||||
|       fftUdp.beginMulticastPacket(); | ||||
|       fftUdp.write(reinterpret_cast<uint8_t *>(&transmitData), sizeof(transmitData)); | ||||
|       fftUdp.endPacket(); | ||||
|       if (fftUdp.beginMulticastPacket() != 0) { // beginMulticastPacket returns 0 in case of error | ||||
|         fftUdp.write(reinterpret_cast<uint8_t *>(&transmitData), sizeof(transmitData)); | ||||
|         fftUdp.endPacket(); | ||||
|       } | ||||
|       return; | ||||
|     } // transmitAudioData() | ||||
|  | ||||
| @@ -1136,7 +1140,7 @@ class AudioReactive : public Usermod { | ||||
|           DEBUGSR_PRINTLN(F("AR: ES7243 Microphone (right channel only).")); | ||||
|           audioSource = new ES7243(SAMPLE_RATE, BLOCK_SIZE); | ||||
|           delay(100); | ||||
|           if (audioSource) audioSource->initialize(sdaPin, sclPin, i2swsPin, i2ssdPin, i2sckPin, mclkPin); | ||||
|           if (audioSource) audioSource->initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin); | ||||
|           break; | ||||
|         case 3: | ||||
|           DEBUGSR_PRINT(F("AR: SPH0645 Microphone - ")); DEBUGSR_PRINTLN(F(I2S_MIC_CHANNEL_TEXT)); | ||||
| @@ -1159,6 +1163,13 @@ class AudioReactive : public Usermod { | ||||
|           if (audioSource) audioSource->initialize(i2swsPin, i2ssdPin); | ||||
|           break; | ||||
|         #endif | ||||
|         case 6: | ||||
|           DEBUGSR_PRINTLN(F("AR: ES8388 Source")); | ||||
|           audioSource = new ES8388Source(SAMPLE_RATE, BLOCK_SIZE); | ||||
|           delay(100); | ||||
|           if (audioSource) audioSource->initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin); | ||||
|           break; | ||||
|  | ||||
|         #if  !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3) | ||||
|         // ADC over I2S is only possible on "classic" ESP32 | ||||
|         case 0: | ||||
| @@ -1166,6 +1177,7 @@ class AudioReactive : public Usermod { | ||||
|           DEBUGSR_PRINTLN(F("AR: Analog Microphone (left channel only).")); | ||||
|           audioSource = new I2SAdcSource(SAMPLE_RATE, BLOCK_SIZE); | ||||
|           delay(100); | ||||
|           useBandPassFilter = true;  // PDM bandpass filter seems to help for bad quality analog | ||||
|           if (audioSource) audioSource->initialize(audioPin); | ||||
|           break; | ||||
|         #endif | ||||
| @@ -1275,9 +1287,10 @@ class AudioReactive : public Usermod { | ||||
|  | ||||
|         #ifdef WLED_DEBUG | ||||
|           // complain when audio userloop has been delayed for long time. Currently we need userloop running between 500 and 1500 times per second.  | ||||
|           if ((userloopDelay > 23) && !disableSoundProcessing && (audioSyncEnabled == 0)) { | ||||
|             DEBUG_PRINTF("[AR userLoop] hickup detected -> was inactive for last %d millis!\n", userloopDelay); | ||||
|           } | ||||
|           // softhack007 disabled temporarily - avoid serial console spam with MANY leds and low FPS | ||||
|           //if ((userloopDelay > 65) && !disableSoundProcessing && (audioSyncEnabled == 0)) { | ||||
|             //DEBUG_PRINTF("[AR userLoop] hiccup detected -> was inactive for last %d millis!\n", userloopDelay); | ||||
|           //} | ||||
|         #endif | ||||
|  | ||||
|         // run filters, and repeat in case of loop delays (hick-up compensation) | ||||
| @@ -1314,6 +1327,9 @@ class AudioReactive : public Usermod { | ||||
|           if (millis() - lastTime > delayMs) { | ||||
|             have_new_sample = receiveAudioData(); | ||||
|             if (have_new_sample) last_UDPTime = millis(); | ||||
| #ifdef ARDUINO_ARCH_ESP32 | ||||
|             else fftUdp.flush(); // Flush udp input buffers if we haven't read it - avoids hickups in receive mode. Does not work on 8266. | ||||
| #endif | ||||
|             lastTime = millis(); | ||||
|           } | ||||
|           if (have_new_sample) syncVolumeSmth = volumeSmth;   // remember received sample | ||||
| @@ -1332,7 +1348,7 @@ class AudioReactive : public Usermod { | ||||
|       // Info Page: keep max sample from last 5 seconds | ||||
|       if ((millis() -  sampleMaxTimer) > CYCLE_SAMPLEMAX) { | ||||
|         sampleMaxTimer = millis(); | ||||
|         maxSample5sec = (0.15 * maxSample5sec) + 0.85 *((soundAgc) ? sampleAgc : sampleAvg); // reset, and start with some smoothing | ||||
|         maxSample5sec = (0.15f * maxSample5sec) + 0.85f *((soundAgc) ? sampleAgc : sampleAvg); // reset, and start with some smoothing | ||||
|         if (sampleAvg < 1) maxSample5sec = 0; // noise gate  | ||||
|       } else { | ||||
|          if ((sampleAvg >= 1)) maxSample5sec = fmaxf(maxSample5sec, (soundAgc) ? rawSampleAgc : sampleRaw); // follow maximum volume | ||||
| @@ -1376,10 +1392,11 @@ class AudioReactive : public Usermod { | ||||
|       memset(fftAvg, 0, sizeof(fftAvg));  | ||||
|       memset(fftResult, 0, sizeof(fftResult));  | ||||
|       for(int i=(init?0:1); i<NUM_GEQ_CHANNELS; i+=2) fftResult[i] = 16; // make a tiny pattern | ||||
|       inputLevel = 128;                                    // resset level slider to default | ||||
|       inputLevel = 128;                                    // reset level slider to default | ||||
|       autoResetPeak(); | ||||
|  | ||||
|       if (init && FFT_Task) { | ||||
|         delay(25);                // give some time for I2S driver to finish sampling before we suspend it | ||||
|         vTaskSuspend(FFT_Task);   // update is about to begin, disable task to prevent crash | ||||
|         if (udpSyncConnected) {   // close UDP sync connection (if open) | ||||
|           udpSyncConnected = false; | ||||
| @@ -1391,15 +1408,14 @@ class AudioReactive : public Usermod { | ||||
|           vTaskResume(FFT_Task); | ||||
|           connected(); // resume UDP | ||||
|         } else | ||||
| //          xTaskCreatePinnedToCore( | ||||
|           xTaskCreate(                        // no need to "pin" this task to core #0 | ||||
|           xTaskCreateUniversal(               // xTaskCreateUniversal also works on -S2 and -C3 with single core | ||||
|             FFTcode,                          // Function to implement the task | ||||
|             "FFT",                            // Name of the task | ||||
|             5000,                             // Stack size in words | ||||
|             3592,                             // Stack size in words // 3592 leaves 800-1024 bytes of task stack free | ||||
|             NULL,                             // Task input parameter | ||||
|             1,                                // Priority of the task | ||||
|             FFTTASK_PRIORITY,                 // Priority of the task | ||||
|             &FFT_Task                         // Task handle | ||||
| //            , 0                                 // Core where the task should run | ||||
|             , 0                               // Core where the task should run | ||||
|           ); | ||||
|       } | ||||
|       micDataReal = 0.0f;                     // just to be sure | ||||
| @@ -1489,14 +1505,14 @@ class AudioReactive : public Usermod { | ||||
|         } else { | ||||
|           // Analog or I2S digital input | ||||
|           if (audioSource && (audioSource->isInitialized())) { | ||||
|             // audio source sucessfully configured | ||||
|             // audio source successfully configured | ||||
|             if (audioSource->getType() == AudioSource::Type_I2SAdc) { | ||||
|               infoArr.add(F("ADC analog")); | ||||
|             } else { | ||||
|               infoArr.add(F("I2S digital")); | ||||
|             } | ||||
|             // input level or "silence" | ||||
|             if (maxSample5sec > 1.0) { | ||||
|             if (maxSample5sec > 1.0f) { | ||||
|               float my_usage = 100.0f * (maxSample5sec / 255.0f); | ||||
|               snprintf_P(myStringBuffer, 15, PSTR(" - peak %3d%%"), int(my_usage)); | ||||
|               infoArr.add(myStringBuffer); | ||||
| @@ -1506,7 +1522,7 @@ class AudioReactive : public Usermod { | ||||
|           } else { | ||||
|             // error during audio source setup | ||||
|             infoArr.add(F("not initialized")); | ||||
|             infoArr.add(F(" - check GPIO config")); | ||||
|             infoArr.add(F(" - check pin settings")); | ||||
|           } | ||||
|         } | ||||
|  | ||||
| @@ -1657,8 +1673,6 @@ class AudioReactive : public Usermod { | ||||
|       pinArray.add(i2swsPin); | ||||
|       pinArray.add(i2sckPin); | ||||
|       pinArray.add(mclkPin); | ||||
|       pinArray.add(sdaPin); | ||||
|       pinArray.add(sclPin); | ||||
|  | ||||
|       JsonObject cfg = top.createNestedObject("config"); | ||||
|       cfg[F("squelch")] = soundSquelch; | ||||
| @@ -1719,8 +1733,6 @@ class AudioReactive : public Usermod { | ||||
|       configComplete &= getJsonValue(top[FPSTR(_digitalmic)]["pin"][1], i2swsPin); | ||||
|       configComplete &= getJsonValue(top[FPSTR(_digitalmic)]["pin"][2], i2sckPin); | ||||
|       configComplete &= getJsonValue(top[FPSTR(_digitalmic)]["pin"][3], mclkPin); | ||||
|       configComplete &= getJsonValue(top[FPSTR(_digitalmic)]["pin"][4], sdaPin); | ||||
|       configComplete &= getJsonValue(top[FPSTR(_digitalmic)]["pin"][5], sclPin); | ||||
|  | ||||
|       configComplete &= getJsonValue(top["config"][F("squelch")], soundSquelch); | ||||
|       configComplete &= getJsonValue(top["config"][F("gain")],    sampleGain); | ||||
| @@ -1752,6 +1764,8 @@ class AudioReactive : public Usermod { | ||||
|     #if  !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) | ||||
|       oappend(SET_F("addOption(dd,'Generic I2S PDM',5);")); | ||||
|     #endif | ||||
|     oappend(SET_F("addOption(dd,'ES8388',6);")); | ||||
|      | ||||
|       oappend(SET_F("dd=addDropdown('AudioReactive','config:AGC');")); | ||||
|       oappend(SET_F("addOption(dd,'Off',0);")); | ||||
|       oappend(SET_F("addOption(dd,'Normal',1);")); | ||||
| @@ -1784,8 +1798,6 @@ class AudioReactive : public Usermod { | ||||
|       #else | ||||
|         oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',3,'<i>master clock</i>','I2S MCLK');")); | ||||
|       #endif | ||||
|       oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',4,'','I2C SDA');")); | ||||
|       oappend(SET_F("addInfo('AudioReactive:digitalmic:pin[]',5,'','I2C SCL');")); | ||||
|     } | ||||
|  | ||||
|  | ||||
| @@ -1814,7 +1826,9 @@ class AudioReactive : public Usermod { | ||||
| const char AudioReactive::_name[]       PROGMEM = "AudioReactive"; | ||||
| const char AudioReactive::_enabled[]    PROGMEM = "enabled"; | ||||
| const char AudioReactive::_inputLvl[]   PROGMEM = "inputLevel"; | ||||
| #if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3) | ||||
| const char AudioReactive::_analogmic[]  PROGMEM = "analogmic"; | ||||
| #endif | ||||
| const char AudioReactive::_digitalmic[] PROGMEM = "digitalmic"; | ||||
| const char AudioReactive::UDP_SYNC_HEADER[]    PROGMEM = "00002"; // new sync header version, as format no longer compatible with previous structure | ||||
| const char AudioReactive::UDP_SYNC_HEADER_v1[] PROGMEM = "00001"; // old sync header version - need to add backwards-compatibility feature | ||||
|   | ||||
| @@ -1,6 +1,5 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include <Wire.h> | ||||
| #ifdef ARDUINO_ARCH_ESP32 | ||||
| #include "wled.h" | ||||
| #include <driver/i2s.h> | ||||
| #include <driver/adc.h> | ||||
| @@ -23,14 +22,14 @@ | ||||
|  | ||||
| // see https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/hw-reference/chip-series-comparison.html#related-documents | ||||
| // and https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/api-reference/peripherals/i2s.html#overview-of-all-modes | ||||
| #if defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(ESP8266) || defined(ESP8265) | ||||
| #if defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(ESP8266) || defined(ESP8265) | ||||
|   // there are two things in these MCUs that could lead to problems with audio processing: | ||||
|   // * no floating point hardware (FPU) support - FFT uses float calculations. If done in software, a strong slow-down can be expected (between 8x and 20x) | ||||
|   // * single core, so FFT task might slow down other things like LED updates | ||||
|   #if !defined(SOC_I2S_NUM) || (SOC_I2S_NUM < 1) | ||||
|   #error This audio reactive usermod does not support ESP32-C2, ESP32-C3 or ESP32-S2. | ||||
|   #error This audio reactive usermod does not support ESP32-C2 or ESP32-C3. | ||||
|   #else | ||||
|   #warning This audio reactive usermod does not support ESP32-C2, ESP32-C3 or ESP32-S2. | ||||
|   #warning This audio reactive usermod does not support ESP32-C2 and ESP32-C3. | ||||
|   #endif | ||||
| #endif | ||||
|  | ||||
| @@ -45,7 +44,7 @@ | ||||
| // benefit: analog mic inputs will be sampled contiously -> better response times and less "glitches" | ||||
| // WARNING: this option WILL lock-up your device in case that any other analogRead() operation is performed;  | ||||
| //          for example if you want to read "analog buttons" | ||||
| //#define I2S_GRAB_ADC1_COMPLETELY // (experimental) continously sample analog ADC microphone. WARNING will cause analogRead() lock-up | ||||
| //#define I2S_GRAB_ADC1_COMPLETELY // (experimental) continuously sample analog ADC microphone. WARNING will cause analogRead() lock-up | ||||
|  | ||||
| // data type requested from the I2S driver - currently we always use 32bit | ||||
| //#define I2S_USE_16BIT_SAMPLES   // (experimental) define this to request 16bit - more efficient but possibly less compatible | ||||
| @@ -72,7 +71,7 @@ | ||||
|  * if you want to receive two channels, one is the actual data from microphone and another channel is suppose to receive 0, it's different data in two channels, you need to choose I2S_CHANNEL_FMT_RIGHT_LEFT in this case. | ||||
| */ | ||||
|  | ||||
| #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)) && (ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(4, 4, 3)) | ||||
| #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)) && (ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(4, 4, 4)) | ||||
| // espressif bug: only_left has no sound, left and right are swapped  | ||||
| // https://github.com/espressif/esp-idf/issues/9635  I2S mic not working since 4.4 (IDFGH-8138) | ||||
| // https://github.com/espressif/esp-idf/issues/8538  I2S channel selection issue? (IDFGH-6918) | ||||
| @@ -123,7 +122,7 @@ class AudioSource { | ||||
|        This function needs to take care of anything that needs to be done | ||||
|        before samples can be obtained from the microphone. | ||||
|     */ | ||||
|     virtual void initialize(int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE) = 0; | ||||
|     virtual void initialize(int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE) = 0; | ||||
|  | ||||
|     /* Deinitialize | ||||
|        Release all resources and deactivate any functionality that is used | ||||
| @@ -192,7 +191,8 @@ class I2SSource : public AudioSource { | ||||
|       }; | ||||
|     } | ||||
|  | ||||
|     virtual void initialize(int8_t i2swsPin = I2S_PIN_NO_CHANGE, int8_t i2ssdPin = I2S_PIN_NO_CHANGE, int8_t i2sckPin = I2S_PIN_NO_CHANGE, int8_t mclkPin = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE) { | ||||
|     virtual void initialize(int8_t i2swsPin = I2S_PIN_NO_CHANGE, int8_t i2ssdPin = I2S_PIN_NO_CHANGE, int8_t i2sckPin = I2S_PIN_NO_CHANGE, int8_t mclkPin = I2S_PIN_NO_CHANGE) { | ||||
|       DEBUGSR_PRINTLN("I2SSource:: initialize()."); | ||||
|       if (i2swsPin != I2S_PIN_NO_CHANGE && i2ssdPin != I2S_PIN_NO_CHANGE) { | ||||
|         if (!pinManager.allocatePin(i2swsPin, true, PinOwner::UM_Audioreactive) || | ||||
|             !pinManager.allocatePin(i2ssdPin, false, PinOwner::UM_Audioreactive)) { // #206 | ||||
| @@ -378,26 +378,17 @@ class I2SSource : public AudioSource { | ||||
| }; | ||||
|  | ||||
| /* ES7243 Microphone | ||||
|    This is an I2S microphone that requires ininitialization over | ||||
|    This is an I2S microphone that requires initialization over | ||||
|    I2C before I2S data can be received | ||||
| */ | ||||
| class ES7243 : public I2SSource { | ||||
|   private: | ||||
|     // I2C initialization functions for ES7243 | ||||
|     void _es7243I2cBegin() { | ||||
|       bool i2c_initialized = Wire.begin(pin_ES7243_SDA, pin_ES7243_SCL, 100000U); | ||||
|       if (i2c_initialized == false) { | ||||
|         DEBUGSR_PRINTLN(F("AR: ES7243 failed to initialize I2C bus driver.")); | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     void _es7243I2cWrite(uint8_t reg, uint8_t val) { | ||||
| #ifndef ES7243_ADDR | ||||
|       Wire.beginTransmission(0x13); | ||||
|       #define ES7243_ADDR 0x13   // default address | ||||
| #else | ||||
|       #ifndef ES7243_ADDR | ||||
|         #define ES7243_ADDR 0x13   // default address | ||||
|       #endif | ||||
|       Wire.beginTransmission(ES7243_ADDR); | ||||
| #endif | ||||
|       Wire.write((uint8_t)reg); | ||||
|       Wire.write((uint8_t)val); | ||||
|       uint8_t i2cErr = Wire.endTransmission();  // i2cErr == 0 means OK | ||||
| @@ -407,7 +398,6 @@ class ES7243 : public I2SSource { | ||||
|     } | ||||
|  | ||||
|     void _es7243InitAdc() { | ||||
|       _es7243I2cBegin(); | ||||
|       _es7243I2cWrite(0x00, 0x01); | ||||
|       _es7243I2cWrite(0x06, 0x00); | ||||
|       _es7243I2cWrite(0x05, 0x1B); | ||||
| @@ -422,47 +412,140 @@ public: | ||||
|       _config.channel_format = I2S_CHANNEL_FMT_ONLY_RIGHT; | ||||
|     }; | ||||
|  | ||||
|     void initialize(int8_t sdaPin, int8_t sclPin, int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t mclkPin) { | ||||
|       // check that pins are valid | ||||
|       if ((sdaPin < 0) || (sclPin < 0)) { | ||||
|         DEBUGSR_PRINTF("\nAR: invalid ES7243 I2C pins: SDA=%d, SCL=%d\n", sdaPin, sclPin);  | ||||
|         return; | ||||
|       } | ||||
|  | ||||
|     void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t mclkPin) { | ||||
|       DEBUGSR_PRINTLN("ES7243:: initialize();"); | ||||
|       if ((i2sckPin < 0) || (mclkPin < 0)) { | ||||
|         DEBUGSR_PRINTF("\nAR: invalid I2S pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);  | ||||
|         return; | ||||
|       } | ||||
|  | ||||
|       // Reserve SDA and SCL pins of the I2C interface | ||||
|       PinManagerPinType es7243Pins[2] = { { sdaPin, true }, { sclPin, true } }; | ||||
|       if (!pinManager.allocateMultiplePins(es7243Pins, 2, PinOwner::HW_I2C)) { | ||||
|         pinManager.deallocateMultiplePins(es7243Pins, 2, PinOwner::HW_I2C); | ||||
|         DEBUGSR_PRINTF("\nAR: Failed to allocate ES7243 I2C pins: SDA=%d, SCL=%d\n", sdaPin, sclPin);  | ||||
|         return; | ||||
|       } | ||||
|  | ||||
|       pin_ES7243_SDA = sdaPin; | ||||
|       pin_ES7243_SCL = sclPin; | ||||
|  | ||||
|       // First route mclk, then configure ADC over I2C, then configure I2S | ||||
|       _es7243InitAdc(); | ||||
|       I2SSource::initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin); | ||||
|     } | ||||
|  | ||||
|     void deinitialize() { | ||||
|       // Release SDA and SCL pins of the I2C interface | ||||
|       PinManagerPinType es7243Pins[2] = { { pin_ES7243_SDA, true }, { pin_ES7243_SCL, true } }; | ||||
|       pinManager.deallocateMultiplePins(es7243Pins, 2, PinOwner::HW_I2C); | ||||
|       I2SSource::deinitialize(); | ||||
|     } | ||||
| }; | ||||
|  | ||||
| /* ES8388 Sound Module | ||||
|    This is an I2S sound processing unit that requires initialization over | ||||
|    I2C before I2S data can be received.  | ||||
| */ | ||||
| class ES8388Source : public I2SSource { | ||||
|   private: | ||||
|  | ||||
|     void _es8388I2cWrite(uint8_t reg, uint8_t val) { | ||||
| #ifndef ES8388_ADDR | ||||
|       Wire.beginTransmission(0x10); | ||||
|       #define ES8388_ADDR 0x10   // default address | ||||
| #else | ||||
|       Wire.beginTransmission(ES8388_ADDR); | ||||
| #endif | ||||
|       Wire.write((uint8_t)reg); | ||||
|       Wire.write((uint8_t)val); | ||||
|       uint8_t i2cErr = Wire.endTransmission();  // i2cErr == 0 means OK | ||||
|       if (i2cErr != 0) { | ||||
|         DEBUGSR_PRINTF("AR: ES8388 I2C write failed with error=%d  (addr=0x%X, reg 0x%X, val 0x%X).\n", i2cErr, ES8388_ADDR, reg, val); | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     void _es8388InitAdc() { | ||||
|       // https://dl.radxa.com/rock2/docs/hw/ds/ES8388%20user%20Guide.pdf Section 10.1 | ||||
|       // http://www.everest-semi.com/pdf/ES8388%20DS.pdf Better spec sheet, more clear.  | ||||
|       // https://docs.google.com/spreadsheets/d/1CN3MvhkcPVESuxKyx1xRYqfUit5hOdsG45St9BCUm-g/edit#gid=0 generally | ||||
|       // Sets ADC to around what AudioReactive expects, and loops line-in to line-out/headphone for monitoring. | ||||
|       // Registries are decimal, settings are binary as that's how everything is listed in the docs | ||||
|       // ...which makes it easier to reference the docs. | ||||
|       // | ||||
|       _es8388I2cWrite( 8,0b00000000); // I2S to slave | ||||
|       _es8388I2cWrite( 2,0b11110011); // Power down DEM and STM | ||||
|       _es8388I2cWrite(43,0b10000000); // Set same LRCK | ||||
|       _es8388I2cWrite( 0,0b00000101); // Set chip to Play & Record Mode | ||||
|       _es8388I2cWrite(13,0b00000010); // Set MCLK/LRCK ratio to 256 | ||||
|       _es8388I2cWrite( 1,0b01000000); // Power up analog and lbias | ||||
|       _es8388I2cWrite( 3,0b00000000); // Power up ADC, Analog Input, and Mic Bias | ||||
|       _es8388I2cWrite( 4,0b11111100); // Power down DAC, Turn on LOUT1 and ROUT1 and LOUT2 and ROUT2 power | ||||
|       _es8388I2cWrite( 2,0b01000000); // Power up DEM and STM and undocumented bit for "turn on line-out amp" | ||||
|  | ||||
|       // #define use_es8388_mic | ||||
|  | ||||
|     #ifdef use_es8388_mic | ||||
|       // The mics *and* line-in are BOTH connected to LIN2/RIN2 on the AudioKit | ||||
|       // so there's no way to completely eliminate the mics. It's also hella noisy.  | ||||
|       // Line-in works OK on the AudioKit, generally speaking, as the mics really need | ||||
|       // amplification to be noticeable in a quiet room. If you're in a very loud room,  | ||||
|       // the mics on the AudioKit WILL pick up sound even in line-in mode.  | ||||
|       // TL;DR: Don't use the AudioKit for anything, use the LyraT.  | ||||
|       // | ||||
|       // The LyraT does a reasonable job with mic input as configured below. | ||||
|  | ||||
|       // Pick one of these. If you have to use the mics, use a LyraT over an AudioKit if you can: | ||||
|       _es8388I2cWrite(10,0b00000000); // Use Lin1/Rin1 for ADC input (mic on LyraT) | ||||
|       //_es8388I2cWrite(10,0b01010000); // Use Lin2/Rin2 for ADC input (mic *and* line-in on AudioKit) | ||||
|        | ||||
|       _es8388I2cWrite( 9,0b10001000); // Select Analog Input PGA Gain for ADC to +24dB (L+R) | ||||
|       _es8388I2cWrite(16,0b00000000); // Set ADC digital volume attenuation to 0dB (left) | ||||
|       _es8388I2cWrite(17,0b00000000); // Set ADC digital volume attenuation to 0dB (right) | ||||
|       _es8388I2cWrite(38,0b00011011); // Mixer - route LIN1/RIN1 to output after mic gain | ||||
|  | ||||
|       _es8388I2cWrite(39,0b01000000); // Mixer - route LIN to mixL, +6dB gain | ||||
|       _es8388I2cWrite(42,0b01000000); // Mixer - route RIN to mixR, +6dB gain | ||||
|       _es8388I2cWrite(46,0b00100001); // LOUT1VOL - 0b00100001 = +4.5dB | ||||
|       _es8388I2cWrite(47,0b00100001); // ROUT1VOL - 0b00100001 = +4.5dB | ||||
|       _es8388I2cWrite(48,0b00100001); // LOUT2VOL - 0b00100001 = +4.5dB | ||||
|       _es8388I2cWrite(49,0b00100001); // ROUT2VOL - 0b00100001 = +4.5dB | ||||
|  | ||||
|       // Music ALC - the mics like Auto Level Control | ||||
|       // You can also use this for line-in, but it's not really needed. | ||||
|       // | ||||
|       _es8388I2cWrite(18,0b11111000); // ALC: stereo, max gain +35.5dB, min gain -12dB  | ||||
|       _es8388I2cWrite(19,0b00110000); // ALC: target -1.5dB, 0ms hold time | ||||
|       _es8388I2cWrite(20,0b10100110); // ALC: gain ramp up = 420ms/93ms, gain ramp down = check manual for calc | ||||
|       _es8388I2cWrite(21,0b00000110); // ALC: use "ALC" mode, no zero-cross, window 96 samples | ||||
|       _es8388I2cWrite(22,0b01011001); // ALC: noise gate threshold, PGA gain constant, noise gate enabled  | ||||
|     #else | ||||
|       _es8388I2cWrite(10,0b01010000); // Use Lin2/Rin2 for ADC input ("line-in") | ||||
|       _es8388I2cWrite( 9,0b00000000); // Select Analog Input PGA Gain for ADC to 0dB (L+R) | ||||
|       _es8388I2cWrite(16,0b01000000); // Set ADC digital volume attenuation to -32dB (left) | ||||
|       _es8388I2cWrite(17,0b01000000); // Set ADC digital volume attenuation to -32dB (right) | ||||
|       _es8388I2cWrite(38,0b00001001); // Mixer - route LIN2/RIN2 to output | ||||
|  | ||||
|       _es8388I2cWrite(39,0b01010000); // Mixer - route LIN to mixL, 0dB gain | ||||
|       _es8388I2cWrite(42,0b01010000); // Mixer - route RIN to mixR, 0dB gain | ||||
|       _es8388I2cWrite(46,0b00011011); // LOUT1VOL - 0b00011110 = +0dB, 0b00011011 = LyraT balance fix | ||||
|       _es8388I2cWrite(47,0b00011110); // ROUT1VOL - 0b00011110 = +0dB | ||||
|       _es8388I2cWrite(48,0b00011110); // LOUT2VOL - 0b00011110 = +0dB | ||||
|       _es8388I2cWrite(49,0b00011110); // ROUT2VOL - 0b00011110 = +0dB | ||||
|     #endif | ||||
|  | ||||
|     } | ||||
|  | ||||
|   public: | ||||
|     ES8388Source(SRate_t sampleRate, int blockSize, float sampleScale = 1.0f, bool i2sMaster=true) : | ||||
|       I2SSource(sampleRate, blockSize, sampleScale) { | ||||
|       _config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT; | ||||
|     }; | ||||
|  | ||||
|     void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t mclkPin) { | ||||
|       DEBUGSR_PRINTLN("ES8388Source:: initialize();"); | ||||
|       if ((i2sckPin < 0) || (mclkPin < 0)) { | ||||
|         DEBUGSR_PRINTF("\nAR: invalid I2S pin: SCK=%d, MCLK=%d\n", i2sckPin, mclkPin);  | ||||
|         return; | ||||
|       } | ||||
|  | ||||
|       // First route mclk, then configure ADC over I2C, then configure I2S | ||||
|       _es8388InitAdc(); | ||||
|       I2SSource::initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin); | ||||
|     } | ||||
|  | ||||
|     void deinitialize() { | ||||
|       I2SSource::deinitialize(); | ||||
|     } | ||||
|  | ||||
|   private: | ||||
|     int8_t pin_ES7243_SDA; | ||||
|     int8_t pin_ES7243_SCL; | ||||
| }; | ||||
|  | ||||
|  | ||||
| #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 2, 0) | ||||
| #if !defined(SOC_I2S_SUPPORTS_ADC) && !defined(SOC_I2S_SUPPORTS_ADC_DAC) | ||||
|   #warning this MCU does not support analog sound input | ||||
| @@ -503,7 +586,8 @@ class I2SAdcSource : public I2SSource { | ||||
|     /* identify Audiosource type - I2S-ADC*/ | ||||
|     AudioSourceType getType(void) {return(Type_I2SAdc);} | ||||
|  | ||||
|     void initialize(int8_t audioPin, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE) { | ||||
|     void initialize(int8_t audioPin, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE) { | ||||
|       DEBUGSR_PRINTLN("I2SAdcSource:: initialize()."); | ||||
|       _myADCchannel = 0x0F; | ||||
|       if(!pinManager.allocatePin(audioPin, false, PinOwner::UM_Audioreactive)) { | ||||
|          DEBUGSR_PRINTF("failed to allocate GPIO for audio analog input: %d\n", audioPin); | ||||
| @@ -674,7 +758,8 @@ class SPH0654 : public I2SSource { | ||||
|       I2SSource(sampleRate, blockSize, sampleScale) | ||||
|     {} | ||||
|  | ||||
|     void initialize(uint8_t i2swsPin, uint8_t i2ssdPin, uint8_t i2sckPin, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE, int8_t = I2S_PIN_NO_CHANGE) { | ||||
|     void initialize(int8_t i2swsPin, int8_t i2ssdPin, int8_t i2sckPin, int8_t = I2S_PIN_NO_CHANGE) { | ||||
|       DEBUGSR_PRINTLN("SPH0654:: initialize();"); | ||||
|       I2SSource::initialize(i2swsPin, i2ssdPin, i2sckPin); | ||||
| #if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(CONFIG_IDF_TARGET_ESP32S3) | ||||
| // these registers are only existing in "classic" ESP32 | ||||
| @@ -685,3 +770,4 @@ class SPH0654 : public I2SSource { | ||||
| #endif | ||||
|     } | ||||
| }; | ||||
| #endif | ||||
| @@ -1,6 +1,6 @@ | ||||
| # Audioreactive usermod | ||||
|  | ||||
| Enabless controlling LEDs via audio input. Audio source can be a microphone or analog-in (AUX) using an appropriate adapter. | ||||
| Enables controlling LEDs via audio input. Audio source can be a microphone or analog-in (AUX) using an appropriate adapter. | ||||
| Supported microphones range from analog (MAX4466, MAX9814, ...) to digital (INMP441, ICS-43434, ...). | ||||
|  | ||||
| Does audio processing and provides data structure that specially written effects can use. | ||||
| @@ -19,7 +19,7 @@ This usermod is an evolution of [SR-WLED](https://github.com/atuline/WLED), and | ||||
| ## Supported MCUs | ||||
| This audioreactive usermod works best on "classic ESP32" (dual core), and on ESP32-S3 which also has dual core and hardware floating point support.  | ||||
|  | ||||
| It will compile succesfully for ESP32-S2 and ESP32-C3, however might not work well, as other WLED functions will become slow. Audio processing requires a lot of computing power, which can be problematic on smaller MCUs like -S2 and -C3.  | ||||
| It will compile successfully for ESP32-S2 and ESP32-C3, however might not work well, as other WLED functions will become slow. Audio processing requires a lot of computing power, which can be problematic on smaller MCUs like -S2 and -C3.  | ||||
|  | ||||
| Analog audio is only possible on "classic" ESP32, but not on other MCUs like ESP32-S3. | ||||
|  | ||||
| @@ -35,7 +35,7 @@ Customised _arduinoFFT_ library for use with this usermod can be found at https: | ||||
|  | ||||
| ### using latest (develop) _arduinoFFT_ library | ||||
| Alternatively, you can use the latest arduinoFFT development version. | ||||
| ArduinoFFT `develop` library is slightly more accurate, and slighly faster than our customised library, however also needs additional 2kB RAM. | ||||
| ArduinoFFT `develop` library is slightly more accurate, and slightly faster than our customised library, however also needs additional 2kB RAM. | ||||
|  | ||||
| * `build_flags` = `-D USERMOD_AUDIOREACTIVE` `-D UM_AUDIOREACTIVE_USE_NEW_FFT` | ||||
| * `lib_deps`= `https://github.com/kosme/arduinoFFT#develop @ 1.9.2` | ||||
| @@ -63,7 +63,7 @@ You can use the following additional flags in your `build_flags` | ||||
| * `-D SR_GAIN=x`     : Default "gain" setting (60) | ||||
| * `-D I2S_USE_RIGHT_CHANNEL`: Use RIGHT instead of LEFT channel (not recommended unless you strictly need this). | ||||
| * `-D I2S_USE_16BIT_SAMPLES`: Use 16bit instead of 32bit for internal sample buffers. Reduces sampling quality, but frees some RAM ressources (not recommended unless you absolutely need this). | ||||
| * `-D I2S_GRAB_ADC1_COMPLETELY`: Experimental: continously sample analog ADC microphone. Only effective on ESP32. WARNING this _will_ cause conflicts(lock-up) with any analogRead() call. | ||||
| * `-D I2S_GRAB_ADC1_COMPLETELY`: Experimental: continuously sample analog ADC microphone. Only effective on ESP32. WARNING this _will_ cause conflicts(lock-up) with any analogRead() call. | ||||
| * `-D MIC_LOGGER`     : (debugging) Logs samples from the microphone to serial USB. Use with serial plotter (Arduino IDE) | ||||
| * `-D SR_DEBUG`       : (debugging) Additional error diagnostics and debug info on serial USB. | ||||
|  | ||||
|   | ||||
| Before Width: | Height: | Size: 68 KiB | 
| @@ -1,68 +0,0 @@ | ||||
| # :battery: Battery status/level Usermod :battery: | ||||
| Enables battery level monitoring of your project. | ||||
|  | ||||
| You can see the battery level and voltage in the `info modal`.  | ||||
|  | ||||
| For this to work, the positive side of the (18650) battery must be connected to pin `A0` of the d1 mini/esp8266 with a 100k Ohm resistor (see [Useful Links](#useful-links)). | ||||
|  | ||||
| If you have an ESP32 board, connect the positive side of the battery to ADC1 (GPIO32 - GPIO39) | ||||
|  | ||||
| <p align="center"> | ||||
|   <img width="300" src="assets/battery_info_screen.png"> | ||||
| </p> | ||||
|  | ||||
| ## Installation | ||||
|  | ||||
| define `USERMOD_BATTERY_STATUS_BASIC` in `my_config.h` | ||||
|  | ||||
| ### Basic wiring diagram | ||||
| <p align="center"> | ||||
|   <img width="300" src="assets/battery_connection_schematic_01.png"> | ||||
| </p> | ||||
|  | ||||
| ### Define Your Options | ||||
|  | ||||
| * `USERMOD_BATTERY_STATUS_BASIC`                   - define this (in `my_config.h`) to have this usermod included wled00\usermods_list.cpp | ||||
| * `USERMOD_BATTERY_MEASUREMENT_PIN`                - defaults to A0 on ESP8266 and GPIO32 on ESP32 | ||||
| * `USERMOD_BATTERY_MEASUREMENT_INTERVAL`           - battery check interval. defaults to 30 seconds | ||||
| * `USERMOD_BATTERY_MIN_VOLTAGE`                    - minimum battery voltage. default is 2.6 (18650 battery standard) | ||||
| * `USERMOD_BATTERY_MAX_VOLTAGE`                    - maximum battery voltage. default is 4.2 (18650 battery standard) | ||||
|  | ||||
| All parameters can be configured at runtime via the Usermods settings page. | ||||
|  | ||||
| ## Important :warning: | ||||
| * Make sure you know your battery specifications! All batteries are **NOT** the same! | ||||
| * Example: | ||||
|  | ||||
| | Your battery specification table  |                 | Options you can define        |  | ||||
| | :-------------------------------- |:--------------- | :---------------------------- | | ||||
| | Capacity                          | 3500mAh 12,5 Wh |                               | | ||||
| | Minimum capacity                  | 3350mAh 11,9 Wh |                               | | ||||
| | Rated voltage                     | 3.6V - 3.7V     |                               | | ||||
| | **Charging end voltage**          | **4,2V ± 0,05** | `USERMOD_BATTERY_MAX_VOLTAGE` | | ||||
| | **Discharge voltage**             | **2,5V**        | `USERMOD_BATTERY_MIN_VOLTAGE` | | ||||
| | Max. discharge current (constant) | 10A (10000mA)   |                               | | ||||
| | max. charging current             | 1.7A (1700mA)   |                               | | ||||
| | ...                               | ...             | ...                           | | ||||
| | ..                                | ..              | ..                            | | ||||
|  | ||||
| Specification from:  [Molicel INR18650-M35A, 3500mAh 10A Lithium-ion battery, 3.6V - 3.7V](https://www.akkuteile.de/lithium-ionen-akkus/18650/molicel/molicel-inr18650-m35a-3500mah-10a-lithium-ionen-akku-3-6v-3-7v_100833) | ||||
|  | ||||
| ## Useful Links | ||||
| * https://lazyzero.de/elektronik/esp8266/wemos_d1_mini_a0/start | ||||
| * https://arduinodiy.wordpress.com/2016/12/25/monitoring-lipo-battery-voltage-with-wemos-d1-minibattery-shield-and-thingspeak/ | ||||
|  | ||||
| ## Change Log | ||||
| 2021-09-02 | ||||
| * added "Battery voltage" to info | ||||
| * added circuit diagram to readme | ||||
| * added MQTT support, sending battery voltage | ||||
| * minor fixes | ||||
|  | ||||
| 2021-08-15 | ||||
| * changed `USERMOD_BATTERY_MIN_VOLTAGE` to 2.6 volt as default for 18650 batteries | ||||
| * Updated readme, added specification table | ||||
|  | ||||
| 2021-08-10 | ||||
| * Created | ||||
|  | ||||
| @@ -1,398 +0,0 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
|  | ||||
|  | ||||
|  | ||||
|  | ||||
| // pin defaults | ||||
| // for the esp32 it is best to use the ADC1: GPIO32 - GPIO39 | ||||
| // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html | ||||
| #ifndef USERMOD_BATTERY_MEASUREMENT_PIN | ||||
|   #ifdef ARDUINO_ARCH_ESP32 | ||||
|     #define USERMOD_BATTERY_MEASUREMENT_PIN 32 | ||||
|   #else //ESP8266 boards | ||||
|     #define USERMOD_BATTERY_MEASUREMENT_PIN A0 | ||||
|   #endif | ||||
| #endif | ||||
|  | ||||
| // esp32 has a 12bit adc resolution | ||||
| // esp8266 only 10bit | ||||
| #ifndef USERMOD_BATTERY_ADC_PRECISION | ||||
|   #ifdef ARDUINO_ARCH_ESP32 | ||||
|     // 12 bits | ||||
|     #define USERMOD_BATTERY_ADC_PRECISION 4095.0f | ||||
|   #else | ||||
|     // 10 bits | ||||
|     #define USERMOD_BATTERY_ADC_PRECISION 1024.0f | ||||
|   #endif | ||||
| #endif | ||||
|  | ||||
|  | ||||
| // the frequency to check the battery, 30 sec | ||||
| #ifndef USERMOD_BATTERY_MEASUREMENT_INTERVAL | ||||
|   #define USERMOD_BATTERY_MEASUREMENT_INTERVAL 30000 | ||||
| #endif | ||||
|  | ||||
|  | ||||
| // default for 18650 battery | ||||
| // https://batterybro.com/blogs/18650-wholesale-battery-reviews/18852515-when-to-recycle-18650-batteries-and-how-to-start-a-collection-center-in-your-vape-shop | ||||
| // Discharge voltage: 2.5 volt + .1 for personal safety | ||||
| #ifndef USERMOD_BATTERY_MIN_VOLTAGE | ||||
|   #define USERMOD_BATTERY_MIN_VOLTAGE 2.6f | ||||
| #endif | ||||
|  | ||||
| #ifndef USERMOD_BATTERY_MAX_VOLTAGE | ||||
|   #define USERMOD_BATTERY_MAX_VOLTAGE 4.2f | ||||
| #endif | ||||
|  | ||||
| class UsermodBatteryBasic : public Usermod  | ||||
| { | ||||
|   private: | ||||
|     // battery pin can be defined in my_config.h | ||||
|     int8_t batteryPin = USERMOD_BATTERY_MEASUREMENT_PIN; | ||||
|     // how often to read the battery voltage | ||||
|     unsigned long readingInterval = USERMOD_BATTERY_MEASUREMENT_INTERVAL; | ||||
|     unsigned long nextReadTime = 0; | ||||
|     unsigned long lastReadTime = 0; | ||||
|     // battery min. voltage | ||||
|     float minBatteryVoltage = USERMOD_BATTERY_MIN_VOLTAGE; | ||||
|     // battery max. voltage | ||||
|     float maxBatteryVoltage = USERMOD_BATTERY_MAX_VOLTAGE; | ||||
|     // 0 - 1024 for esp8266 (10-bit resolution) | ||||
|     // 0 - 4095 for esp32 (Default is 12-bit resolution) | ||||
|     float adcPrecision = USERMOD_BATTERY_ADC_PRECISION; | ||||
|     // raw analog reading  | ||||
|     float rawValue = 0.0; | ||||
|     // calculated voltage             | ||||
|     float voltage = 0.0; | ||||
|     // mapped battery level based on voltage | ||||
|     long batteryLevel = 0; | ||||
|     bool initDone = false; | ||||
|     bool initializing = true; | ||||
|  | ||||
|  | ||||
|     // strings to reduce flash memory usage (used more than twice) | ||||
|     static const char _name[]; | ||||
|     static const char _readInterval[]; | ||||
|      | ||||
|  | ||||
|     // custom map function | ||||
|     // https://forum.arduino.cc/t/floating-point-using-map-function/348113/2 | ||||
|     double mapf(double x, double in_min, double in_max, double out_min, double out_max)  | ||||
|     { | ||||
|       return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; | ||||
|     } | ||||
|  | ||||
|     float truncate(float val, byte dec)  | ||||
|     { | ||||
|       float x = val * pow(10, dec); | ||||
|       float y = round(x); | ||||
|       float z = x - y; | ||||
|       if ((int)z == 5) | ||||
|       { | ||||
|           y++; | ||||
|       } | ||||
|       x = y / pow(10, dec); | ||||
|       return x; | ||||
|     } | ||||
|  | ||||
|  | ||||
|  | ||||
|   public: | ||||
|     //Functions called by WLED | ||||
|  | ||||
|     /* | ||||
|      * setup() is called once at boot. WiFi is not yet connected at this point. | ||||
|      * You can use it to initialize variables, sensors or similar. | ||||
|      */ | ||||
|     void setup()  | ||||
|     { | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         DEBUG_PRINTLN(F("Allocating battery pin...")); | ||||
|         if (batteryPin >= 0 && pinManager.allocatePin(batteryPin, false))  | ||||
|         { | ||||
|           DEBUG_PRINTLN(F("Battery pin allocation succeeded.")); | ||||
|         } else { | ||||
|           if (batteryPin >= 0) DEBUG_PRINTLN(F("Battery pin allocation failed.")); | ||||
|           batteryPin = -1;  // allocation failed | ||||
|         } | ||||
|       #else //ESP8266 boards have only one analog input pin A0 | ||||
|  | ||||
|         pinMode(batteryPin, INPUT); | ||||
|       #endif | ||||
|  | ||||
|       nextReadTime = millis() + readingInterval; | ||||
|       lastReadTime = millis(); | ||||
|  | ||||
|       initDone = true; | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * connected() is called every time the WiFi is (re)connected | ||||
|      * Use it to initialize network interfaces | ||||
|      */ | ||||
|     void connected()  | ||||
|     { | ||||
|       //Serial.println("Connected to WiFi!"); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * loop() is called continuously. Here you can check for events, read sensors, etc. | ||||
|      *  | ||||
|      */ | ||||
|     void loop()  | ||||
|     { | ||||
|       if(strip.isUpdating()) return; | ||||
|  | ||||
|       // check the battery level every USERMOD_BATTERY_MEASUREMENT_INTERVAL (ms) | ||||
|       if (millis() < nextReadTime) return; | ||||
|  | ||||
|  | ||||
|       nextReadTime = millis() + readingInterval; | ||||
|       lastReadTime = millis(); | ||||
|       initializing = false; | ||||
|  | ||||
|       // read battery raw input | ||||
|       rawValue = analogRead(batteryPin); | ||||
|  | ||||
|       // calculate the voltage      | ||||
|       voltage = (rawValue / adcPrecision) * maxBatteryVoltage ; | ||||
|       // check if voltage is within specified voltage range | ||||
|       voltage = voltage<minBatteryVoltage||voltage>maxBatteryVoltage?-1.0f:voltage; | ||||
|  | ||||
|       // translate battery voltage into percentage | ||||
|       /* | ||||
|         the standard "map" function doesn't work | ||||
|         https://www.arduino.cc/reference/en/language/functions/math/map/  notes and warnings at the bottom | ||||
|       */ | ||||
|       batteryLevel = mapf(voltage, minBatteryVoltage, maxBatteryVoltage, 0, 100); | ||||
|  | ||||
|  | ||||
|       // SmartHome stuff | ||||
|       if (WLED_MQTT_CONNECTED) { | ||||
|         char subuf[64]; | ||||
|         strcpy(subuf, mqttDeviceTopic); | ||||
|         strcat_P(subuf, PSTR("/voltage")); | ||||
|         mqtt->publish(subuf, 0, false, String(voltage).c_str()); | ||||
|       } | ||||
|  | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. | ||||
|      * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. | ||||
|      * Below it is shown how this could be used for e.g. a light sensor | ||||
|      */ | ||||
|     void addToJsonInfo(JsonObject& root) | ||||
|     { | ||||
|        | ||||
|       JsonObject user = root["u"]; | ||||
|       if (user.isNull()) user = root.createNestedObject("u"); | ||||
|  | ||||
|       // info modal display names | ||||
|       JsonArray batteryPercentage = user.createNestedArray("Battery level"); | ||||
|       JsonArray batteryVoltage = user.createNestedArray("Battery voltage"); | ||||
|  | ||||
|       if (initializing) { | ||||
|         batteryPercentage.add((nextReadTime - millis()) / 1000); | ||||
|         batteryPercentage.add(" sec"); | ||||
|         batteryVoltage.add((nextReadTime - millis()) / 1000); | ||||
|         batteryVoltage.add(" sec"); | ||||
|         return; | ||||
|       } | ||||
|  | ||||
|       if(batteryLevel < 0) { | ||||
|         batteryPercentage.add(F("invalid")); | ||||
|       } else { | ||||
|         batteryPercentage.add(batteryLevel); | ||||
|       } | ||||
|       batteryPercentage.add(F(" %")); | ||||
|  | ||||
|       if(voltage < 0) { | ||||
|         batteryVoltage.add(F("invalid")); | ||||
|       } else { | ||||
|         batteryVoltage.add(truncate(voltage, 2)); | ||||
|       } | ||||
|       batteryVoltage.add(F(" V")); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object). | ||||
|      * Values in the state object may be modified by connected clients | ||||
|      */ | ||||
|     /* | ||||
|     void addToJsonState(JsonObject& root) | ||||
|     { | ||||
|  | ||||
|     } | ||||
|     */ | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object). | ||||
|      * Values in the state object may be modified by connected clients | ||||
|      */ | ||||
|     /* | ||||
|     void readFromJsonState(JsonObject& root) | ||||
|     { | ||||
|     } | ||||
|     */ | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * addToConfig() can be used to add custom persistent settings to the cfg.json file in the "um" (usermod) object. | ||||
|      * It will be called by WLED when settings are actually saved (for example, LED settings are saved) | ||||
|      * If you want to force saving the current state, use serializeConfig() in your loop(). | ||||
|      *  | ||||
|      * CAUTION: serializeConfig() will initiate a filesystem write operation. | ||||
|      * It might cause the LEDs to stutter and will cause flash wear if called too often. | ||||
|      * Use it sparingly and always in the loop, never in network callbacks! | ||||
|      *  | ||||
|      * addToConfig() will make your settings editable through the Usermod Settings page automatically. | ||||
|      * | ||||
|      * Usermod Settings Overview: | ||||
|      * - Numeric values are treated as floats in the browser. | ||||
|      *   - If the numeric value entered into the browser contains a decimal point, it will be parsed as a C float | ||||
|      *     before being returned to the Usermod.  The float data type has only 6-7 decimal digits of precision, and | ||||
|      *     doubles are not supported, numbers will be rounded to the nearest float value when being parsed. | ||||
|      *     The range accepted by the input field is +/- 1.175494351e-38 to +/- 3.402823466e+38. | ||||
|      *   - If the numeric value entered into the browser doesn't contain a decimal point, it will be parsed as a | ||||
|      *     C int32_t (range: -2147483648 to 2147483647) before being returned to the usermod. | ||||
|      *     Overflows or underflows are truncated to the max/min value for an int32_t, and again truncated to the type | ||||
|      *     used in the Usermod when reading the value from ArduinoJson. | ||||
|      * - Pin values can be treated differently from an integer value by using the key name "pin" | ||||
|      *   - "pin" can contain a single or array of integer values | ||||
|      *   - On the Usermod Settings page there is simple checking for pin conflicts and warnings for special pins | ||||
|      *     - Red color indicates a conflict.  Yellow color indicates a pin with a warning (e.g. an input-only pin) | ||||
|      *   - Tip: use int8_t to store the pin value in the Usermod, so a -1 value (pin not set) can be used | ||||
|      * | ||||
|      * See usermod_v2_auto_save.h for an example that saves Flash space by reusing ArduinoJson key name strings | ||||
|      *  | ||||
|      * If you need a dedicated settings page with custom layout for your Usermod, that takes a lot more work.   | ||||
|      * You will have to add the setting to the HTML, xml.cpp and set.cpp manually. | ||||
|      * See the WLED Soundreactive fork (code and wiki) for reference.  https://github.com/atuline/WLED | ||||
|      *  | ||||
|      * I highly recommend checking out the basics of ArduinoJson serialization and deserialization in order to use custom settings! | ||||
|      */ | ||||
|     void addToConfig(JsonObject& root) | ||||
|     { | ||||
|       // created JSON object:  | ||||
|       /* | ||||
|       { | ||||
|         "Battery-Level": { | ||||
|           "pin": "A0",              <--- only when using esp32 boards | ||||
|           "minBatteryVoltage": 2.6,  | ||||
|           "maxBatteryVoltage": 4.2, | ||||
|           "read-interval-ms": 30000   | ||||
|         } | ||||
|       } | ||||
|       */  | ||||
|       JsonObject battery = root.createNestedObject(FPSTR(_name)); // usermodname | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         battery["pin"] = batteryPin;                              // usermodparam | ||||
|       #endif | ||||
|       battery["minBatteryVoltage"] = minBatteryVoltage;           // usermodparam | ||||
|       battery["maxBatteryVoltage"] = maxBatteryVoltage;           // usermodparam | ||||
|       battery[FPSTR(_readInterval)] = readingInterval; | ||||
|  | ||||
|       DEBUG_PRINTLN(F("Battery config saved.")); | ||||
|     } | ||||
|  | ||||
|  | ||||
|     /* | ||||
|      * readFromConfig() can be used to read back the custom settings you added with addToConfig(). | ||||
|      * This is called by WLED when settings are loaded (currently this only happens immediately after boot, or after saving on the Usermod Settings page) | ||||
|      *  | ||||
|      * readFromConfig() is called BEFORE setup(). This means you can use your persistent values in setup() (e.g. pin assignments, buffer sizes), | ||||
|      * but also that if you want to write persistent values to a dynamic buffer, you'd need to allocate it here instead of in setup. | ||||
|      * If you don't know what that is, don't fret. It most likely doesn't affect your use case :) | ||||
|      *  | ||||
|      * Return true in case the config values returned from Usermod Settings were complete, or false if you'd like WLED to save your defaults to disk (so any missing values are editable in Usermod Settings) | ||||
|      *  | ||||
|      * getJsonValue() returns false if the value is missing, or copies the value into the variable provided and returns true if the value is present | ||||
|      * The configComplete variable is true only if the "exampleUsermod" object and all values are present.  If any values are missing, WLED will know to call addToConfig() to save them | ||||
|      *  | ||||
|      * This function is guaranteed to be called on boot, but could also be called every time settings are updated | ||||
|      */ | ||||
|     bool readFromConfig(JsonObject& root) | ||||
|     { | ||||
|       // looking for JSON object:  | ||||
|       /* | ||||
|       { | ||||
|         "BatteryLevel": { | ||||
|           "pin": "A0",              <--- only when using esp32 boards | ||||
|           "minBatteryVoltage": 2.6,  | ||||
|           "maxBatteryVoltage": 4.2, | ||||
|           "read-interval-ms": 30000   | ||||
|         } | ||||
|       } | ||||
|       */ | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         int8_t newBatteryPin = batteryPin; | ||||
|       #endif | ||||
|  | ||||
|       JsonObject battery = root[FPSTR(_name)]; | ||||
|       if (battery.isNull())  | ||||
|       { | ||||
|         DEBUG_PRINT(FPSTR(_name)); | ||||
|         DEBUG_PRINTLN(F(": No config found. (Using defaults.)")); | ||||
|         return false; | ||||
|       } | ||||
|  | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         newBatteryPin     = battery["pin"] | newBatteryPin; | ||||
|       #endif | ||||
|       minBatteryVoltage   = battery["minBatteryVoltage"] | minBatteryVoltage; | ||||
|       //minBatteryVoltage = min(12.0f, (int)readingInterval); | ||||
|       maxBatteryVoltage   = battery["maxBatteryVoltage"] | maxBatteryVoltage; | ||||
|       //maxBatteryVoltage = min(14.4f, max(3.3f,(int)readingInterval)); | ||||
|       readingInterval     = battery["read-interval-ms"] | readingInterval; | ||||
|       readingInterval     = max(3000, (int)readingInterval); // minimum repetition is >5000ms (5s) | ||||
|  | ||||
|       DEBUG_PRINT(FPSTR(_name)); | ||||
|  | ||||
|       #ifdef ARDUINO_ARCH_ESP32 | ||||
|         if (!initDone)  | ||||
|         { | ||||
|           // first run: reading from cfg.json | ||||
|           newBatteryPin = batteryPin; | ||||
|           DEBUG_PRINTLN(F(" config loaded.")); | ||||
|         }  | ||||
|         else  | ||||
|         { | ||||
|           DEBUG_PRINTLN(F(" config (re)loaded.")); | ||||
|  | ||||
|           // changing paramters from settings page | ||||
|           if (newBatteryPin != batteryPin)  | ||||
|           { | ||||
|             // deallocate pin | ||||
|             pinManager.deallocatePin(batteryPin); | ||||
|             batteryPin = newBatteryPin; | ||||
|             // initialise | ||||
|             setup(); | ||||
|           } | ||||
|         } | ||||
|       #endif | ||||
|  | ||||
|       return !battery[FPSTR(_readInterval)].isNull(); | ||||
|     } | ||||
|  | ||||
|     | ||||
|     /* | ||||
|      * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). | ||||
|      * This could be used in the future for the system to determine whether your usermod is installed. | ||||
|      */ | ||||
|     uint16_t getId() | ||||
|     { | ||||
|       return USERMOD_ID_BATTERY_STATUS_BASIC; | ||||
|     } | ||||
| }; | ||||
|  | ||||
| // strings to reduce flash memory usage (used more than twice) | ||||
| const char UsermodBatteryBasic::_name[]         PROGMEM = "Battery-level"; | ||||
| const char UsermodBatteryBasic::_readInterval[] PROGMEM = "read-interval-ms"; | ||||
| @@ -1,28 +0,0 @@ | ||||
| # Blynk controllable relay | ||||
| Enables controlling a relay state via user variables. Allows the user variables to be set via Blynk. | ||||
|  | ||||
| Optionally, the servo can have a reset timer to return to its default state after a user definable interval. The interval is set via userVar1. | ||||
|  | ||||
| ## Instalation | ||||
|  | ||||
| Replace the WLED06_usermod.ino file in Aircoookies WLED folder, with the one here. | ||||
|  | ||||
| ## Customizations | ||||
|  | ||||
| Update the following parameters in WLED06_usermod.ino to configure the mod's behavior: | ||||
|  | ||||
| ```cpp | ||||
| //Which pin is the relay connected to | ||||
| #define RELAY_PIN 5 | ||||
| //Which pin state should the relay default to | ||||
| #define RELAY_PIN_DEFAULT LOW | ||||
| //If >0 The controller returns to RELAY_PIN_DEFAULT after this time, in milliseconds | ||||
| #define RELAY_PIN_TIMER_DEFAULT 3000 | ||||
|  | ||||
| //Blynk virtual pin for controlling relay | ||||
| #define BLYNK_USER_VAR0_PIN V9 | ||||
| //Blynk virtual pin for controlling relay timer | ||||
| #define BLYNK_USER_VAR1_PIN V10 | ||||
| //Number of milliseconds between Blynk updates | ||||
| #define BLYNK_RELAY_UPDATE_INTERVAL 5000 | ||||
| ``` | ||||
| @@ -1,96 +0,0 @@ | ||||
| /* | ||||
|  * This file allows you to add own functionality to WLED more easily | ||||
|  * See: https://github.com/Aircoookie/WLED/wiki/Add-own-functionality | ||||
|  * EEPROM bytes 2750+ are reserved for your custom use case. (if you extend #define EEPSIZE in wled_eeprom.h) | ||||
|  * bytes 2400+ are currently ununsed, but might be used for future wled features | ||||
|  */ | ||||
|  | ||||
| //Use userVar0 (API calls &U0=, uint16_t) to set relay state | ||||
| #define relayPinState userVar0 | ||||
| //Use userVar1 (API calls &U1=, uint16_t) to set relay timer duration | ||||
| //Ignored if 0, otherwise number of milliseconds to allow relay to stay in | ||||
| //non default state. | ||||
| #define relayTimerInterval userVar1 | ||||
|  | ||||
| //Which pin is the relay connected to | ||||
| #define RELAY_PIN 5 | ||||
| //Which pin state should the relay default to | ||||
| #define RELAY_PIN_DEFAULT LOW | ||||
| //If >0 The controller returns to RELAY_PIN_DEFAULT after this time in milliseconds | ||||
| #define RELAY_PIN_TIMER_DEFAULT 3000 | ||||
|  | ||||
| //Blynk virtual pin for controlling relay | ||||
| #define BLYNK_USER_VAR0_PIN V9 | ||||
| //Blynk virtual pin for controlling relay timer | ||||
| #define BLYNK_USER_VAR1_PIN V10 | ||||
| //Number of milliseconds between updating blynk | ||||
| #define BLYNK_RELAY_UPDATE_INTERVAL 5000 | ||||
|  | ||||
| //Is the timer for resetting the relay active | ||||
| bool relayTimerStarted = false; | ||||
| //millis() time after which relay will be reset | ||||
| unsigned long relayTimeToDefault = 0; | ||||
| //millis() time after which relay vars in Blynk will be sent | ||||
| unsigned long relayBlynkUpdateTime = 0; | ||||
|  | ||||
| //gets called once at boot. Do all initialization that doesn't depend on network here | ||||
| void userSetup() | ||||
| { | ||||
|   relayPinState = RELAY_PIN_DEFAULT; | ||||
|   relayTimerInterval = RELAY_PIN_TIMER_DEFAULT; | ||||
|   pinMode(RELAY_PIN, OUTPUT); | ||||
|   digitalWrite(RELAY_PIN, relayPinState); | ||||
| } | ||||
|  | ||||
| //gets called every time WiFi is (re-)connected. Initialize own network interfaces here | ||||
| void userConnected() | ||||
| { | ||||
| } | ||||
|  | ||||
| //loop. You can use "if (WLED_CONNECTED)" to check for successful connection | ||||
| void userLoop() | ||||
| { | ||||
|   //Normalize relayPinState to an accepted value | ||||
|   if (relayPinState != HIGH && relayPinState != LOW) { | ||||
|     relayPinState = RELAY_PIN_DEFAULT; | ||||
|   } | ||||
|   //If relay changes and relayTimerInterval is set, start a timer to change back | ||||
|   if (relayTimerInterval != 0 && | ||||
|       relayPinState != RELAY_PIN_DEFAULT && | ||||
|       !relayTimerStarted ) { | ||||
|     relayTimerStarted = true; | ||||
|     relayTimeToDefault = millis() + relayTimerInterval; | ||||
|   } | ||||
|   //If manually changed back to default, cancel timer | ||||
|   if (relayTimerStarted && relayPinState == RELAY_PIN_DEFAULT ) { | ||||
|     relayTimerStarted = false; | ||||
|   } | ||||
|   //If timer completes, set relay back to default | ||||
|   if (relayTimerStarted && millis() > relayTimeToDefault) { | ||||
|     relayPinState = RELAY_PIN_DEFAULT; | ||||
|     relayTimerStarted = false; | ||||
|   } | ||||
|   digitalWrite(RELAY_PIN, relayPinState); | ||||
|   updateRelayBlynk(); | ||||
| } | ||||
|  | ||||
| //Update Blynk with state of userVars at BLYNK_RELAY_UPDATE_INTERVAL | ||||
| void updateRelayBlynk() | ||||
| { | ||||
|   if (!WLED_CONNECTED) return; | ||||
|   if (relayBlynkUpdateTime > millis()) return; | ||||
|   Blynk.virtualWrite(BLYNK_USER_VAR0_PIN, userVar0); | ||||
|   Blynk.virtualWrite(BLYNK_USER_VAR1_PIN, userVar1); | ||||
|   relayBlynkUpdateTime = millis() + BLYNK_RELAY_UPDATE_INTERVAL; | ||||
| } | ||||
|  | ||||
| //Add Blynk callback for setting userVar0 | ||||
| BLYNK_WRITE(BLYNK_USER_VAR0_PIN) | ||||
| { | ||||
|   userVar0 = param.asInt(); | ||||
| } | ||||
| //Add Blynk callback for setting userVar1 | ||||
| BLYNK_WRITE(BLYNK_USER_VAR1_PIN) | ||||
| { | ||||
|   userVar1 = param.asInt(); | ||||
| } | ||||
| @@ -219,6 +219,7 @@ class BobLightUsermod : public Usermod { | ||||
|  | ||||
|     void enable(bool en) { enabled = en; } | ||||
|      | ||||
| #ifndef WLED_DISABLE_MQTT | ||||
|     /** | ||||
|      * handling of MQTT message | ||||
|      * topic only contains stripped topic (part after /wled/MAC) | ||||
| @@ -249,6 +250,7 @@ class BobLightUsermod : public Usermod { | ||||
|       //  mqtt->subscribe(subuf, 0); | ||||
|       //} | ||||
|     } | ||||
| #endif | ||||
|  | ||||
|     void addToJsonInfo(JsonObject& root) | ||||
|     { | ||||
|   | ||||
| @@ -85,12 +85,9 @@ class MPU6050Driver : public Usermod { | ||||
|      * setup() is called once at boot. WiFi is not yet connected at this point. | ||||
|      */ | ||||
|     void setup() { | ||||
|       PinManagerPinType pins[2] = { { i2c_scl, true }, { i2c_sda, true } }; | ||||
|       if (!pinManager.allocateMultiplePins(pins, 2, PinOwner::HW_I2C)) { enabled = false; return; } | ||||
|       // join I2C bus (I2Cdev library doesn't do this automatically) | ||||
|       if (i2c_scl<0 || i2c_sda<0) { enabled = false; return; } | ||||
|       #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE | ||||
|         Wire.begin(); | ||||
|         Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties | ||||
|         Wire.setClock(400000U); // 400kHz I2C clock. Comment this line if having compilation difficulties | ||||
|       #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE | ||||
|         Fastwire::setup(400, true); | ||||
|       #endif | ||||
| @@ -138,7 +135,7 @@ class MPU6050Driver : public Usermod { | ||||
|         // (if it's going to break, usually the code will be 1) | ||||
|         DEBUG_PRINT(F("DMP Initialization failed (code ")); | ||||
|         DEBUG_PRINT(devStatus); | ||||
|         DEBUG_PRINTLN(F(")")); | ||||
|         DEBUG_PRINTLN(")"); | ||||
|       } | ||||
|     } | ||||
|  | ||||
| @@ -209,7 +206,7 @@ class MPU6050Driver : public Usermod { | ||||
|       JsonObject user = root["u"]; | ||||
|       if (user.isNull()) user = root.createNestedObject("u"); | ||||
|  | ||||
|       JsonArray imu_meas = user.createNestedObject("IMU"); | ||||
|       JsonObject imu_meas = user.createNestedObject("IMU"); | ||||
|       JsonArray quat_json = imu_meas.createNestedArray("Quat"); | ||||
|       quat_json.add(qat.w); | ||||
|       quat_json.add(qat.x); | ||||
| @@ -287,4 +284,4 @@ class MPU6050Driver : public Usermod { | ||||
|       return USERMOD_ID_IMU; | ||||
|     } | ||||
|  | ||||
| }; | ||||
| }; | ||||
|   | ||||
| @@ -50,5 +50,5 @@ This usermod listens on `[mqttDeviceTopic]/switch/0/set` (where 0 is replaced wi | ||||
| Feedback about the current state is provided at `[mqttDeviceTopic]/switch/0/state`. | ||||
|  | ||||
| ### Home Assistant auto-discovery | ||||
| Auto-discovery information is automatically published and you shoudn't have to do anything to register the switches in Home Assistant. | ||||
| Auto-discovery information is automatically published and you shouldn't have to do anything to register the switches in Home Assistant. | ||||
|   | ||||
|   | ||||
| @@ -1,6 +1,9 @@ | ||||
| # Multi Relay | ||||
|  | ||||
| This usermod-v2 modification allows the connection of multiple relays, each with individual delay and on/off mode. | ||||
| Usermod supports PCF8574 I2C port expander to reduce GPIO use. | ||||
| PCF8574 supports 8 outputs and each output corresponds to a relay in WLED (relay 0 = port 0, etc). I you are using more than 8 relays with multiple PCF8574 make sure their addresses are set in sequence (e.g. 0x20 and 0x21). You can set address of first expander in settings. | ||||
| (**NOTE:** Will require Wire library and global I2C pins defined.) | ||||
|  | ||||
| ## HTTP API | ||||
| All responses are returned in JSON format.  | ||||
| @@ -81,13 +84,15 @@ void registerUsermods() | ||||
| Usermod can be configured via the Usermods settings page. | ||||
|  | ||||
| * `enabled` - enable/disable usermod | ||||
| * `use-PCF8574` - use PCF8574 port expander instead of GPIO pins | ||||
| * `first-PCF8574` - I2C address of first expander (WARNING: enter *decimal* value) | ||||
| * `broadcast`- time in seconds between MQTT relay-state broadcasts | ||||
| * `HA-discovery`- enable Home Assistant auto discovery | ||||
| * `pin` - ESP GPIO pin the relay is connected to (can be configured at compile time `-D MULTI_RELAY_PINS=xx,xx,...`) | ||||
| * `delay-s` - delay in seconds after on/off command is received | ||||
| * `active-high` - assign high/low activation of relay (can be used to reverse relay states) | ||||
| * `external` - if enabled, WLED does not control relay, it can only be triggered by an external command (MQTT, HTTP, JSON or button) | ||||
| * `button` - button (from LED Settings) that controls this relay | ||||
| * `broadcast`- time in seconds between MQTT relay-state broadcasts | ||||
| * `HA-discovery`- enable Home Assistant auto discovery | ||||
|  | ||||
| If there is no MultiRelay section, just save current configuration and re-open Usermods settings page.  | ||||
|  | ||||
| @@ -100,3 +105,6 @@ Have fun - @blazoncek | ||||
| 2021-11 | ||||
| * Added information about dynamic configuration options | ||||
| * Added button support. | ||||
|  | ||||
| 2023-05 | ||||
| * Added support for PCF8574 I2C port expander (multiple) | ||||
| @@ -2,7 +2,7 @@ | ||||
| The (un)official usermod to get the best out of the QuinLED-An-Penta (https://quinled.info/quinled-an-penta/), e.g. using the OLED and the SHT30 temperature/humidity sensor. | ||||
|  | ||||
| ## Requirements | ||||
| * "u8gs" by olikraus, v2.28 or higher: https://github.com/olikraus/u8g2 | ||||
| * "u8g2" by olikraus, v2.28 or higher: https://github.com/olikraus/u8g2 | ||||
| * "SHT85" by Rob Tillaart, v0.2 or higher: https://github.com/RobTillaart/SHT85 | ||||
|  | ||||
| ## Usermod installation | ||||
|   | ||||
| @@ -20,7 +20,7 @@ | ||||
|   | `pinSourceSelect` | GPIO that is connected to SD's `SS`(source select) / `CS`(chip select)                           | 16      | | ||||
|   | `pinSourceClock`  | GPIO that is connected to SD's `SCLK` (source clock) / `CLK`(clock)                              | 14      | | ||||
|   | `pinPoci`         | GPIO that is connected to SD's `POCI`<sup>☨</sup> (Peripheral-Out-Ctrl-In) / `MISO` (deprecated) | 36      | | ||||
|   | `pinPico`         | GPIO that is connected to SD's `PICO`<sup>☨</sup> (Peripheral-In-Ctrl-Out) / `MOSI` (deprecated) | 14      | | ||||
|   | `pinPico`         | GPIO that is connected to SD's `PICO`<sup>☨</sup> (Peripheral-In-Ctrl-Out) / `MOSI` (deprecated) | 15      | | ||||
|   | `sdEnable`        | Enable to read data from the SD-card                                                             | true    | | ||||
|  | ||||
|   <sup>☨</sup><sub>Following new naming convention of [OSHWA](https://www.oshwa.org/a-resolution-to-redefine-spi-signal-names/)</sub> | ||||
| @@ -31,4 +31,4 @@ | ||||
| -  checks if the specified file is available on the SD card | ||||
|    ```cpp | ||||
|    bool file_onSD(const char *filepath) {...} | ||||
|    ``` | ||||
|    ``` | ||||
|   | ||||
| @@ -1,8 +1,11 @@ | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
| #include <Arduino.h> | ||||
| #include <Wire.h> | ||||
| #include <Adafruit_Sensor.h> | ||||
| #include <Adafruit_BMP280.h> | ||||
| #include <Adafruit_CCS811.h> | ||||
| @@ -12,14 +15,6 @@ Adafruit_BMP280 bmp; | ||||
| Adafruit_Si7021 si7021; | ||||
| Adafruit_CCS811 ccs811; | ||||
|  | ||||
| #ifdef ARDUINO_ARCH_ESP32 //ESP32 boards | ||||
| uint8_t SCL_PIN = 22; | ||||
| uint8_t SDA_PIN = 21; | ||||
| #else //ESP8266 boards | ||||
| uint8_t SCL_PIN = 5; | ||||
| uint8_t SDA_PIN = 4; | ||||
| #endif | ||||
|  | ||||
| class UserMod_SensorsToMQTT : public Usermod | ||||
| { | ||||
| private: | ||||
| @@ -227,7 +222,6 @@ public: | ||||
|   void setup() | ||||
|   { | ||||
|     Serial.println("Starting!"); | ||||
|     Wire.begin(SDA_PIN, SCL_PIN); | ||||
|     Serial.println("Initializing sensors.. "); | ||||
|     _initialize(); | ||||
|   } | ||||
|   | ||||
| @@ -17,7 +17,7 @@ The number of individual LEDs per segment. 7 segments per digit. | ||||
| #### perPeriod -- ssLEDPerPeriod | ||||
| The number of individual LEDs per period. A ':' (colon) has two periods. | ||||
| #### startIdx -- ssStartLED | ||||
| Index of the LED the display starts at. Enabless a seven segment display to be in the middle of a string. | ||||
| Index of the LED the display starts at. Enables a seven segment display to be in the middle of a string. | ||||
| #### timeEnable -- ssTimeEnabled | ||||
| When true, when displayMask is configured for a time output and no message is set, the time will be displayed. | ||||
| #### scrollSpd -- ssScrollSpeed | ||||
|   | ||||
| @@ -1,3 +1,7 @@ | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
| @@ -405,7 +409,7 @@ public: | ||||
|  | ||||
|     if (mqttGroupTopic[0] != 0) | ||||
|     { | ||||
|       //subcribe for sevenseg messages on the group topic | ||||
|       //subscribe for sevenseg messages on the group topic | ||||
|       sprintf_P(subBuffer, PSTR("%s/%S/+/set"), mqttGroupTopic, _str_sevenSeg); | ||||
|       mqtt->subscribe(subBuffer, 2); | ||||
|     } | ||||
| @@ -413,7 +417,7 @@ public: | ||||
|  | ||||
|   bool onMqttMessage(char *topic, char *payload) | ||||
|   { | ||||
|     //If topic beings iwth sevenSeg cut it off, otherwise not our message. | ||||
|     //If topic beings with sevenSeg cut it off, otherwise not our message. | ||||
|     size_t topicPrefixLen = strlen_P(PSTR("/sevenSeg/")); | ||||
|     if (strncmp_P(topic, PSTR("/sevenSeg/"), topicPrefixLen) == 0) | ||||
|       topic += topicPrefixLen; | ||||
|   | ||||
| @@ -24,6 +24,9 @@ Enables the inverted mode in which the background should be enabled and the digi | ||||
| ### Colon-blinking | ||||
| Enables the blinking colon(s) if they are defined | ||||
|  | ||||
| ### Leading-Zero | ||||
| Shows the leading zero of the hour if it exists (i.e. shows `07` instead of `7`) | ||||
|  | ||||
| ### enable-auto-brightness | ||||
| Enables the auto brightness feature. Can be used only when the usermod SN_Photoresistor is installed. | ||||
|  | ||||
|   | ||||
| @@ -1,3 +1,7 @@ | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
| @@ -13,6 +17,7 @@ private: | ||||
|   bool umSSDRDisplayTime = false; | ||||
|   bool umSSDRInverted = false; | ||||
|   bool umSSDRColonblink = true; | ||||
|   bool umSSDRLeadingZero = false; | ||||
|   bool umSSDREnableLDR = false; | ||||
|   String umSSDRHours = ""; | ||||
|   String umSSDRMinutes = ""; | ||||
| @@ -75,6 +80,7 @@ private: | ||||
|   static const char _str_timeEnabled[]; | ||||
|   static const char _str_inverted[]; | ||||
|   static const char _str_colonblink[]; | ||||
|   static const char _str_leadingZero[]; | ||||
|   static const char _str_displayMask[]; | ||||
|   static const char _str_hours[]; | ||||
|   static const char _str_minutes[]; | ||||
| @@ -101,15 +107,15 @@ private: | ||||
|       switch (umSSDRDisplayMask[index]) { | ||||
|         case 'h': | ||||
|           timeVar = hourFormat12(localTime); | ||||
|           _showElements(&umSSDRHours, timeVar, 0, 1); | ||||
|           _showElements(&umSSDRHours, timeVar, 0, !umSSDRLeadingZero); | ||||
|           break; | ||||
|         case 'H': | ||||
|           timeVar = hour(localTime); | ||||
|           _showElements(&umSSDRHours, timeVar, 0, 1); | ||||
|           _showElements(&umSSDRHours, timeVar, 0, !umSSDRLeadingZero); | ||||
|           break; | ||||
|         case 'k': | ||||
|           timeVar = hour(localTime) + 1; | ||||
|           _showElements(&umSSDRHours, timeVar, 0, 0); | ||||
|           _showElements(&umSSDRHours, timeVar, 0, !umSSDRLeadingZero); | ||||
|           break; | ||||
|         case 'm': | ||||
|           timeVar = minute(localTime); | ||||
| @@ -305,6 +311,9 @@ private: | ||||
|     if (_cmpIntSetting_P(topic, payload, _str_colonblink, &umSSDRColonblink)) { | ||||
|       return true; | ||||
|     } | ||||
|     if (_cmpIntSetting_P(topic, payload, _str_leadingZero, &umSSDRLeadingZero)) { | ||||
|       return true; | ||||
|     } | ||||
|     if (strcmp_P(topic, _str_displayMask) == 0) { | ||||
|       umSSDRDisplayMask = String(payload); | ||||
|       _publishMQTTstr_P(_str_displayMask, umSSDRDisplayMask); | ||||
| @@ -319,6 +328,7 @@ private: | ||||
|     _publishMQTTint_P(_str_ldrEnabled, umSSDREnableLDR); | ||||
|     _publishMQTTint_P(_str_inverted, umSSDRInverted); | ||||
|     _publishMQTTint_P(_str_colonblink, umSSDRColonblink); | ||||
|     _publishMQTTint_P(_str_leadingZero, umSSDRLeadingZero); | ||||
|  | ||||
|     _publishMQTTstr_P(_str_hours, umSSDRHours); | ||||
|     _publishMQTTstr_P(_str_minutes, umSSDRMinutes); | ||||
| @@ -343,6 +353,7 @@ private: | ||||
|     ssdrObj[FPSTR(_str_ldrEnabled)] = umSSDREnableLDR; | ||||
|     ssdrObj[FPSTR(_str_inverted)] = umSSDRInverted; | ||||
|     ssdrObj[FPSTR(_str_colonblink)] = umSSDRColonblink; | ||||
|     ssdrObj[FPSTR(_str_leadingZero)] = umSSDRLeadingZero; | ||||
|     ssdrObj[FPSTR(_str_displayMask)] = umSSDRDisplayMask; | ||||
|     ssdrObj[FPSTR(_str_hours)] = umSSDRHours; | ||||
|     ssdrObj[FPSTR(_str_minutes)] = umSSDRMinutes; | ||||
| @@ -421,6 +432,8 @@ public: | ||||
|     invert.add(umSSDRInverted); | ||||
|     JsonArray blink = user.createNestedArray("Blinking colon"); | ||||
|     blink.add(umSSDRColonblink); | ||||
|     JsonArray zero = user.createNestedArray("Show the hour leading zero"); | ||||
|     zero.add(umSSDRLeadingZero); | ||||
|     JsonArray ldrEnable = user.createNestedArray("Auto Brightness enabled"); | ||||
|     ldrEnable.add(umSSDREnableLDR); | ||||
|  | ||||
| @@ -450,6 +463,7 @@ public: | ||||
|       umSSDREnableLDR = ssdrObj[FPSTR(_str_ldrEnabled)] | umSSDREnableLDR; | ||||
|       umSSDRInverted = ssdrObj[FPSTR(_str_inverted)] | umSSDRInverted; | ||||
|       umSSDRColonblink = ssdrObj[FPSTR(_str_colonblink)] | umSSDRColonblink; | ||||
|       umSSDRLeadingZero = ssdrObj[FPSTR(_str_leadingZero)] | umSSDRLeadingZero; | ||||
|       umSSDRDisplayMask = ssdrObj[FPSTR(_str_displayMask)] | umSSDRDisplayMask; | ||||
|     } | ||||
|   } | ||||
| @@ -466,14 +480,14 @@ public: | ||||
|  | ||||
|     if (mqttGroupTopic[0] != 0) | ||||
|     { | ||||
|       //subcribe for sevenseg messages on the group topic | ||||
|       //subscribe for sevenseg messages on the group topic | ||||
|       sprintf_P(subBuffer, PSTR("%s/%S/+/set"), mqttGroupTopic, _str_name); | ||||
|       mqtt->subscribe(subBuffer, 2); | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   bool onMqttMessage(char *topic, char *payload) { | ||||
|     //If topic beings iwth sevenSeg cut it off, otherwise not our message. | ||||
|     //If topic begins with sevenSeg cut it off, otherwise not our message. | ||||
|     size_t topicPrefixLen = strlen_P(PSTR("/wledSS/")); | ||||
|     if (strncmp_P(topic, PSTR("/wledSS/"), topicPrefixLen) == 0) { | ||||
|       topic += topicPrefixLen; | ||||
| @@ -512,6 +526,7 @@ public: | ||||
|     umSSDREnableLDR        = (top[FPSTR(_str_ldrEnabled)] | umSSDREnableLDR); | ||||
|     umSSDRInverted         = (top[FPSTR(_str_inverted)] | umSSDRInverted); | ||||
|     umSSDRColonblink       = (top[FPSTR(_str_colonblink)] | umSSDRColonblink); | ||||
|     umSSDRLeadingZero      = (top[FPSTR(_str_leadingZero)] | umSSDRLeadingZero); | ||||
|  | ||||
|     umSSDRDisplayMask      = top[FPSTR(_str_displayMask)] | umSSDRDisplayMask; | ||||
|     umSSDRHours            = top[FPSTR(_str_hours)] | umSSDRHours; | ||||
| @@ -542,6 +557,7 @@ const char UsermodSSDR::_str_name[]        PROGMEM = "UsermodSSDR"; | ||||
| const char UsermodSSDR::_str_timeEnabled[] PROGMEM = "enabled"; | ||||
| const char UsermodSSDR::_str_inverted[]    PROGMEM = "inverted"; | ||||
| const char UsermodSSDR::_str_colonblink[]  PROGMEM = "Colon-blinking"; | ||||
| const char UsermodSSDR::_str_leadingZero[] PROGMEM = "Leading-Zero"; | ||||
| const char UsermodSSDR::_str_displayMask[] PROGMEM = "Display-Mask"; | ||||
| const char UsermodSSDR::_str_hours[]       PROGMEM = "LED-Numbers-Hours"; | ||||
| const char UsermodSSDR::_str_minutes[]     PROGMEM = "LED-Numbers-Minutes"; | ||||
|   | ||||
| @@ -1,3 +1,7 @@ | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #pragma once | ||||
|  | ||||
| #include "SHT85.h" | ||||
| @@ -12,13 +16,12 @@ class ShtUsermod : public Usermod | ||||
|   private: | ||||
|     bool enabled = false; // Is usermod enabled or not | ||||
|     bool firstRunDone = false; // Remembers if the first config load run had been done | ||||
|     bool pinAllocDone = true; // Remembers if we have allocated pins | ||||
|     bool initDone = false; // Remembers if the mod has been completely initialised | ||||
|     bool haMqttDiscovery = false; // Is MQTT discovery enabled or not | ||||
|     bool haMqttDiscoveryDone = false; // Remembers if we already published the HA discovery topics | ||||
|  | ||||
|     // SHT vars | ||||
|     SHT *shtTempHumidSensor; // Instance of SHT lib | ||||
|     SHT *shtTempHumidSensor = nullptr; // Instance of SHT lib | ||||
|     byte shtType = 0; // SHT sensor type to be used. Default: SHT30 | ||||
|     byte unitOfTemp = 0; // Temperature unit to be used. Default: Celsius (0 = Celsius, 1 = Fahrenheit) | ||||
|     bool shtInitDone = false; // Remembers if SHT sensor has been initialised | ||||
| @@ -26,15 +29,14 @@ class ShtUsermod : public Usermod | ||||
|     const byte shtI2cAddress = 0x44; // i2c address of the sensor. 0x44 is the default for all SHT sensors. Change this, if needed | ||||
|     unsigned long shtLastTimeUpdated = 0; // Remembers when we read data the last time | ||||
|     bool shtDataRequested = false; // Reading data is done async. This remembers if we asked the sensor to read data | ||||
|     float shtCurrentTempC = 0; // Last read temperature in Celsius | ||||
|     float shtCurrentTempF = 0; // Last read temperature in Fahrenheit | ||||
|     float shtCurrentHumidity = 0; // Last read humidity in RH% | ||||
|     float shtCurrentTempC = 0.0f; // Last read temperature in Celsius | ||||
|     float shtCurrentHumidity = 0.0f; // Last read humidity in RH% | ||||
|  | ||||
|  | ||||
|     void initShtTempHumiditySensor(); | ||||
|     void cleanupShtTempHumiditySensor(); | ||||
|     void cleanup(); | ||||
|     bool isShtReady(); | ||||
|     inline bool isShtReady() { return shtInitDone; } // Checks if the SHT sensor has been initialised. | ||||
|  | ||||
|     void publishTemperatureAndHumidityViaMqtt(); | ||||
|     void publishHomeAssistantAutodiscovery(); | ||||
| @@ -56,18 +58,22 @@ class ShtUsermod : public Usermod | ||||
|     bool readFromConfig(JsonObject &root); | ||||
|     void addToJsonInfo(JsonObject& root); | ||||
|  | ||||
|     float getTemperatureC(); | ||||
|     float getTemperatureF(); | ||||
|     float getHumidity(); | ||||
|     bool isEnabled() { return enabled; } | ||||
|  | ||||
|     float getTemperature(); | ||||
|     float getTemperatureC() { return roundf(shtCurrentTempC * 10.0f) / 10.0f; } | ||||
|     float getTemperatureF() { return (getTemperatureC() * 1.8f) + 32.0f; } | ||||
|     float getHumidity() { return roundf(shtCurrentHumidity * 10.0f) / 10.0f; } | ||||
|     const char* getUnitString(); | ||||
|  | ||||
|     uint16_t getId() { return USERMOD_ID_SHT; } | ||||
| }; | ||||
|  | ||||
| // Strings to reduce flash memory usage (used more than twice) | ||||
| const char ShtUsermod::_name[]    PROGMEM = "SHT-Sensor"; | ||||
| const char ShtUsermod::_enabled[] PROGMEM = "Enabled"; | ||||
| const char ShtUsermod::_shtType[] PROGMEM = "SHT-Type"; | ||||
| const char ShtUsermod::_unitOfTemp[] PROGMEM = "Unit"; | ||||
| const char ShtUsermod::_name[]            PROGMEM = "SHT-Sensor"; | ||||
| const char ShtUsermod::_enabled[]         PROGMEM = "Enabled"; | ||||
| const char ShtUsermod::_shtType[]         PROGMEM = "SHT-Type"; | ||||
| const char ShtUsermod::_unitOfTemp[]      PROGMEM = "Unit"; | ||||
| const char ShtUsermod::_haMqttDiscovery[] PROGMEM = "Add-To-HA-MQTT-Discovery"; | ||||
|  | ||||
| /** | ||||
| @@ -87,10 +93,9 @@ void ShtUsermod::initShtTempHumiditySensor() | ||||
|     case USERMOD_SHT_TYPE_SHT85: shtTempHumidSensor = (SHT *) new SHT85(); break; | ||||
|   } | ||||
|  | ||||
|   shtTempHumidSensor->begin(shtI2cAddress, i2c_sda, i2c_scl); | ||||
|   shtTempHumidSensor->begin(shtI2cAddress); // uses &Wire | ||||
|   if (shtTempHumidSensor->readStatus() == 0xFFFF) { | ||||
|     DEBUG_PRINTF("[%s] SHT init failed!\n", _name); | ||||
|     cleanupShtTempHumiditySensor(); | ||||
|     cleanup(); | ||||
|     return; | ||||
|   } | ||||
| @@ -109,10 +114,9 @@ void ShtUsermod::cleanupShtTempHumiditySensor() | ||||
| { | ||||
|   if (isShtReady()) { | ||||
|     shtTempHumidSensor->reset(); | ||||
|     delete shtTempHumidSensor; | ||||
|     shtTempHumidSensor = nullptr; | ||||
|   } | ||||
|  | ||||
|   delete shtTempHumidSensor; | ||||
|  | ||||
|   shtInitDone = false; | ||||
| } | ||||
|  | ||||
| @@ -126,29 +130,10 @@ void ShtUsermod::cleanupShtTempHumiditySensor() | ||||
|  */ | ||||
| void ShtUsermod::cleanup() | ||||
| { | ||||
|   if (isShtReady()) { | ||||
|     cleanupShtTempHumiditySensor(); | ||||
|   } | ||||
|  | ||||
|   if (pinAllocDone) { | ||||
|     PinManagerPinType pins[2] = { { i2c_sda, true }, { i2c_scl, true } }; | ||||
|     pinManager.deallocateMultiplePins(pins, 2, PinOwner::HW_I2C); | ||||
|     pinAllocDone = false; | ||||
|   } | ||||
|  | ||||
|   cleanupShtTempHumiditySensor(); | ||||
|   enabled = false; | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Checks if the SHT sensor has been initialised. | ||||
|   * | ||||
|  * @return bool | ||||
|  */ | ||||
| bool ShtUsermod::isShtReady() | ||||
| { | ||||
|   return shtInitDone; | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Publish temperature and humidity to WLED device topic. | ||||
|  * | ||||
| @@ -162,9 +147,9 @@ void ShtUsermod::publishTemperatureAndHumidityViaMqtt() { | ||||
|   char buf[128]; | ||||
|  | ||||
|   snprintf_P(buf, 127, PSTR("%s/temperature"), mqttDeviceTopic); | ||||
|   mqtt->publish(buf, 0, false, String((unitOfTemp ? getTemperatureF() : getTemperatureC())).c_str()); | ||||
|   mqtt->publish(buf, 0, false, String(getTemperature()).c_str()); | ||||
|   snprintf_P(buf, 127, PSTR("%s/humidity"), mqttDeviceTopic); | ||||
|   mqtt->publish(buf, 0, false, String(shtCurrentHumidity).c_str()); | ||||
|   mqtt->publish(buf, 0, false, String(getHumidity()).c_str()); | ||||
| } | ||||
|  | ||||
| /** | ||||
| @@ -191,7 +176,7 @@ void ShtUsermod::publishHomeAssistantAutodiscovery() { | ||||
|   json[F("stat_cla")] = F("measurement"); | ||||
|   snprintf_P(buf, 127, PSTR("%s-temperature"), escapedMac.c_str()); | ||||
|   json[F("uniq_id")] = buf; | ||||
|   json[F("unit_of_meas")] = F("°C"); | ||||
|   json[F("unit_of_meas")] = unitOfTemp ? F("°F") : F("°C"); | ||||
|   appendDeviceToMqttDiscoveryMessage(json); | ||||
|   payload_size = serializeJson(json, json_str); | ||||
|   snprintf_P(buf, 127, PSTR("homeassistant/sensor/%s/%s-temperature/config"), escapedMac.c_str(), escapedMac.c_str()); | ||||
| @@ -222,7 +207,7 @@ void ShtUsermod::publishHomeAssistantAutodiscovery() { | ||||
|  * @return void | ||||
|  */ | ||||
| void ShtUsermod::appendDeviceToMqttDiscoveryMessage(JsonDocument& root) { | ||||
|   JsonObject device = root.createNestedObject("dev"); | ||||
|   JsonObject device = root.createNestedObject(F("dev")); | ||||
|   device[F("ids")] = escapedMac.c_str(); | ||||
|   device[F("name")] = serverDescription; | ||||
|   device[F("sw")] = versionString; | ||||
| @@ -244,14 +229,12 @@ void ShtUsermod::appendDeviceToMqttDiscoveryMessage(JsonDocument& root) { | ||||
| void ShtUsermod::setup() | ||||
| { | ||||
|   if (enabled) { | ||||
|     PinManagerPinType pins[2] = { { i2c_sda, true }, { i2c_scl, true } }; | ||||
|     // GPIOs can be set to -1 and allocateMultiplePins() will return true, so check they're gt zero | ||||
|     if (i2c_sda < 0 || i2c_scl < 0 || !pinManager.allocateMultiplePins(pins, 2, PinOwner::HW_I2C)) { | ||||
|       DEBUG_PRINTF("[%s] SHT pin allocation failed!\n", _name); | ||||
|     // GPIOs can be set to -1 , so check they're gt zero | ||||
|     if (i2c_sda < 0 || i2c_scl < 0) { | ||||
|       DEBUG_PRINTF("[%s] I2C bus not initialised!\n", _name); | ||||
|       cleanup(); | ||||
|       return; | ||||
|     } | ||||
|     pinAllocDone = true; | ||||
|  | ||||
|     initShtTempHumiditySensor(); | ||||
|  | ||||
| @@ -290,13 +273,11 @@ void ShtUsermod::loop() | ||||
|       if (shtTempHumidSensor->dataReady()) { | ||||
|         if (shtTempHumidSensor->readData(false)) { | ||||
|           shtCurrentTempC = shtTempHumidSensor->getTemperature(); | ||||
|           shtCurrentTempF = shtTempHumidSensor->getFahrenheit(); | ||||
|           shtCurrentHumidity = shtTempHumidSensor->getHumidity(); | ||||
|  | ||||
|           publishTemperatureAndHumidityViaMqtt(); | ||||
|           shtReadDataSuccess = true; | ||||
|         } | ||||
|         else { | ||||
|         } else { | ||||
|           shtReadDataSuccess = false; | ||||
|         } | ||||
|  | ||||
| @@ -309,7 +290,7 @@ void ShtUsermod::loop() | ||||
| /** | ||||
|  * Whenever MQTT is connected, publish HA autodiscovery topics. | ||||
|  * | ||||
|  * Is only donce once. | ||||
|  * Is only done once. | ||||
|  * | ||||
|  * @see Usermod::onMqttConnect() | ||||
|  * @see UsermodManager::onMqttConnect() | ||||
| @@ -387,6 +368,7 @@ bool ShtUsermod::readFromConfig(JsonObject &root) | ||||
|  | ||||
|   bool oldEnabled = enabled; | ||||
|   byte oldShtType = shtType; | ||||
|   byte oldUnitOfTemp = unitOfTemp; | ||||
|   bool oldHaMqttDiscovery = haMqttDiscovery; | ||||
|  | ||||
|   getJsonValue(top[FPSTR(_enabled)], enabled); | ||||
| @@ -410,6 +392,11 @@ bool ShtUsermod::readFromConfig(JsonObject &root) | ||||
|       initShtTempHumiditySensor(); | ||||
|     } | ||||
|  | ||||
|     if (oldUnitOfTemp != unitOfTemp) { | ||||
|       publishTemperatureAndHumidityViaMqtt(); | ||||
|       publishHomeAssistantAutodiscovery(); | ||||
|     } | ||||
|  | ||||
|     if (oldHaMqttDiscovery != haMqttDiscovery && haMqttDiscovery) { | ||||
|       publishHomeAssistantAutodiscovery(); | ||||
|     } | ||||
| @@ -448,45 +435,46 @@ void ShtUsermod::addToJsonInfo(JsonObject& root) | ||||
|     if (shtLastTimeUpdated == 0) { | ||||
|       jsonTemp.add(F(" Not read yet")); | ||||
|       jsonHumidity.add(F(" Not read yet")); | ||||
|     } | ||||
|     else { | ||||
|     } else { | ||||
|       jsonTemp.add(F(" Error")); | ||||
|       jsonHumidity.add(F(" Error")); | ||||
|     } | ||||
|  | ||||
|     return; | ||||
|   } | ||||
|  | ||||
|   jsonHumidity.add(shtCurrentHumidity); | ||||
|   jsonHumidity.add(getHumidity()); | ||||
|   jsonHumidity.add(F(" RH")); | ||||
|  | ||||
|   unitOfTemp ? jsonTemp.add(getTemperatureF()) : jsonTemp.add(getTemperatureC()); | ||||
|   unitOfTemp ? jsonTemp.add(F(" °F")) : jsonTemp.add(F(" °C")); | ||||
|   jsonTemp.add(getTemperature()); | ||||
|   jsonTemp.add(getUnitString()); | ||||
|  | ||||
|   // sensor object | ||||
|   JsonObject sensor = root[F("sensor")]; | ||||
|   if (sensor.isNull()) sensor = root.createNestedObject(F("sensor")); | ||||
|  | ||||
|   jsonTemp = sensor.createNestedArray(F("temp")); | ||||
|   jsonTemp.add(getTemperature()); | ||||
|   jsonTemp.add(getUnitString()); | ||||
|  | ||||
|   jsonHumidity = sensor.createNestedArray(F("humidity")); | ||||
|   jsonHumidity.add(getHumidity()); | ||||
|   jsonHumidity.add(F(" RH")); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Getter for last read temperature in Celsius. | ||||
|  * Getter for last read temperature for configured unit. | ||||
|  * | ||||
|  * @return float | ||||
|  */ | ||||
| float ShtUsermod::getTemperatureC() { | ||||
|   return shtCurrentTempC; | ||||
| float ShtUsermod::getTemperature() { | ||||
|   return unitOfTemp ? getTemperatureF() : getTemperatureC(); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Getter for last read temperature in Fahrenheit. | ||||
|  * Returns the current configured unit as human readable string. | ||||
|  * | ||||
|  * @return float | ||||
|  * @return const char* | ||||
|  */ | ||||
| float ShtUsermod::getTemperatureF() { | ||||
|   return shtCurrentTempF; | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Getter for last read humidity in RH%. | ||||
|  * | ||||
|  * @return float | ||||
|  */ | ||||
| float ShtUsermod::getHumidity() { | ||||
|   return shtCurrentHumidity; | ||||
| const char* ShtUsermod::getUnitString() { | ||||
|   return unitOfTemp ? "°F" : "°C"; | ||||
| } | ||||
| @@ -1,3 +1,7 @@ | ||||
| #ifndef WLED_ENABLE_MQTT | ||||
| #error "This user mod requires MQTT to be enabled." | ||||
| #endif | ||||
|  | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
|   | ||||
| @@ -91,7 +91,8 @@ class StairwayWipeUsermod : public Usermod { | ||||
|     void startWipe() | ||||
|     { | ||||
|     bri = briLast; //turn on | ||||
|     transitionDelayTemp = 0; //no transition | ||||
|     jsonTransitionOnce = true; | ||||
|     strip.setTransition(0); //no transition | ||||
|     effectCurrent = FX_MODE_COLOR_WIPE; | ||||
|     resetTimebase(); //make sure wipe starts from beginning | ||||
|  | ||||
| @@ -105,10 +106,11 @@ class StairwayWipeUsermod : public Usermod { | ||||
|  | ||||
|     void turnOff() | ||||
|     { | ||||
|     jsonTransitionOnce = true; | ||||
|     #ifdef STAIRCASE_WIPE_OFF | ||||
|     transitionDelayTemp = 0; //turn off immediately after wipe completed | ||||
|     strip.setTransition(0); //turn off immediately after wipe completed | ||||
|     #else | ||||
|     transitionDelayTemp = 4000; //fade out slowly | ||||
|     strip.setTransition(4000); //fade out slowly | ||||
|     #endif | ||||
|     bri = 0; | ||||
|     stateUpdated(CALL_MODE_NOTIFICATION); | ||||
|   | ||||
| @@ -23,7 +23,7 @@ private: | ||||
|   unsigned char Enc_B; | ||||
|   unsigned char Enc_A_prev = 0; | ||||
|  | ||||
|   // private class memebers configurable by Usermod Settings (defaults set inside readFromConfig()) | ||||
|   // private class members configurable by Usermod Settings (defaults set inside readFromConfig()) | ||||
|   int8_t pins[3]; // pins[0] = DT from encoder, pins[1] = CLK from encoder, pins[2] = CLK from encoder (optional) | ||||
|   int fadeAmount; // how many points to fade the Neopixel with each step | ||||
|  | ||||
| @@ -162,7 +162,7 @@ public: | ||||
|    * - configComplete is used to return false if any value is missing, not just if the main object is missing | ||||
|    * - The defaults are loaded every time readFromConfig() is run, not just once after boot | ||||
|    *  | ||||
|    * This ensures that missing values are added to the config, with their default values, in the rare but plauible cases of: | ||||
|    * This ensures that missing values are added to the config, with their default values, in the rare but plausible cases of: | ||||
|    * - a single value being missing at boot, e.g. if the Usermod was upgraded and a new setting was added | ||||
|    * - a single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) | ||||
|    *  | ||||
|   | ||||
| @@ -101,7 +101,7 @@ class AutoSaveUsermod : public Usermod { | ||||
|     // network here | ||||
|     void setup() { | ||||
|       #ifdef USERMOD_FOUR_LINE_DISPLAY     | ||||
|       // This Usermod has enhanced funcionality if | ||||
|       // This Usermod has enhanced functionality if | ||||
|       // FourLineDisplayUsermod is available. | ||||
|       display = (FourLineDisplayUsermod*) usermods.lookup(USERMOD_ID_FOUR_LINE_DISP); | ||||
|       #endif | ||||
| @@ -148,7 +148,7 @@ class AutoSaveUsermod : public Usermod { | ||||
|  | ||||
|       if (autoSaveAfter && now > autoSaveAfter) { | ||||
|         autoSaveAfter = 0; | ||||
|         // Time to auto save. You may have some flickry? | ||||
|         // Time to auto save. You may have some flickery? | ||||
|         saveSettings(); | ||||
|         displayOverlay(); | ||||
|       } | ||||
|   | ||||
| @@ -23,7 +23,7 @@ This file should be placed in the same directory as `platformio.ini`. | ||||
| * `FLD_PIN_SCL`                - The display SCL pin, defaults to 5 | ||||
| * `FLD_PIN_SDA`                - The display SDA pin, defaults to 4 | ||||
|  | ||||
| All of the parameters can be configured via the Usermods settings page, inluding GPIO pins. | ||||
| All of the parameters can be configured via the Usermods settings page, including GPIO pins. | ||||
|  | ||||
| ### PlatformIO requirements | ||||
|  | ||||
|   | ||||
| @@ -11,7 +11,7 @@ | ||||
| // for WLED. | ||||
| // | ||||
| // Dependencies | ||||
| // * This usermod REQURES the ModeSortUsermod | ||||
| // * This usermod REQUIRES the ModeSortUsermod | ||||
| // * This Usermod works best, by far, when coupled  | ||||
| //   with RotaryEncoderUIUsermod. | ||||
| // | ||||
| @@ -393,7 +393,7 @@ class FourLineDisplayUsermod : public Usermod { | ||||
|         drawString(getCols() - 1, 0, "~"); | ||||
|       } | ||||
|  | ||||
|       // Second row with IP or Psssword | ||||
|       // Second row with IP or Password | ||||
|       drawGlyph(0, lineHeight, 68, u8x8_font_open_iconic_embedded_1x1); // wifi icon | ||||
|       // Print password in AP mode and if led is OFF. | ||||
|       if (apActive && bri == 0) { | ||||
|   | ||||
							
								
								
									
										40
									
								
								usermods/usermod_v2_klipper_percentage/readme.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,40 @@ | ||||
| # Klipper Percentage Usermod | ||||
| This usermod polls the Klipper API every 10s for the progressvalue. | ||||
| The leds are then filled with a solid color according to that progress percentage.  | ||||
| the solid color is the secondary color of the segment. | ||||
|  | ||||
| A corresponding curl command would be: | ||||
| ``` | ||||
| curl --location --request GET 'http://[]/printer/objects/query?virtual_sdcard=progress' | ||||
| ``` | ||||
| ## Usage | ||||
| Compile the source with the buildflag  `-D USERMOD_KLIPPER_PERCENTAGE` added. | ||||
|  | ||||
| You can also use the WLBD bot in the Discord by simply extending an existing build environment: | ||||
| ``` | ||||
| [env:esp32klipper] | ||||
| extends = env:esp32dev | ||||
| build_flags = ${common.build_flags_esp32} -D USERMOD_KLIPPER_PERCENTAGE | ||||
| ``` | ||||
|  | ||||
| ## Settings  | ||||
|  | ||||
| ### Enabled: | ||||
| Checkbox to enable or disable the overlay | ||||
|  | ||||
| ### Klipper IP:  | ||||
| IP address of your Klipper instance you want to poll. ESP has to be restarted after change | ||||
|  | ||||
| ### Direction :  | ||||
| 0 = normal | ||||
|  | ||||
| 1 = reversed | ||||
|  | ||||
| 2 = center | ||||
|  | ||||
| ----- | ||||
| Author: | ||||
|  | ||||
| Sören Willrodt | ||||
|  | ||||
| Discord: Sören#5281 | ||||
| @@ -0,0 +1,222 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include "wled.h" | ||||
|  | ||||
| class klipper_percentage : public Usermod | ||||
| { | ||||
| private: | ||||
|   unsigned long lastTime = 0; | ||||
|   String ip = "192.168.25.207"; | ||||
|   WiFiClient wifiClient; | ||||
|   char errorMessage[100] = ""; | ||||
|   int printPercent = 0; | ||||
|   int direction = 0; // 0 for along the strip, 1 for reversed direction | ||||
|  | ||||
|   static const char _name[]; | ||||
|   static const char _enabled[]; | ||||
|   bool enabled = false; | ||||
|  | ||||
|   void httpGet(WiFiClient &client, char *errorMessage) | ||||
|   { | ||||
|     // https://arduinojson.org/v6/example/http-client/ | ||||
|     // is this the most compact way to do http get and put it in arduinojson object??? | ||||
|     // would like async response ... ??? | ||||
|     client.setTimeout(10000); | ||||
|     if (!client.connect(ip.c_str(), 80)) | ||||
|     { | ||||
|       strcat(errorMessage, PSTR("Connection failed")); | ||||
|     } | ||||
|     else | ||||
|     { | ||||
|       // Send HTTP request | ||||
|       client.println(F("GET /printer/objects/query?virtual_sdcard=progress HTTP/1.0")); | ||||
|       client.println("Host: " + ip); | ||||
|       client.println(F("Connection: close")); | ||||
|       if (client.println() == 0) | ||||
|       { | ||||
|         strcat(errorMessage, PSTR("Failed to send request")); | ||||
|       } | ||||
|       else | ||||
|       { | ||||
|         // Check HTTP status | ||||
|         char status[32] = {0}; | ||||
|         client.readBytesUntil('\r', status, sizeof(status)); | ||||
|         if (strcmp(status, "HTTP/1.1 200 OK") != 0) | ||||
|         { | ||||
|           strcat(errorMessage, PSTR("Unexpected response: ")); | ||||
|           strcat(errorMessage, status); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|           // Skip HTTP headers | ||||
|           char endOfHeaders[] = "\r\n\r\n"; | ||||
|           if (!client.find(endOfHeaders)) | ||||
|           { | ||||
|             strcat(errorMessage, PSTR("Invalid response")); | ||||
|           } | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|   } | ||||
|  | ||||
| public: | ||||
|   void setup() | ||||
|   { | ||||
|   } | ||||
|  | ||||
|   void connected() | ||||
|   { | ||||
|   } | ||||
|  | ||||
|   void loop() | ||||
|   { | ||||
|     if (enabled) | ||||
|     { | ||||
|       if (WLED_CONNECTED) | ||||
|       { | ||||
|         if (millis() - lastTime > 10000) | ||||
|         { | ||||
|           httpGet(wifiClient, errorMessage); | ||||
|           if (strcmp(errorMessage, "") == 0) | ||||
|           { | ||||
|             PSRAMDynamicJsonDocument klipperDoc(4096); // in practice about 2673 | ||||
|             DeserializationError error = deserializeJson(klipperDoc, wifiClient); | ||||
|             if (error) | ||||
|             { | ||||
|               strcat(errorMessage, PSTR("deserializeJson() failed: ")); | ||||
|               strcat(errorMessage, error.c_str()); | ||||
|             } | ||||
|             printPercent = (int)(klipperDoc["result"]["status"]["virtual_sdcard"]["progress"].as<float>() * 100); | ||||
|  | ||||
|             DEBUG_PRINT("Percent: "); | ||||
|             DEBUG_PRINTLN((int)(klipperDoc["result"]["status"]["virtual_sdcard"]["progress"].as<float>() * 100)); | ||||
|             DEBUG_PRINT("LEDs: "); | ||||
|             DEBUG_PRINTLN(direction == 2 ? (strip.getLengthTotal() / 2) * printPercent / 100 : strip.getLengthTotal() * printPercent / 100); | ||||
|           } | ||||
|           else | ||||
|           { | ||||
|             DEBUG_PRINTLN(errorMessage); | ||||
|             DEBUG_PRINTLN(ip); | ||||
|           } | ||||
|           lastTime = millis(); | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   void addToConfig(JsonObject &root) | ||||
|   { | ||||
|     JsonObject top = root.createNestedObject("Klipper Printing Percentage"); | ||||
|     top["Enabled"] = enabled; | ||||
|     top["Klipper IP"] = ip; | ||||
|     top["Direction"] = direction; | ||||
|   } | ||||
|  | ||||
|   bool readFromConfig(JsonObject &root) | ||||
|   { | ||||
|     // default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor | ||||
|     // setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) | ||||
|  | ||||
|     JsonObject top = root["Klipper Printing Percentage"]; | ||||
|  | ||||
|     bool configComplete = !top.isNull(); | ||||
|     configComplete &= getJsonValue(top["Klipper IP"], ip); | ||||
|     configComplete &= getJsonValue(top["Enabled"], enabled); | ||||
|     configComplete &= getJsonValue(top["Direction"], direction); | ||||
|     return configComplete; | ||||
|   } | ||||
|  | ||||
|   /* | ||||
|    * addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API. | ||||
|    * Creating an "u" object allows you to add custom key/value pairs to the Info section of the WLED web UI. | ||||
|    * Below it is shown how this could be used for e.g. a light sensor | ||||
|    */ | ||||
|   void addToJsonInfo(JsonObject &root) | ||||
|   { | ||||
|     JsonObject user = root["u"]; | ||||
|     if (user.isNull()) | ||||
|       user = root.createNestedObject("u"); | ||||
|  | ||||
|     JsonArray infoArr = user.createNestedArray(FPSTR(_name)); | ||||
|     String uiDomString = F("<button class=\"btn btn-xs\" onclick=\"requestJson({"); | ||||
|     uiDomString += FPSTR(_name); | ||||
|     uiDomString += F(":{"); | ||||
|     uiDomString += FPSTR(_enabled); | ||||
|     uiDomString += enabled ? F(":false}});\">") : F(":true}});\">"); | ||||
|     uiDomString += F("<i class=\"icons"); | ||||
|     uiDomString += enabled ? F(" on") : F(" off"); | ||||
|     uiDomString += F("\"></i>"); | ||||
|     uiDomString += F("</button>"); | ||||
|     infoArr.add(uiDomString); | ||||
|   } | ||||
|  | ||||
|   void addToJsonState(JsonObject &root) | ||||
|   { | ||||
|     JsonObject usermod = root[FPSTR(_name)]; | ||||
|     if (usermod.isNull()) | ||||
|     { | ||||
|       usermod = root.createNestedObject(FPSTR(_name)); | ||||
|     } | ||||
|     usermod["on"] = enabled; | ||||
|   } | ||||
|   void readFromJsonState(JsonObject &root) | ||||
|   { | ||||
|     JsonObject usermod = root[FPSTR(_name)]; | ||||
|     if (!usermod.isNull()) | ||||
|     { | ||||
|       if (usermod[FPSTR(_enabled)].is<bool>()) | ||||
|       { | ||||
|         enabled = usermod[FPSTR(_enabled)].as<bool>(); | ||||
|       } | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   /* | ||||
|    * handleOverlayDraw() is called just before every show() (LED strip update frame) after effects have set the colors. | ||||
|    * Use this to blank out some LEDs or set them to a different color regardless of the set effect mode. | ||||
|    * Commonly used for custom clocks (Cronixie, 7 segment) | ||||
|    */ | ||||
|   void handleOverlayDraw() | ||||
|   { | ||||
|     if (enabled) | ||||
|     { | ||||
|       if (direction == 0) // normal | ||||
|       { | ||||
|         for (int i = 0; i < strip.getLengthTotal() * printPercent / 100; i++) | ||||
|         { | ||||
|           strip.setPixelColor(i, strip.getSegment(0).colors[1]); | ||||
|         } | ||||
|       } | ||||
|       else if (direction == 1) // reversed | ||||
|       { | ||||
|         for (int i = 0; i < strip.getLengthTotal() * printPercent / 100; i++) | ||||
|         { | ||||
|           strip.setPixelColor(strip.getLengthTotal() - i, strip.getSegment(0).colors[1]); | ||||
|         } | ||||
|       } | ||||
|       else if (direction == 2) // center | ||||
|       { | ||||
|         for (int i = 0; i < (strip.getLengthTotal() / 2) * printPercent / 100; i++) | ||||
|         { | ||||
|           strip.setPixelColor((strip.getLengthTotal() / 2) + i, strip.getSegment(0).colors[1]); | ||||
|           strip.setPixelColor((strip.getLengthTotal() / 2) - i, strip.getSegment(0).colors[1]); | ||||
|         } | ||||
|       } | ||||
|       else | ||||
|       { | ||||
|         direction = 0; | ||||
|       } | ||||
|     } | ||||
|   } | ||||
|  | ||||
|   /* | ||||
|    * getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!). | ||||
|    * This could be used in the future for the system to determine whether your usermod is installed. | ||||
|    */ | ||||
|   uint16_t getId() | ||||
|   { | ||||
|     return USERMOD_ID_KLIPPER; | ||||
|   } | ||||
| }; | ||||
| const char klipper_percentage::_name[] PROGMEM = "Klipper_Percentage"; | ||||
| const char klipper_percentage::_enabled[] PROGMEM = "enabled"; | ||||
| @@ -7,4 +7,4 @@ Contains a modification to use WLED in combination with the Ping Pong Ball LED C | ||||
| To install this Usermod, you instruct PlatformIO to compile the Project with the USERMOD_PING_PONG_CLOCK flag. | ||||
| WLED then automatically provides you with various settings on the Usermod Page. | ||||
|  | ||||
| Note: Depending on the size of your clock, you may have to update the led indices for the indivdual numbers and the base indices. | ||||
| Note: Depending on the size of your clock, you may have to update the led indices for the individual numbers and the base indices. | ||||
|   | ||||
| @@ -18,15 +18,15 @@ private: | ||||
|  | ||||
|   // ---- Variables for correct LED numbering below, edit only if your clock is built different ---- | ||||
|  | ||||
|   int baseH = 43;  // Adress for the one place of the hours | ||||
|   int baseHH = 7;  // Adress for the tens place of the hours | ||||
|   int baseM = 133; // Adress for the one place of the minutes | ||||
|   int baseMM = 97; // Adress for the tens place of the minutes | ||||
|   int colon1 = 79; // Adress for the first colon led | ||||
|   int colon2 = 80; // Adress for the second colon led | ||||
|   int baseH = 43;  // Address for the one place of the hours | ||||
|   int baseHH = 7;  // Address for the tens place of the hours | ||||
|   int baseM = 133; // Address for the one place of the minutes | ||||
|   int baseMM = 97; // Address for the tens place of the minutes | ||||
|   int colon1 = 79; // Address for the first colon led | ||||
|   int colon2 = 80; // Address for the second colon led | ||||
|  | ||||
|   // Matrix for the illumination of the numbers | ||||
|   // Note: These only define the increments of the base adress. e.g. to define the second Minute you have to add the baseMM to every led position | ||||
|   // Note: These only define the increments of the base address. e.g. to define the second Minute you have to add the baseMM to every led position | ||||
|   const int numbers[10][10] =  | ||||
|     { | ||||
|       {  0,  1,  4,  6, 13, 15, 18, 19, -1, -1 }, // 0: null | ||||
|   | ||||
| @@ -20,7 +20,7 @@ | ||||
| // Change between modes by pressing a button. | ||||
| // | ||||
| // Dependencies | ||||
| // * This usermod REQURES the ModeSortUsermod | ||||
| // * This usermod REQUIRES the ModeSortUsermod | ||||
| // * This Usermod works best coupled with  | ||||
| //   FourLineDisplayUsermod. | ||||
| // | ||||
|   | ||||
| @@ -8,7 +8,7 @@ active: enable/disable usermod | ||||
| diplayItIs: enable/disable display of "Es ist" on the clock | ||||
| ledOffset: number of LEDs before the wordclock LEDs | ||||
|  | ||||
| ### Update for alternatative wiring pattern | ||||
| ### Update for alternative wiring pattern | ||||
| Based on this fantastic work I added an alternative wiring pattern. | ||||
| The original used a long wire to connect DO to DI, from one line to the next line. | ||||
|  | ||||
|   | ||||
| @@ -7,8 +7,8 @@ | ||||
|  * See: https://github.com/Aircoookie/WLED/wiki/Add-own-functionality | ||||
|  *  | ||||
|  * This usermod can be used to drive a wordclock with a 11x10 pixel matrix with WLED. There are also 4 additional dots for the minutes.  | ||||
|  * The visualisation is desribed in 4 mask with LED numbers (single dots for minutes, minutes, hours and "clock/Uhr"). | ||||
|  * There are 2 parameters to chnage the behaviour: | ||||
|  * The visualisation is described in 4 mask with LED numbers (single dots for minutes, minutes, hours and "clock/Uhr"). | ||||
|  * There are 2 parameters to change the behaviour: | ||||
|  *  | ||||
|  * active: enable/disable usermod | ||||
|  * diplayItIs: enable/disable display of "Es ist" on the clock. | ||||
| @@ -25,6 +25,7 @@ class WordClockUsermod : public Usermod | ||||
|     bool displayItIs = false; | ||||
|     int ledOffset = 100; | ||||
|     bool meander = false; | ||||
|     bool nord = false; | ||||
|      | ||||
|     // defines for mask sizes | ||||
|     #define maskSizeLeds        114 | ||||
| @@ -37,39 +38,44 @@ class WordClockUsermod : public Usermod | ||||
|  | ||||
|     // "minute" masks | ||||
|     // Normal wiring | ||||
|     const int maskMinutes[12][maskSizeMinutes] =  | ||||
|     const int maskMinutes[14][maskSizeMinutes] =  | ||||
|     { | ||||
|       {107, 108, 109,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1}, // :00 | ||||
|       {  7,   8,   9,  10,  40,  41,  42,  43,  -1,  -1,  -1,  -1}, // :05 fünf nach | ||||
|       { 11,  12,  13,  14,  40,  41,  42,  43,  -1,  -1,  -1,  -1}, // :10 zehn nach | ||||
|       { 26,  27,  28,  29,  30,  31,  32,  -1,  -1,  -1,  -1,  -1}, // :15 viertel | ||||
|       { 15,  16,  17,  18,  19,  20,  21,  40,  41,  42,  43,  -1}, // :20 zwanzig nach | ||||
|       {  7,   8,   9,  10,  33,  34,  35,  44,  45,  46,  47,  -1}, // :25 fünf vor halb | ||||
|       { 44,  45,  46,  47,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1}, // :30 halb | ||||
|       {  7,   8,   9,  10,  40,  41,  42,  43,  44,  45,  46,  47}, // :35 fünf nach halb | ||||
|       { 15,  16,  17,  18,  19,  20,  21,  33,  34,  35,  -1,  -1}, // :40 zwanzig vor | ||||
|       { 22,  23,  24,  25,  26,  27,  28,  29,  30,  31,  32,  -1}, // :45 dreiviertel | ||||
|       { 11,  12,  13,  14,  33,  34,  35,  -1,  -1,  -1,  -1,  -1}, // :50 zehn vor | ||||
|       {  7,   8,   9,  10,  33,  34,  35,  -1,  -1,  -1,  -1,  -1}  // :55 fünf vor | ||||
|       {107, 108, 109,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1}, // 0 - 00 | ||||
|       {  7,   8,   9,  10,  40,  41,  42,  43,  -1,  -1,  -1,  -1}, // 1 - 05 fünf nach | ||||
|       { 11,  12,  13,  14,  40,  41,  42,  43,  -1,  -1,  -1,  -1}, // 2 - 10 zehn nach | ||||
|       { 26,  27,  28,  29,  30,  31,  32,  -1,  -1,  -1,  -1,  -1}, // 3 - 15 viertel | ||||
|       { 15,  16,  17,  18,  19,  20,  21,  40,  41,  42,  43,  -1}, // 4 - 20 zwanzig nach | ||||
|       {  7,   8,   9,  10,  33,  34,  35,  44,  45,  46,  47,  -1}, // 5 - 25 fünf vor halb | ||||
|       { 44,  45,  46,  47,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1}, // 6 - 30 halb | ||||
|       {  7,   8,   9,  10,  40,  41,  42,  43,  44,  45,  46,  47}, // 7 - 35 fünf nach halb | ||||
|       { 15,  16,  17,  18,  19,  20,  21,  33,  34,  35,  -1,  -1}, // 8 - 40 zwanzig vor | ||||
|       { 22,  23,  24,  25,  26,  27,  28,  29,  30,  31,  32,  -1}, // 9 - 45 dreiviertel | ||||
|       { 11,  12,  13,  14,  33,  34,  35,  -1,  -1,  -1,  -1,  -1}, // 10 - 50 zehn vor | ||||
|       {  7,   8,   9,  10,  33,  34,  35,  -1,  -1,  -1,  -1,  -1}, // 11 - 55 fünf vor | ||||
|       { 26,  27,  28,  29,  30,  31,  32,  40,  41,  42,  43,  -1}, // 12 - 15 alternative viertel nach | ||||
|       { 26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  -1,  -1}  // 13 - 45 alternative viertel vor | ||||
|     }; | ||||
|  | ||||
|     // Meander wiring | ||||
|     const int maskMinutesMea[12][maskSizeMinutesMea] =  | ||||
|     const int maskMinutesMea[14][maskSizeMinutesMea] =  | ||||
|     { | ||||
|       { 99, 100, 101,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1}, // :00 | ||||
|       {  7,   8,   9,  10,  33,  34,  35,  36,  -1,  -1,  -1,  -1}, // :05 fünf nach | ||||
|       { 18,  19,  20,  21,  33,  34,  35,  36,  -1,  -1,  -1,  -1}, // :10 zehn nach | ||||
|       { 26,  27,  28,  29,  30,  31,  32,  -1,  -1,  -1,  -1,  -1}, // :15 viertel | ||||
|       { 11,  12,  13,  14,  15,  16,  17,  33,  34,  35,  36,  -1}, // :20 zwanzig nach | ||||
|       {  7,   8,   9,  10,  41,  42,  43,  44,  45,  46,  47,  -1}, // :25 fünf vor halb | ||||
|       { 44,  45,  46,  47,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1}, // :30 halb | ||||
|       {  7,   8,   9,  10,  33,  34,  35,  36,  44,  45,  46,  47}, // :35 fünf nach halb | ||||
|       { 11,  12,  13,  14,  15,  16,  17,  41,  42,  43,  -1,  -1}, // :40 zwanzig vor | ||||
|       { 22,  23,  24,  25,  26,  27,  28,  29,  30,  31,  32,  -1}, // :45 dreiviertel | ||||
|       { 18,  19,  20,  21,  41,  42,  43,  -1,  -1,  -1,  -1,  -1}, // :50 zehn vor | ||||
|       {  7,   8,   9,  10,  41,  42,  43,  -1,  -1,  -1,  -1,  -1}  // :55 fünf vor | ||||
|       { 99, 100, 101,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1}, // 0 - 00 | ||||
|       {  7,   8,   9,  10,  33,  34,  35,  36,  -1,  -1,  -1,  -1}, // 1 - 05 fünf nach | ||||
|       { 18,  19,  20,  21,  33,  34,  35,  36,  -1,  -1,  -1,  -1}, // 2 - 10 zehn nach | ||||
|       { 26,  27,  28,  29,  30,  31,  32,  -1,  -1,  -1,  -1,  -1}, // 3 - 15 viertel | ||||
|       { 11,  12,  13,  14,  15,  16,  17,  33,  34,  35,  36,  -1}, // 4 - 20 zwanzig nach | ||||
|       {  7,   8,   9,  10,  41,  42,  43,  44,  45,  46,  47,  -1}, // 5 - 25 fünf vor halb | ||||
|       { 44,  45,  46,  47,  -1,  -1,  -1,  -1,  -1,  -1,  -1,  -1}, // 6 - 30 halb | ||||
|       {  7,   8,   9,  10,  33,  34,  35,  36,  44,  45,  46,  47}, // 7 - 35 fünf nach halb | ||||
|       { 11,  12,  13,  14,  15,  16,  17,  41,  42,  43,  -1,  -1}, // 8 - 40 zwanzig vor | ||||
|       { 22,  23,  24,  25,  26,  27,  28,  29,  30,  31,  32,  -1}, // 9 - 45 dreiviertel | ||||
|       { 18,  19,  20,  21,  41,  42,  43,  -1,  -1,  -1,  -1,  -1}, // 10 - 50 zehn vor | ||||
|       {  7,   8,   9,  10,  41,  42,  43,  -1,  -1,  -1,  -1,  -1}, // 11 - 55 fünf vor | ||||
|       { 26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  36,  -1}, // 12 - 15 alternative viertel nach | ||||
|       { 26,  27,  28,  29,  30,  31,  32,  41,  42,  43,  -1,  -1}  // 13 - 45 alternative viertel vor | ||||
|     }; | ||||
|  | ||||
|  | ||||
|     // hour masks | ||||
|     // Normal wiring | ||||
|     const int maskHours[13][maskSizeHours] =  | ||||
| @@ -242,9 +248,15 @@ class WordClockUsermod : public Usermod | ||||
|             setHours(hours, false); | ||||
|             break; | ||||
|         case 3: | ||||
|             // viertel | ||||
|             setMinutes(3); | ||||
|             setHours(hours + 1, false); | ||||
|             if (nord) { | ||||
|               // viertel nach | ||||
|               setMinutes(12); | ||||
|               setHours(hours, false); | ||||
|             } else { | ||||
|               // viertel  | ||||
|               setMinutes(3); | ||||
|               setHours(hours + 1, false); | ||||
|             }; | ||||
|             break; | ||||
|         case 4: | ||||
|             // 20 nach | ||||
| @@ -273,7 +285,13 @@ class WordClockUsermod : public Usermod | ||||
|             break; | ||||
|         case 9: | ||||
|             // viertel vor | ||||
|             setMinutes(9); | ||||
|             if (nord) { | ||||
|               setMinutes(13); | ||||
|             }  | ||||
|             // dreiviertel | ||||
|               else { | ||||
|               setMinutes(9); | ||||
|             } | ||||
|             setHours(hours + 1, false); | ||||
|             break; | ||||
|         case 10: | ||||
| @@ -405,11 +423,18 @@ class WordClockUsermod : public Usermod | ||||
|      */ | ||||
|     void addToConfig(JsonObject& root) | ||||
|     { | ||||
|       JsonObject top = root.createNestedObject("WordClockUsermod"); | ||||
|       top["active"] = usermodActive; | ||||
|       top["displayItIs"] = displayItIs; | ||||
|       top["ledOffset"] = ledOffset; | ||||
|       top["Meander wiring?"] = meander; | ||||
|       JsonObject top = root.createNestedObject(F("WordClockUsermod")); | ||||
|       top[F("active")] = usermodActive; | ||||
|       top[F("displayItIs")] = displayItIs; | ||||
|       top[F("ledOffset")] = ledOffset; | ||||
|       top[F("Meander wiring?")] = meander; | ||||
|       top[F("Norddeutsch")] = nord; | ||||
|     } | ||||
|  | ||||
|     void appendConfigData() | ||||
|     { | ||||
|       oappend(SET_F("addInfo('WordClockUsermod:ledOffset', 1, 'Number of LEDs before the letters');")); | ||||
|       oappend(SET_F("addInfo('WordClockUsermod:Norddeutsch', 1, 'Viertel vor instead of Dreiviertel');")); | ||||
|     } | ||||
|  | ||||
|     /* | ||||
| @@ -432,14 +457,15 @@ class WordClockUsermod : public Usermod | ||||
|       // default settings values could be set here (or below using the 3-argument getJsonValue()) instead of in the class definition or constructor | ||||
|       // setting them inside readFromConfig() is slightly more robust, handling the rare but plausible use case of single value being missing after boot (e.g. if the cfg.json was manually edited and a value was removed) | ||||
|  | ||||
|       JsonObject top = root["WordClockUsermod"]; | ||||
|       JsonObject top = root[F("WordClockUsermod")]; | ||||
|  | ||||
|       bool configComplete = !top.isNull(); | ||||
|  | ||||
|       configComplete &= getJsonValue(top["active"], usermodActive); | ||||
|       configComplete &= getJsonValue(top["displayItIs"], displayItIs); | ||||
|       configComplete &= getJsonValue(top["ledOffset"], ledOffset); | ||||
|       configComplete &= getJsonValue(top["Meander wiring?"], meander); | ||||
|       configComplete &= getJsonValue(top[F("active")], usermodActive); | ||||
|       configComplete &= getJsonValue(top[F("displayItIs")], displayItIs); | ||||
|       configComplete &= getJsonValue(top[F("ledOffset")], ledOffset); | ||||
|       configComplete &= getJsonValue(top[F("Meander wiring?")], meander); | ||||
|       configComplete &= getJsonValue(top[F("Norddeutsch")], nord); | ||||
|  | ||||
|       return configComplete; | ||||
|     } | ||||
|   | ||||
							
								
								
									
										22
									
								
								usermods/wireguard/platformio_override.ini
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,22 @@ | ||||
| # Example PlatformIO Project Configuration Override for WireGuard | ||||
| # ------------------------------------------------------------------------------ | ||||
| # Copy to platformio_override.ini to activate. | ||||
| # ------------------------------------------------------------------------------ | ||||
| # Please visit documentation: https://docs.platformio.org/page/projectconf.html | ||||
|  | ||||
| [platformio] | ||||
| default_envs = WLED_ESP32-WireGuard | ||||
|  | ||||
| [env:WLED_ESP32-WireGuard] | ||||
| board = esp32dev | ||||
| platform = ${esp32.platform} | ||||
| platform_packages = ${esp32.platform_packages} | ||||
| build_unflags = ${common.build_unflags} | ||||
| build_flags = ${common.build_flags_esp32}  | ||||
|    -D WLED_RELEASE_NAME=ESP32-WireGuard | ||||
|    -D USERMOD_WIREGUARD | ||||
| lib_deps = ${esp32.lib_deps} | ||||
|    https://github.com/kienvu58/WireGuard-ESP32-Arduino.git | ||||
| monitor_filters = esp32_exception_decoder | ||||
| board_build.partitions = ${esp32.default_partitions} | ||||
| upload_speed = 921600 | ||||
							
								
								
									
										19
									
								
								usermods/wireguard/readme.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,19 @@ | ||||
| # WireGuard VPN | ||||
|  | ||||
| This usermod will connect your WLED instance to a remote WireGuard subnet. | ||||
|  | ||||
| Configuration is performed via the Usermod menu. There are no parameters to set in code! | ||||
|  | ||||
| ## Installation  | ||||
|  | ||||
| Copy the `platformio_override.ini` file to the root project directory, review the build options, and select the `WLED_ESP32-WireGuard` environment. | ||||
|  | ||||
|  | ||||
| ## Author | ||||
|  | ||||
| Aiden Vigue [vigue.me](https://vigue.me) | ||||
| [@acvigue](https://github.com/acvigue) | ||||
| aiden@vigue.me | ||||
|  | ||||
|  | ||||
|  | ||||
							
								
								
									
										127
									
								
								usermods/wireguard/wireguard.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,127 @@ | ||||
| #pragma once | ||||
|  | ||||
| #include <WireGuard-ESP32.h> | ||||
|  | ||||
| #include "wled.h" | ||||
|  | ||||
| class WireguardUsermod : public Usermod { | ||||
|    public: | ||||
|     void setup() { configTzTime(posix_tz, ntpServerName); } | ||||
|  | ||||
|     void connected() { | ||||
|         if (wg.is_initialized()) { | ||||
|             wg.end(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     void loop() { | ||||
|         if (millis() - lastTime > 5000) { | ||||
|             if (is_enabled && WLED_CONNECTED) { | ||||
|                 if (!wg.is_initialized()) { | ||||
|                     struct tm timeinfo; | ||||
|                     if (getLocalTime(&timeinfo, 0)) { | ||||
|                         if (strlen(preshared_key) < 1) { | ||||
|                             wg.begin(local_ip, private_key, endpoint_address, public_key, endpoint_port, NULL); | ||||
|                         } else { | ||||
|                             wg.begin(local_ip, private_key, endpoint_address, public_key, endpoint_port, preshared_key); | ||||
|                         } | ||||
|                     } | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             lastTime = millis(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     void addToJsonInfo(JsonObject& root) { | ||||
|         JsonObject user = root["u"]; | ||||
|         if (user.isNull()) user = root.createNestedObject("u"); | ||||
|  | ||||
|         JsonArray infoArr = user.createNestedArray(F("WireGuard")); | ||||
|         String uiDomString; | ||||
|  | ||||
|         struct tm timeinfo; | ||||
|         if (!getLocalTime(&timeinfo, 0)) { | ||||
|             uiDomString = "Time out of sync!"; | ||||
|         } else { | ||||
|             if (wg.is_initialized()) { | ||||
|                 uiDomString = "netif up!"; | ||||
|             } else { | ||||
|                 uiDomString = "netif down :("; | ||||
|             } | ||||
|         } | ||||
|         if (is_enabled) infoArr.add(uiDomString); | ||||
|     } | ||||
|  | ||||
|     void appendConfigData() { | ||||
|         oappend(SET_F("addInfo('WireGuard:host',1,'Server Hostname');"));           // 0 is field type, 1 is actual field | ||||
|         oappend(SET_F("addInfo('WireGuard:port',1,'Server Port');"));               // 0 is field type, 1 is actual field | ||||
|         oappend(SET_F("addInfo('WireGuard:ip',1,'Device IP');"));                   // 0 is field type, 1 is actual field | ||||
|         oappend(SET_F("addInfo('WireGuard:psk',1,'Pre Shared Key (optional)');"));  // 0 is field type, 1 is actual field | ||||
|         oappend(SET_F("addInfo('WireGuard:pem',1,'Private Key');"));                // 0 is field type, 1 is actual field | ||||
|         oappend(SET_F("addInfo('WireGuard:pub',1,'Public Key');"));                 // 0 is field type, 1 is actual field | ||||
|         oappend(SET_F("addInfo('WireGuard:tz',1,'POSIX timezone string');"));       // 0 is field type, 1 is actual field | ||||
|     } | ||||
|  | ||||
|     void addToConfig(JsonObject& root) { | ||||
|         JsonObject top = root.createNestedObject(F("WireGuard")); | ||||
|         top[F("host")] = endpoint_address; | ||||
|         top[F("port")] = endpoint_port; | ||||
|         top[F("ip")] = local_ip.toString(); | ||||
|         top[F("psk")] = preshared_key; | ||||
|         top[F("pem")] = private_key; | ||||
|         top[F("pub")] = public_key; | ||||
|         top[F("tz")] = posix_tz; | ||||
|     } | ||||
|  | ||||
|     bool readFromConfig(JsonObject& root) { | ||||
|         JsonObject top = root[F("WireGuard")]; | ||||
|  | ||||
|         if (top["host"].isNull() || top["port"].isNull() || top["ip"].isNull() || top["pem"].isNull() || top["pub"].isNull() || top["tz"].isNull()) { | ||||
|             is_enabled = false; | ||||
|             return false; | ||||
|         } else { | ||||
|             const char* host = top["host"]; | ||||
|             strncpy(endpoint_address, host, 100); | ||||
|  | ||||
|             const char* ip_s = top["ip"]; | ||||
|             uint8_t ip[4]; | ||||
|             sscanf(ip_s, "%u.%u.%u.%u", &ip[0], &ip[1], &ip[2], &ip[3]); | ||||
|             local_ip = IPAddress(ip[0], ip[1], ip[2], ip[3]); | ||||
|  | ||||
|             const char* pem = top["pem"]; | ||||
|             strncpy(private_key, pem, 45); | ||||
|  | ||||
|             const char* pub = top["pub"]; | ||||
|             strncpy(public_key, pub, 45); | ||||
|  | ||||
|             const char* tz = top["tz"]; | ||||
|             strncpy(posix_tz, tz, 150); | ||||
|  | ||||
|             endpoint_port = top["port"]; | ||||
|  | ||||
|             if (!top["psk"].isNull()) { | ||||
|                 const char* psk = top["psk"]; | ||||
|                 strncpy(preshared_key, psk, 45); | ||||
|             } | ||||
|  | ||||
|             is_enabled = true; | ||||
|         } | ||||
|  | ||||
|         return is_enabled; | ||||
|     } | ||||
|  | ||||
|     uint16_t getId() { return USERMOD_ID_WIREGUARD; } | ||||
|  | ||||
|    private: | ||||
|     WireGuard wg; | ||||
|     char preshared_key[45]; | ||||
|     char private_key[45]; | ||||
|     IPAddress local_ip; | ||||
|     char public_key[45]; | ||||
|     char endpoint_address[100]; | ||||
|     char posix_tz[150]; | ||||
|     int endpoint_port = 0; | ||||
|     bool is_enabled = false; | ||||
|     unsigned long lastTime = 0; | ||||
| }; | ||||
| @@ -1,6 +1,6 @@ | ||||
| # Controlling Wiz lights | ||||
|  | ||||
| Enabless controlling [WiZ](https://www.wizconnected.com/en/consumer/) lights that are part of the same network as the WLED controller. | ||||
| Enables controlling [WiZ](https://www.wizconnected.com/en/consumer/) lights that are part of the same network as the WLED controller. | ||||
|  | ||||
| The mod takes the colors from the first few pixels and sends them to the lights. | ||||
|  | ||||
| @@ -8,7 +8,7 @@ The mod takes the colors from the first few pixels and sends them to the lights. | ||||
|  | ||||
| - Interval (ms) | ||||
|     - How frequently to update the WiZ lights, in milliseconds. | ||||
|     - Setting it too low may causse the ESP to become unresponsive. | ||||
|     - Setting it too low may cause the ESP to become unresponsive. | ||||
| - Send Delay (ms) | ||||
|     - An optional millisecond delay after updating each WiZ light.  | ||||
|     - Can help smooth out effects when using a large number of WiZ lights | ||||
|   | ||||
							
								
								
									
										25
									
								
								wled00.sln
									
									
									
									
									
								
							
							
						
						| @@ -1,25 +0,0 @@ | ||||
|  | ||||
| Microsoft Visual Studio Solution File, Format Version 12.00 | ||||
| # Visual Studio 15 | ||||
| VisualStudioVersion = 15.0.28010.2046 | ||||
| MinimumVisualStudioVersion = 10.0.40219.1 | ||||
| Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "wled00", "wled00\wled00.vcxproj", "{C5F80730-F44F-4478-BDAE-6634EFC2CA88}" | ||||
| EndProject | ||||
| Global | ||||
| 	GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||||
| 		Debug|x86 = Debug|x86 | ||||
| 		Release|x86 = Release|x86 | ||||
| 	EndGlobalSection | ||||
| 	GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||||
| 		{C5F80730-F44F-4478-BDAE-6634EFC2CA88}.Debug|x86.ActiveCfg = Debug|Win32 | ||||
| 		{C5F80730-F44F-4478-BDAE-6634EFC2CA88}.Debug|x86.Build.0 = Debug|Win32 | ||||
| 		{C5F80730-F44F-4478-BDAE-6634EFC2CA88}.Release|x86.ActiveCfg = Release|Win32 | ||||
| 		{C5F80730-F44F-4478-BDAE-6634EFC2CA88}.Release|x86.Build.0 = Release|Win32 | ||||
| 	EndGlobalSection | ||||
| 	GlobalSection(SolutionProperties) = preSolution | ||||
| 		HideSolutionNode = FALSE | ||||
| 	EndGlobalSection | ||||
| 	GlobalSection(ExtensibilityGlobals) = postSolution | ||||
| 		SolutionGuid = {9A679C2B-61D3-400B-B96F-06E604E9CED2} | ||||
| 	EndGlobalSection | ||||
| EndGlobal | ||||
							
								
								
									
										1890
									
								
								wled00/FX.cpp
									
									
									
									
									
								
							
							
						
						
							
								
								
									
										317
									
								
								wled00/FX.h
									
									
									
									
									
								
							
							
						
						| @@ -72,7 +72,11 @@ | ||||
|   #ifndef MAX_NUM_SEGMENTS | ||||
|     #define MAX_NUM_SEGMENTS  32 | ||||
|   #endif | ||||
|   #define MAX_SEGMENT_DATA  32767 | ||||
|   #if defined(ARDUINO_ARCH_ESP32S2) | ||||
|     #define MAX_SEGMENT_DATA  24576 | ||||
|   #else | ||||
|     #define MAX_SEGMENT_DATA  32767 | ||||
|   #endif | ||||
| #endif | ||||
|  | ||||
| /* How much data bytes each segment should max allocate to leave enough space for other segments, | ||||
| @@ -105,20 +109,15 @@ | ||||
| #define PINK       (uint32_t)0xFF1493 | ||||
| #define ULTRAWHITE (uint32_t)0xFFFFFFFF | ||||
| #define DARKSLATEGRAY (uint32_t)0x2F4F4F | ||||
| #define DARKSLATEGREY (uint32_t)0x2F4F4F | ||||
| #define DARKSLATEGREY DARKSLATEGRAY | ||||
|  | ||||
| // options | ||||
| // bit    7: segment is in transition mode | ||||
| // bits 4-6: TBD | ||||
| // bit    3: mirror effect within segment | ||||
| // bit    2: segment is on | ||||
| // bit    1: reverse segment | ||||
| // bit    0: segment is selected | ||||
| // segment options | ||||
| #define NO_OPTIONS   (uint16_t)0x0000 | ||||
| #define TRANSPOSED   (uint16_t)0x0400 // rotated 90deg & reversed | ||||
| #define REVERSE_Y_2D (uint16_t)0x0200 | ||||
| #define MIRROR_Y_2D  (uint16_t)0x0100 | ||||
| #define TRANSITIONAL (uint16_t)0x0080 | ||||
| #define TRANSPOSED   (uint16_t)0x0100 // rotated 90deg & reversed | ||||
| #define MIRROR_Y_2D  (uint16_t)0x0080 | ||||
| #define REVERSE_Y_2D (uint16_t)0x0040 | ||||
| #define RESET_REQ    (uint16_t)0x0020 | ||||
| #define FROZEN       (uint16_t)0x0010 | ||||
| #define MIRROR       (uint16_t)0x0008 | ||||
| #define SEGMENT_ON   (uint16_t)0x0004 | ||||
| #define REVERSE      (uint16_t)0x0002 | ||||
| @@ -143,7 +142,7 @@ | ||||
| #define FX_MODE_SAW                     16 | ||||
| #define FX_MODE_TWINKLE                 17 | ||||
| #define FX_MODE_DISSOLVE                18 | ||||
| #define FX_MODE_DISSOLVE_RANDOM         19 | ||||
| #define FX_MODE_DISSOLVE_RANDOM         19  // candidate for removal (use Dissolve with with check 3) | ||||
| #define FX_MODE_SPARKLE                 20 | ||||
| #define FX_MODE_FLASH_SPARKLE           21 | ||||
| #define FX_MODE_HYPER_SPARKLE           22 | ||||
| @@ -172,7 +171,7 @@ | ||||
| #define FX_MODE_FIRE_FLICKER            45 | ||||
| #define FX_MODE_GRADIENT                46 | ||||
| #define FX_MODE_LOADING                 47 | ||||
| // #define FX_MODE_POLICE                  48  // removed in 0.14! | ||||
| #define FX_MODE_ROLLINGBALLS            48  //was Police before 0.14 | ||||
| #define FX_MODE_FAIRY                   49  //was Police All prior to 0.13.0-b6 (use "Two Dots" with Red/Blue and full intensity) | ||||
| #define FX_MODE_TWO_DOTS                50 | ||||
| #define FX_MODE_FAIRYTWINKLE            51  //was Two Areas prior to 0.13.0-b6 (use "Two Dots" with full intensity) | ||||
| @@ -227,7 +226,7 @@ | ||||
| #define FX_MODE_HEARTBEAT              100 | ||||
| #define FX_MODE_PACIFICA               101 | ||||
| #define FX_MODE_CANDLE_MULTI           102 | ||||
| #define FX_MODE_SOLID_GLITTER          103 | ||||
| #define FX_MODE_SOLID_GLITTER          103  // candidate for removal (use glitter) | ||||
| #define FX_MODE_SUNRISE                104 | ||||
| #define FX_MODE_PHASED                 105 | ||||
| #define FX_MODE_TWINKLEUP              106 | ||||
| @@ -241,7 +240,7 @@ | ||||
| // #define FX_MODE_CANDY_CANE             114  // removed in 0.14! | ||||
| #define FX_MODE_BLENDS                 115 | ||||
| #define FX_MODE_TV_SIMULATOR           116 | ||||
| #define FX_MODE_DYNAMIC_SMOOTH         117 | ||||
| #define FX_MODE_DYNAMIC_SMOOTH         117 // candidate for removal (check3 in dynamic) | ||||
|  | ||||
| // new 0.14 2D effects | ||||
| #define FX_MODE_2DSPACESHIPS           118 //gap fill | ||||
| @@ -250,6 +249,10 @@ | ||||
| #define FX_MODE_2DBLOBS                121 //gap fill | ||||
| #define FX_MODE_2DSCROLLTEXT           122 //gap fill | ||||
| #define FX_MODE_2DDRIFTROSE            123 //gap fill | ||||
| #define FX_MODE_2DDISTORTIONWAVES      124 //gap fill | ||||
| #define FX_MODE_2DSOAP                 125 //gap fill | ||||
| #define FX_MODE_2DOCTOPUS              126 //gap fill | ||||
| #define FX_MODE_2DWAVINGCELL           127 //gap fill | ||||
|  | ||||
| // WLED-SR effects (SR compatible IDs !!!) | ||||
| #define FX_MODE_PIXELS                 128 | ||||
| @@ -321,7 +324,7 @@ typedef enum mapping1D2D { | ||||
|   M12_pCorner = 3 | ||||
| } mapping1D2D_t; | ||||
|  | ||||
| // segment, 72 bytes | ||||
| // segment, 80 bytes | ||||
| typedef struct Segment { | ||||
|   public: | ||||
|     uint16_t start; // start index / start X coordinate 2D (left) | ||||
| @@ -340,12 +343,12 @@ typedef struct Segment { | ||||
|         bool    mirror      : 1;  //     3 : mirrored | ||||
|         bool    freeze      : 1;  //     4 : paused/frozen | ||||
|         bool    reset       : 1;  //     5 : indicates that Segment runtime requires reset | ||||
|         bool    transitional: 1;  //     6 : transitional (there is transition occuring) | ||||
|         bool    reverse_y   : 1;  //     7 : reversed Y (2D) | ||||
|         bool    mirror_y    : 1;  //     8 : mirrored Y (2D) | ||||
|         bool    transpose   : 1;  //     9 : transposed (2D, swapped X & Y) | ||||
|         uint8_t map1D2D     : 3;  // 10-12 : mapping for 1D effect on 2D (0-use as strip, 1-expand vertically, 2-circular/arc, 3-rectangular/corner, ...) | ||||
|         uint8_t soundSim    : 3;  // 13-15 : 0-7 sound simulation types | ||||
|         bool    reverse_y   : 1;  //     6 : reversed Y (2D) | ||||
|         bool    mirror_y    : 1;  //     7 : mirrored Y (2D) | ||||
|         bool    transpose   : 1;  //     8 : transposed (2D, swapped X & Y) | ||||
|         uint8_t map1D2D     : 3;  //  9-11 : mapping for 1D effect on 2D (0-use as strip, 1-expand vertically, 2-circular/arc, 3-rectangular/corner, ...) | ||||
|         uint8_t soundSim    : 2;  // 12-13 : 0-3 sound simulation types ("soft" & "hard" or "on"/"off") | ||||
|         uint8_t set         : 2;  // 14-15 : 0-3 UI segment sets/groups | ||||
|       }; | ||||
|     }; | ||||
|     uint8_t  grouping, spacing; | ||||
| @@ -361,7 +364,7 @@ typedef struct Segment { | ||||
|     }; | ||||
|     uint8_t startY;  // start Y coodrinate 2D (top); there should be no more than 255 rows | ||||
|     uint8_t stopY;   // stop Y coordinate 2D (bottom); there should be no more than 255 rows | ||||
|     char *name; | ||||
|     char    *name; | ||||
|  | ||||
|     // runtime data | ||||
|     unsigned long next_time;  // millis() of next update | ||||
| @@ -369,11 +372,33 @@ typedef struct Segment { | ||||
|     uint32_t call;  // call counter | ||||
|     uint16_t aux0;  // custom var | ||||
|     uint16_t aux1;  // custom var | ||||
|     byte* data;     // effect data pointer | ||||
|     CRGB* leds;     // local leds[] array (may be a pointer to global) | ||||
|     static CRGB *_globalLeds;             // global leds[] array | ||||
|     byte     *data; // effect data pointer | ||||
|     static uint16_t maxWidth, maxHeight;  // these define matrix width & height (max. segment dimensions) | ||||
|  | ||||
|     typedef struct TemporarySegmentData { | ||||
|       uint16_t _optionsT; | ||||
|       uint32_t _colorT[NUM_COLORS]; | ||||
|       uint8_t  _speedT; | ||||
|       uint8_t  _intensityT; | ||||
|       uint8_t  _custom1T, _custom2T;   // custom FX parameters/sliders | ||||
|       struct { | ||||
|         uint8_t _custom3T : 5;        // reduced range slider (0-31) | ||||
|         bool    _check1T  : 1;        // checkmark 1 | ||||
|         bool    _check2T  : 1;        // checkmark 2 | ||||
|         bool    _check3T  : 1;        // checkmark 3 | ||||
|       }; | ||||
|       uint16_t _aux0T; | ||||
|       uint16_t _aux1T; | ||||
|       uint32_t _stepT; | ||||
|       uint32_t _callT; | ||||
|       uint8_t *_dataT; | ||||
|       uint16_t _dataLenT; | ||||
|       TemporarySegmentData() | ||||
|         : _dataT(nullptr) // just in case... | ||||
|         , _dataLenT(0) | ||||
|       {} | ||||
|     } tmpsegd_t; | ||||
|  | ||||
|   private: | ||||
|     union { | ||||
|       uint8_t  _capabilities; | ||||
| @@ -385,42 +410,37 @@ typedef struct Segment { | ||||
|         uint8_t _reserved : 4; | ||||
|       }; | ||||
|     }; | ||||
|     uint16_t _dataLen; | ||||
|     uint16_t        _dataLen; | ||||
|     static uint16_t _usedSegmentData; | ||||
|  | ||||
|     // transition data, valid only if transitional==true, holds values during transition | ||||
|     // perhaps this should be per segment, not static | ||||
|     static CRGBPalette16 _randomPalette;      // actual random palette | ||||
|     static CRGBPalette16 _newRandomPalette;   // target random palette | ||||
|     static unsigned long _lastPaletteChange;  // last random palette change time in millis() | ||||
|     #ifndef WLED_DISABLE_MODE_BLEND | ||||
|     static bool          _modeBlend;          // mode/effect blending semaphore | ||||
|     #endif | ||||
|  | ||||
|     // transition data, valid only if transitional==true, holds values during transition (72 bytes) | ||||
|     struct Transition { | ||||
|       #ifndef WLED_DISABLE_MODE_BLEND | ||||
|       tmpsegd_t     _segT;        // previous segment environment | ||||
|       uint8_t       _modeT;       // previous mode/effect | ||||
|       #else | ||||
|       uint32_t      _colorT[NUM_COLORS]; | ||||
|       #endif | ||||
|       uint8_t       _briT;        // temporary brightness | ||||
|       uint8_t       _cctT;        // temporary CCT | ||||
|       CRGBPalette16 _palT;        // temporary palette | ||||
|       uint8_t       _prevPaletteBlends; // number of previous palette blends (there are max 255 belnds possible) | ||||
|       uint8_t       _modeP;       // previous mode/effect | ||||
|       //uint16_t      _aux0, _aux1; // previous mode/effect runtime data | ||||
|       //uint32_t      _step, _call; // previous mode/effect runtime data | ||||
|       //byte         *_data;        // previous mode/effect runtime data | ||||
|       uint32_t      _start; | ||||
|       uint8_t       _prevPaletteBlends; // number of previous palette blends (there are max 255 blends possible) | ||||
|       unsigned long _start;       // must accommodate millis() | ||||
|       uint16_t      _dur; | ||||
|       Transition(uint16_t dur=750) | ||||
|         : _briT(255) | ||||
|         , _cctT(127) | ||||
|         , _palT(CRGBPalette16(CRGB::Black)) | ||||
|         : _palT(CRGBPalette16(CRGB::Black)) | ||||
|         , _prevPaletteBlends(0) | ||||
|         , _modeP(FX_MODE_STATIC) | ||||
|         , _start(millis()) | ||||
|         , _dur(dur) | ||||
|       {} | ||||
|       Transition(uint16_t d, uint8_t b, uint8_t c, const uint32_t *o) | ||||
|         : _briT(b) | ||||
|         , _cctT(c) | ||||
|         , _palT(CRGBPalette16(CRGB::Black)) | ||||
|         , _prevPaletteBlends(0) | ||||
|         , _modeP(FX_MODE_STATIC) | ||||
|         , _start(millis()) | ||||
|         , _dur(d) | ||||
|       { | ||||
|         for (size_t i=0; i<NUM_COLORS; i++) _colorT[i] = o[i]; | ||||
|       } | ||||
|     } *_t; | ||||
|  | ||||
|   public: | ||||
| @@ -454,12 +474,13 @@ typedef struct Segment { | ||||
|       aux0(0), | ||||
|       aux1(0), | ||||
|       data(nullptr), | ||||
|       leds(nullptr), | ||||
|       _capabilities(0), | ||||
|       _dataLen(0), | ||||
|       _t(nullptr) | ||||
|     { | ||||
|       refreshLightCapabilities(); | ||||
|       #ifdef WLED_DEBUG | ||||
|       //Serial.printf("-- Creating segment: %p\n", this); | ||||
|       #endif | ||||
|     } | ||||
|  | ||||
|     Segment(uint16_t sStartX, uint16_t sStopX, uint16_t sStartY, uint16_t sStopY) : Segment(sStartX, sStopX) { | ||||
| @@ -471,16 +492,14 @@ typedef struct Segment { | ||||
|     Segment(Segment &&orig) noexcept; // move constructor | ||||
|  | ||||
|     ~Segment() { | ||||
|       //#ifdef WLED_DEBUG | ||||
|       //Serial.print(F("Destroying segment:")); | ||||
|       #ifdef WLED_DEBUG | ||||
|       //Serial.printf("-- Destroying segment: %p\n", this); | ||||
|       //if (name) Serial.printf(" %s (%p)", name, name); | ||||
|       //if (data) Serial.printf(" %d (%p)", (int)_dataLen, data); | ||||
|       //if (leds) Serial.printf(" [%u]", length()*sizeof(CRGB)); | ||||
|       //Serial.println(); | ||||
|       //#endif | ||||
|       if (!Segment::_globalLeds && leds) free(leds); | ||||
|       if (name) delete[] name; | ||||
|       if (_t) delete _t; | ||||
|       #endif | ||||
|       if (name) { delete[] name; name = nullptr; } | ||||
|       stopTransition(); | ||||
|       deallocateData(); | ||||
|     } | ||||
|  | ||||
| @@ -488,22 +507,31 @@ typedef struct Segment { | ||||
|     Segment& operator= (Segment &&orig) noexcept; // move assignment | ||||
|  | ||||
| #ifdef WLED_DEBUG | ||||
|     size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0) + (!Segment::_globalLeds && leds?sizeof(CRGB)*length():0); } | ||||
|     size_t getSize() const { return sizeof(Segment) + (data?_dataLen:0) + (name?strlen(name):0) + (_t?sizeof(Transition):0); } | ||||
| #endif | ||||
|  | ||||
|     inline bool     getOption(uint8_t n) const { return ((options >> n) & 0x01); } | ||||
|     inline bool     isSelected(void)     const { return selected; } | ||||
|     inline bool     isInTransition(void) const { return _t != nullptr; } | ||||
|     inline bool     isActive(void)       const { return stop > start; } | ||||
|     inline bool     is2D(void)           const { return (width()>1 && height()>1); } | ||||
|     inline uint16_t width(void)          const { return stop - start; }       // segment width in physical pixels (length if 1D) | ||||
|     inline uint16_t height(void)         const { return stopY - startY; }     // segment height (if 2D) in physical pixels | ||||
|     inline uint16_t length(void)         const { return width() * height(); } // segment length (count) in physical pixels | ||||
|     inline bool     hasRGB(void)         const { return _isRGB; } | ||||
|     inline bool     hasWhite(void)       const { return _hasW; } | ||||
|     inline bool     isCCT(void)          const { return _isCCT; } | ||||
|     inline uint16_t width(void)          const { return isActive() ? (stop - start) : 0; }  // segment width in physical pixels (length if 1D) | ||||
|     inline uint16_t height(void)         const { return stopY - startY; }                   // segment height (if 2D) in physical pixels (it *is* always >=1) | ||||
|     inline uint16_t length(void)         const { return width() * height(); }               // segment length (count) in physical pixels | ||||
|     inline uint16_t groupLength(void)    const { return grouping + spacing; } | ||||
|     inline uint8_t  getLightCapabilities(void) const { return _capabilities; } | ||||
|  | ||||
|     static uint16_t getUsedSegmentData(void)    { return _usedSegmentData; } | ||||
|     static void     addUsedSegmentData(int len) { _usedSegmentData += len; } | ||||
|     #ifndef WLED_DISABLE_MODE_BLEND | ||||
|     static void     modeBlend(bool blend)       { _modeBlend = blend; } | ||||
|     #endif | ||||
|     static void     handleRandomPalette(); | ||||
|  | ||||
|     void    setUp(uint16_t i1, uint16_t i2, uint8_t grp=1, uint8_t spc=0, uint16_t ofs=UINT16_MAX, uint16_t i1Y=0, uint16_t i2Y=1, uint8_t segId = 255); | ||||
|     bool    setColor(uint8_t slot, uint32_t c); //returns true if changed | ||||
|     void    setCCT(uint16_t k); | ||||
|     void    setOpacity(uint8_t o); | ||||
| @@ -518,28 +546,33 @@ typedef struct Segment { | ||||
|     bool allocateData(size_t len); | ||||
|     void deallocateData(void); | ||||
|     void resetIfRequired(void); | ||||
|     /**  | ||||
|     /** | ||||
|       * Flags that before the next effect is calculated, | ||||
|       * the internal segment state should be reset.  | ||||
|       * the internal segment state should be reset. | ||||
|       * Call resetIfRequired before calling the next effect function. | ||||
|       * Safe to call from interrupts and network requests. | ||||
|       */ | ||||
|     inline void markForReset(void) { reset = true; }  // setOption(SEG_OPTION_RESET, true) | ||||
|     void setUpLeds(void);   // set up leds[] array for loseless getPixelColor() | ||||
|  | ||||
|     // transition functions | ||||
|     void     startTransition(uint16_t dur); // transition has to start before actual segment values change | ||||
|     void     stopTransition(void); | ||||
|     void     handleTransition(void); | ||||
|     #ifndef WLED_DISABLE_MODE_BLEND | ||||
|     void     swapSegenv(tmpsegd_t &tmpSegD); | ||||
|     void     restoreSegenv(tmpsegd_t &tmpSegD); | ||||
|     #endif | ||||
|     uint16_t progress(void); //transition progression between 0-65535 | ||||
|     uint8_t  currentBri(uint8_t briNew, bool useCct = false); | ||||
|     uint8_t  currentMode(uint8_t modeNew); | ||||
|     uint32_t currentColor(uint8_t slot, uint32_t colorNew); | ||||
|     uint8_t  currentBri(bool useCct = false); | ||||
|     uint8_t  currentMode(void); | ||||
|     uint32_t currentColor(uint8_t slot); | ||||
|     CRGBPalette16 &loadPalette(CRGBPalette16 &tgt, uint8_t pal); | ||||
|     CRGBPalette16 ¤tPalette(CRGBPalette16 &tgt, uint8_t paletteID); | ||||
|  | ||||
|     // 1D strip | ||||
|     uint16_t virtualLength(void) const; | ||||
|     void setPixelColor(int n, uint32_t c); // set relative pixel within segment with color | ||||
|     void setPixelColor(unsigned n, uint32_t c)                    { setPixelColor(int(n), c); } | ||||
|     void setPixelColor(int n, byte r, byte g, byte b, byte w = 0) { setPixelColor(n, RGBW32(r,g,b,w)); } // automatically inline | ||||
|     void setPixelColor(int n, CRGB c)                             { setPixelColor(n, RGBW32(c.r,c.g,c.b,0)); } // automatically inline | ||||
|     void setPixelColor(float i, uint32_t c, bool aa = true); | ||||
| @@ -553,11 +586,10 @@ typedef struct Segment { | ||||
|     void fadeToBlackBy(uint8_t fadeBy); | ||||
|     void blendPixelColor(int n, uint32_t color, uint8_t blend); | ||||
|     void blendPixelColor(int n, CRGB c, uint8_t blend)            { blendPixelColor(n, RGBW32(c.r,c.g,c.b,0), blend); } | ||||
|     void addPixelColor(int n, uint32_t color); | ||||
|     void addPixelColor(int n, byte r, byte g, byte b, byte w = 0) { addPixelColor(n, RGBW32(r,g,b,w)); } // automatically inline | ||||
|     void addPixelColor(int n, CRGB c)                             { addPixelColor(n, RGBW32(c.r,c.g,c.b,0)); } // automatically inline | ||||
|     void addPixelColor(int n, uint32_t color, bool fast = false); | ||||
|     void addPixelColor(int n, byte r, byte g, byte b, byte w = 0, bool fast = false) { addPixelColor(n, RGBW32(r,g,b,w), fast); } // automatically inline | ||||
|     void addPixelColor(int n, CRGB c, bool fast = false)          { addPixelColor(n, RGBW32(c.r,c.g,c.b,0), fast); } // automatically inline | ||||
|     void fadePixelColor(uint16_t n, uint8_t fade); | ||||
|     uint8_t get_random_wheel_index(uint8_t pos); | ||||
|     uint32_t color_from_palette(uint16_t, bool mapping, bool wrap, uint8_t mcol, uint8_t pbri = 255); | ||||
|     uint32_t color_wheel(uint8_t pos); | ||||
|  | ||||
| @@ -566,8 +598,9 @@ typedef struct Segment { | ||||
|     uint16_t virtualHeight(void) const; | ||||
|     uint16_t nrOfVStrips(void) const; | ||||
|   #ifndef WLED_DISABLE_2D | ||||
|     uint16_t XY(uint16_t x, uint16_t y); // support function to get relative index within segment (for leds[]) | ||||
|     uint16_t XY(uint16_t x, uint16_t y); // support function to get relative index within segment | ||||
|     void setPixelColorXY(int x, int y, uint32_t c); // set relative pixel within segment with color | ||||
|     void setPixelColorXY(unsigned x, unsigned y, uint32_t c)               { setPixelColorXY(int(x), int(y), c); } | ||||
|     void setPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0) { setPixelColorXY(x, y, RGBW32(r,g,b,w)); } // automatically inline | ||||
|     void setPixelColorXY(int x, int y, CRGB c)                             { setPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0)); } // automatically inline | ||||
|     void setPixelColorXY(float x, float y, uint32_t c, bool aa = true); | ||||
| @@ -577,21 +610,23 @@ typedef struct Segment { | ||||
|     // 2D support functions | ||||
|     void blendPixelColorXY(uint16_t x, uint16_t y, uint32_t color, uint8_t blend); | ||||
|     void blendPixelColorXY(uint16_t x, uint16_t y, CRGB c, uint8_t blend)  { blendPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0), blend); } | ||||
|     void addPixelColorXY(int x, int y, uint32_t color); | ||||
|     void addPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0) { addPixelColorXY(x, y, RGBW32(r,g,b,w)); } // automatically inline | ||||
|     void addPixelColorXY(int x, int y, CRGB c)                             { addPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0)); } | ||||
|     void addPixelColorXY(int x, int y, uint32_t color, bool fast = false); | ||||
|     void addPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0, bool fast = false) { addPixelColorXY(x, y, RGBW32(r,g,b,w), fast); } // automatically inline | ||||
|     void addPixelColorXY(int x, int y, CRGB c, bool fast = false)                             { addPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0), fast); } | ||||
|     void fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade); | ||||
|     void box_blur(uint16_t i, bool vertical, fract8 blur_amount); // 1D box blur (with weight) | ||||
|     void blurRow(uint16_t row, fract8 blur_amount); | ||||
|     void blurCol(uint16_t col, fract8 blur_amount); | ||||
|     void moveX(int8_t delta); | ||||
|     void moveY(int8_t delta); | ||||
|     void move(uint8_t dir, uint8_t delta); | ||||
|     void moveX(int8_t delta, bool wrap = false); | ||||
|     void moveY(int8_t delta, bool wrap = false); | ||||
|     void move(uint8_t dir, uint8_t delta, bool wrap = false); | ||||
|     void draw_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB c); | ||||
|     void fill_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB c); | ||||
|     void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint32_t c); | ||||
|     void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, CRGB c) { drawLine(x0, y0, x1, y1, RGBW32(c.r,c.g,c.b,0)); } // automatic inline | ||||
|     void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color); | ||||
|     void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color, uint32_t col2 = 0, int8_t rotate = 0); | ||||
|     void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, CRGB c) { drawCharacter(chr, x, y, w, h, RGBW32(c.r,c.g,c.b,0)); } // automatic inline | ||||
|     void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, CRGB c, CRGB c2, int8_t rotate = 0) { drawCharacter(chr, x, y, w, h, RGBW32(c.r,c.g,c.b,0), RGBW32(c2.r,c2.g,c2.b,0), rotate); } // automatic inline | ||||
|     void wu_pixel(uint32_t x, uint32_t y, CRGB c); | ||||
|     void blur1d(fract8 blur_amount); // blur all rows in 1 dimension | ||||
|     void blur2d(fract8 blur_amount) { blur(blur_amount); } | ||||
| @@ -608,21 +643,22 @@ typedef struct Segment { | ||||
|     uint32_t getPixelColorXY(uint16_t x, uint16_t y)                       { return getPixelColor(x); } | ||||
|     void blendPixelColorXY(uint16_t x, uint16_t y, uint32_t c, uint8_t blend) { blendPixelColor(x, c, blend); } | ||||
|     void blendPixelColorXY(uint16_t x, uint16_t y, CRGB c, uint8_t blend)  { blendPixelColor(x, RGBW32(c.r,c.g,c.b,0), blend); } | ||||
|     void addPixelColorXY(int x, int y, uint32_t color)                     { addPixelColor(x, color); } | ||||
|     void addPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0) { addPixelColor(x, RGBW32(r,g,b,w)); } | ||||
|     void addPixelColorXY(int x, int y, CRGB c)                             { addPixelColor(x, RGBW32(c.r,c.g,c.b,0)); } | ||||
|     void addPixelColorXY(int x, int y, uint32_t color, bool fast = false)  { addPixelColor(x, color, fast); } | ||||
|     void addPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0, bool fast = false) { addPixelColor(x, RGBW32(r,g,b,w), fast); } | ||||
|     void addPixelColorXY(int x, int y, CRGB c, bool fast = false)          { addPixelColor(x, RGBW32(c.r,c.g,c.b,0), fast); } | ||||
|     void fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade)            { fadePixelColor(x, fade); } | ||||
|     void box_blur(uint16_t i, bool vertical, fract8 blur_amount) {} | ||||
|     void blurRow(uint16_t row, fract8 blur_amount) {} | ||||
|     void blurCol(uint16_t col, fract8 blur_amount) {} | ||||
|     void moveX(int8_t delta) {} | ||||
|     void moveY(int8_t delta) {} | ||||
|     void move(uint8_t dir, uint8_t delta) {} | ||||
|     void moveX(int8_t delta, bool wrap = false) {} | ||||
|     void moveY(int8_t delta, bool wrap = false) {} | ||||
|     void move(uint8_t dir, uint8_t delta, bool wrap = false) {} | ||||
|     void fill_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB c) {} | ||||
|     void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint32_t c) {} | ||||
|     void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, CRGB c) {} | ||||
|     void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color) {} | ||||
|     void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color, uint32_t = 0, int8_t = 0) {} | ||||
|     void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, CRGB color) {} | ||||
|     void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, CRGB c, CRGB c2, int8_t rotate = 0) {} | ||||
|     void wu_pixel(uint32_t x, uint32_t y, CRGB c) {} | ||||
|   #endif | ||||
| } segment; | ||||
| @@ -640,7 +676,7 @@ class WS2812FX {  // 96 bytes | ||||
|   } mode_data_t; | ||||
|  | ||||
|   static WS2812FX* instance; | ||||
|    | ||||
|  | ||||
|   public: | ||||
|  | ||||
|     WS2812FX() : | ||||
| @@ -654,12 +690,7 @@ class WS2812FX {  // 96 bytes | ||||
|       timebase(0), | ||||
|       isMatrix(false), | ||||
| #ifndef WLED_DISABLE_2D | ||||
|       hPanels(1), | ||||
|       vPanels(1), | ||||
|       panelH(8), | ||||
|       panelW(8), | ||||
|       matrix{0,0,0,0}, | ||||
|       panel{{0,0,0,0}}, | ||||
|       panels(1), | ||||
| #endif | ||||
|       // semi-private (just obscured) used in effect functions through macros | ||||
|       _currentPalette(CRGBPalette16(CRGB::Black)), | ||||
| @@ -682,7 +713,15 @@ class WS2812FX {  // 96 bytes | ||||
|       customMappingSize(0), | ||||
|       _lastShow(0), | ||||
|       _segment_index(0), | ||||
|       _mainSegment(0) | ||||
|       _mainSegment(0), | ||||
|       _queuedChangesSegId(255), | ||||
|       _qStart(0), | ||||
|       _qStop(0), | ||||
|       _qStartY(0), | ||||
|       _qStopY(0), | ||||
|       _qGrouping(0), | ||||
|       _qSpacing(0), | ||||
|       _qOffset(0) | ||||
|     { | ||||
|       WS2812FX::instance = this; | ||||
|       _mode.reserve(_modeCount);     // allocate memory to prevent initial fragmentation (does not increase size()) | ||||
| @@ -696,8 +735,10 @@ class WS2812FX {  // 96 bytes | ||||
|       _mode.clear(); | ||||
|       _modeData.clear(); | ||||
|       _segments.clear(); | ||||
| #ifndef WLED_DISABLE_2D | ||||
|       panel.clear(); | ||||
| #endif | ||||
|       customPalettes.clear(); | ||||
|       if (useLedsArray && Segment::_globalLeds) free(Segment::_globalLeds); | ||||
|     } | ||||
|  | ||||
|     static WS2812FX* getInstance(void) { return instance; } | ||||
| @@ -709,7 +750,6 @@ class WS2812FX {  // 96 bytes | ||||
|       finalizeInit(), | ||||
|       service(void), | ||||
|       setMode(uint8_t segid, uint8_t m), | ||||
|       setColor(uint8_t slot, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0), | ||||
|       setColor(uint8_t slot, uint32_t c), | ||||
|       setCCT(uint16_t k), | ||||
|       setBrightness(uint8_t b, bool direct = false), | ||||
| @@ -724,10 +764,10 @@ class WS2812FX {  // 96 bytes | ||||
|       fixInvalidSegments(), | ||||
|       setPixelColor(int n, uint32_t c), | ||||
|       show(void), | ||||
|       setTargetFps(uint8_t fps), | ||||
|       deserializeMap(uint8_t n=0); | ||||
|       setTargetFps(uint8_t fps); | ||||
|  | ||||
|     void fill(uint32_t c) { for (int i = 0; i < _length; i++) setPixelColor(i, c); } // fill whole strip with color (inline) | ||||
|     void setColor(uint8_t slot, uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0) { setColor(slot, RGBW32(r,g,b,w)); } | ||||
|     void fill(uint32_t c) { for (int i = 0; i < getLengthTotal(); i++) setPixelColor(i, c); } // fill whole strip with color (inline) | ||||
|     void addEffect(uint8_t id, mode_ptr mode_fn, const char *mode_name); // add effect to the list; defined in FX.cpp | ||||
|     void setupEffectData(void); // add default effects to the list; defined in FX.cpp | ||||
|  | ||||
| @@ -737,7 +777,7 @@ class WS2812FX {  // 96 bytes | ||||
|     inline void trigger(void) { _triggered = true; } // Forces the next frame to be computed on all active segments. | ||||
|     inline void setShowCallback(show_callback cb) { _callback = cb; } | ||||
|     inline void setTransition(uint16_t t) { _transitionDur = t; } | ||||
|     inline void appendSegment(const Segment &seg = Segment()) { _segments.push_back(seg); } | ||||
|     inline void appendSegment(const Segment &seg = Segment()) { if (_segments.size() < getMaxSegments()) _segments.push_back(seg); } | ||||
|  | ||||
|     bool | ||||
|       checkSegmentAlignment(void), | ||||
| @@ -745,7 +785,7 @@ class WS2812FX {  // 96 bytes | ||||
|       hasCCTBus(void), | ||||
|       // return true if the strip is being sent pixel updates | ||||
|       isUpdating(void), | ||||
|       useLedsArray = false; | ||||
|       deserializeMap(uint8_t n=0); | ||||
|  | ||||
|     inline bool isServicing(void) { return _isServicing; } | ||||
|     inline bool hasWhiteChannel(void) {return _hasWhiteChannel;} | ||||
| @@ -759,6 +799,7 @@ class WS2812FX {  // 96 bytes | ||||
|       getActiveSegmentsNum(void), | ||||
|       getFirstSelectedSegId(void), | ||||
|       getLastActiveSegmentId(void), | ||||
|       getActiveSegsLightCapabilities(bool selectedOnly = false), | ||||
|       setPixelSegment(uint8_t n); | ||||
|  | ||||
|     inline uint8_t getBrightness(void) { return _brightness; } | ||||
| @@ -774,17 +815,17 @@ class WS2812FX {  // 96 bytes | ||||
|       ablMilliampsMax, | ||||
|       currentMilliamps, | ||||
|       getLengthPhysical(void), | ||||
|       getLengthTotal(void), // will include virtual/nonexistent pixels in matrix | ||||
|       getFps(); | ||||
|  | ||||
|     inline uint16_t getFrameTime(void) { return _frametime; } | ||||
|     inline uint16_t getMinShowDelay(void) { return MIN_SHOW_DELAY; } | ||||
|     inline uint16_t getLengthTotal(void) { return _length; } | ||||
|     inline uint16_t getLength(void) { return _length; } // 2D matrix may have less pixels than W*H | ||||
|     inline uint16_t getTransition(void) { return _transitionDur; } | ||||
|  | ||||
|     uint32_t | ||||
|       now, | ||||
|       timebase, | ||||
|       currentColor(uint32_t colorNew, uint8_t tNr), | ||||
|       getPixelColor(uint16_t); | ||||
|  | ||||
|     inline uint32_t getLastShow(void) { return _lastShow; } | ||||
| @@ -808,34 +849,41 @@ class WS2812FX {  // 96 bytes | ||||
| #ifndef WLED_DISABLE_2D | ||||
|     #define WLED_MAX_PANELS 64 | ||||
|     uint8_t | ||||
|       hPanels, | ||||
|       vPanels; | ||||
|       panels; | ||||
|  | ||||
|     uint16_t | ||||
|       panelH, | ||||
|       panelW; | ||||
|  | ||||
|     typedef struct panel_bitfield_t { | ||||
|       bool bottomStart : 1; // starts at bottom? | ||||
|       bool rightStart  : 1; // starts on right? | ||||
|       bool vertical    : 1; // is vertical? | ||||
|       bool serpentine  : 1; // is serpentine? | ||||
|     typedef struct panel_t { | ||||
|       uint16_t xOffset; // x offset relative to the top left of matrix in LEDs | ||||
|       uint16_t yOffset; // y offset relative to the top left of matrix in LEDs | ||||
|       uint8_t  width;   // width of the panel | ||||
|       uint8_t  height;  // height of the panel | ||||
|       union { | ||||
|         uint8_t options; | ||||
|         struct { | ||||
|           bool bottomStart : 1; // starts at bottom? | ||||
|           bool rightStart  : 1; // starts on right? | ||||
|           bool vertical    : 1; // is vertical? | ||||
|           bool serpentine  : 1; // is serpentine? | ||||
|         }; | ||||
|       }; | ||||
|       panel_t() | ||||
|         : xOffset(0) | ||||
|         , yOffset(0) | ||||
|         , width(8) | ||||
|         , height(8) | ||||
|         , options(0) | ||||
|       {} | ||||
|     } Panel; | ||||
|     Panel | ||||
|       matrix, | ||||
|       panel[WLED_MAX_PANELS]; | ||||
|     std::vector<Panel> panel; | ||||
| #endif | ||||
|  | ||||
|     void | ||||
|       setUpMatrix(), | ||||
|       setPixelColorXY(int x, int y, uint32_t c); | ||||
|     void setUpMatrix(); | ||||
|  | ||||
|     // outsmart the compiler :) by correctly overloading | ||||
|     inline void setPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0) { setPixelColorXY(x, y, RGBW32(r,g,b,w)); } // automatically inline | ||||
|     inline void setPixelColorXY(int x, int y, CRGB c)                             { setPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0)); } | ||||
|     inline void setPixelColorXY(int x, int y, uint32_t c)   { setPixelColor(y * Segment::maxWidth + x, c); } | ||||
|     inline void setPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0) { setPixelColorXY(x, y, RGBW32(r,g,b,w)); } | ||||
|     inline void setPixelColorXY(int x, int y, CRGB c)       { setPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0)); } | ||||
|  | ||||
|     uint32_t | ||||
|       getPixelColorXY(uint16_t, uint16_t); | ||||
|     inline uint32_t getPixelColorXY(uint16_t x, uint16_t y) { return getPixelColor(isMatrix ? y * Segment::maxWidth + x : x);} | ||||
|  | ||||
|   // end 2D support | ||||
|  | ||||
| @@ -876,14 +924,21 @@ class WS2812FX {  // 96 bytes | ||||
|  | ||||
|     uint16_t* customMappingTable; | ||||
|     uint16_t  customMappingSize; | ||||
|      | ||||
|     uint32_t _lastShow; | ||||
|      | ||||
|  | ||||
|     unsigned long _lastShow; | ||||
|  | ||||
|     uint8_t _segment_index; | ||||
|     uint8_t _mainSegment; | ||||
|     uint8_t _queuedChangesSegId; | ||||
|     uint16_t _qStart, _qStop, _qStartY, _qStopY; | ||||
|     uint8_t _qGrouping, _qSpacing; | ||||
|     uint16_t _qOffset; | ||||
|  | ||||
|     uint8_t | ||||
|       estimateCurrentAndLimitBri(void); | ||||
|  | ||||
|     void | ||||
|       estimateCurrentAndLimitBri(void); | ||||
|       setUpSegmentFromQueuedChanges(void); | ||||
| }; | ||||
|  | ||||
| extern const char JSON_mode_names[]; | ||||
|   | ||||
| @@ -1,6 +1,6 @@ | ||||
| /* | ||||
|   FX_2Dfcn.cpp contains all 2D utility functions | ||||
|    | ||||
|  | ||||
|   LICENSE | ||||
|   The MIT License (MIT) | ||||
|   Copyright (c) 2022  Blaz Kristan (https://blaz.at/home) | ||||
| @@ -43,99 +43,118 @@ void WS2812FX::setUpMatrix() { | ||||
|  | ||||
|   // isMatrix is set in cfg.cpp or set.cpp | ||||
|   if (isMatrix) { | ||||
|     Segment::maxWidth  = hPanels * panelW; | ||||
|     Segment::maxHeight = vPanels * panelH; | ||||
|     // calculate width dynamically because it will have gaps | ||||
|     Segment::maxWidth = 1; | ||||
|     Segment::maxHeight = 1; | ||||
|     for (size_t i = 0; i < panel.size(); i++) { | ||||
|       Panel &p = panel[i]; | ||||
|       if (p.xOffset + p.width > Segment::maxWidth) { | ||||
|         Segment::maxWidth = p.xOffset + p.width; | ||||
|       } | ||||
|       if (p.yOffset + p.height > Segment::maxHeight) { | ||||
|         Segment::maxHeight = p.yOffset + p.height; | ||||
|       } | ||||
|     } | ||||
|  | ||||
|     // safety check | ||||
|     if (Segment::maxWidth * Segment::maxHeight > MAX_LEDS || Segment::maxWidth == 1 || Segment::maxHeight == 1) { | ||||
|     if (Segment::maxWidth * Segment::maxHeight > MAX_LEDS || Segment::maxWidth <= 1 || Segment::maxHeight <= 1) { | ||||
|       DEBUG_PRINTLN(F("2D Bounds error.")); | ||||
|       isMatrix = false; | ||||
|       Segment::maxWidth = _length; | ||||
|       Segment::maxHeight = 1; | ||||
|       isMatrix = false; | ||||
|       panels = 0; | ||||
|       panel.clear(); // release memory allocated by panels | ||||
|       resetSegments(); | ||||
|       return; | ||||
|     } | ||||
|  | ||||
|     customMappingSize  = Segment::maxWidth * Segment::maxHeight; | ||||
|     customMappingTable = new uint16_t[customMappingSize]; | ||||
|     customMappingTable = new uint16_t[Segment::maxWidth * Segment::maxHeight]; | ||||
|  | ||||
|     if (customMappingTable != nullptr) { | ||||
|       uint16_t startL; // index in custom mapping array (logical strip) | ||||
|       uint16_t startP; // position of 1st pixel of panel on (virtual) strip | ||||
|       uint16_t x, y, offset; | ||||
|       uint8_t h = matrix.vertical ? vPanels : hPanels; | ||||
|       uint8_t v = matrix.vertical ? hPanels : vPanels; | ||||
|       customMappingSize = Segment::maxWidth * Segment::maxHeight; | ||||
|  | ||||
|       for (uint8_t j=0, p=0; j<v; j++) { | ||||
|         for (uint8_t i=0; i<h; i++, p++) { | ||||
|           y = (matrix.vertical ? matrix.rightStart : matrix.bottomStart) ? v - j - 1 : j; | ||||
|           x = (matrix.vertical ? matrix.bottomStart : matrix.rightStart) ? h - i - 1 : i; | ||||
|           x = matrix.serpentine && j%2 ? h - x - 1 : x; | ||||
|       // fill with empty in case we don't fill the entire matrix | ||||
|       for (size_t i = 0; i< customMappingSize; i++) { | ||||
|         customMappingTable[i] = (uint16_t)-1; | ||||
|       } | ||||
|  | ||||
|           startL = (matrix.vertical ? y : x) * panelW + (matrix.vertical ? x : y) * Segment::maxWidth * panelH; // logical index (top-left corner) | ||||
|           startP = p * panelW * panelH; // physical index (top-left corner) | ||||
|       // we will try to load a "gap" array (a JSON file) | ||||
|       // the array has to have the same amount of values as mapping array (or larger) | ||||
|       // "gap" array is used while building ledmap (mapping array) | ||||
|       // and discarded afterwards as it has no meaning after the process | ||||
|       // content of the file is just raw JSON array in the form of [val1,val2,val3,...] | ||||
|       // there are no other "key":"value" pairs in it | ||||
|       // allowed values are: -1 (missing pixel/no LED attached), 0 (inactive/unused pixel), 1 (active/used pixel) | ||||
|       char    fileName[32]; strcpy_P(fileName, PSTR("/2d-gaps.json")); // reduce flash footprint | ||||
|       bool    isFile = WLED_FS.exists(fileName); | ||||
|       size_t  gapSize = 0; | ||||
|       int8_t *gapTable = nullptr; | ||||
|  | ||||
|           uint8_t H = panel[h*j + i].vertical ? panelW : panelH; | ||||
|           uint8_t W = panel[h*j + i].vertical ? panelH : panelW; | ||||
|           for (uint16_t l=0, q=0; l<H; l++) { | ||||
|             for (uint16_t k=0; k<W; k++, q++) { | ||||
|               y = (panel[h*j + i].vertical ? panel[h*j + i].rightStart : panel[h*j + i].bottomStart) ? H - l - 1 : l; | ||||
|               x = (panel[h*j + i].vertical ? panel[h*j + i].bottomStart : panel[h*j + i].rightStart) ? W - k - 1 : k; | ||||
|               x = (panel[h*j + i].serpentine && l%2) ? (W - x - 1) : x; | ||||
|               offset = (panel[h*j + i].vertical ? y : x) + (panel[h*j + i].vertical ? x : y) * Segment::maxWidth; | ||||
|               customMappingTable[startL + offset] = startP + q; | ||||
|       if (isFile && requestJSONBufferLock(20)) { | ||||
|         DEBUG_PRINT(F("Reading LED gap from ")); | ||||
|         DEBUG_PRINTLN(fileName); | ||||
|         // read the array into global JSON buffer | ||||
|         if (readObjectFromFile(fileName, nullptr, &doc)) { | ||||
|           // the array is similar to ledmap, except it has only 3 values: | ||||
|           // -1 ... missing pixel (do not increase pixel count) | ||||
|           //  0 ... inactive pixel (it does count, but should be mapped out (-1)) | ||||
|           //  1 ... active pixel (it will count and will be mapped) | ||||
|           JsonArray map = doc.as<JsonArray>(); | ||||
|           gapSize = map.size(); | ||||
|           if (!map.isNull() && gapSize >= customMappingSize) { // not an empty map | ||||
|             gapTable = new int8_t[gapSize]; | ||||
|             if (gapTable) for (size_t i = 0; i < gapSize; i++) { | ||||
|               gapTable[i] = constrain(map[i], -1, 1); | ||||
|             } | ||||
|           } | ||||
|         } | ||||
|         DEBUG_PRINTLN(F("Gaps loaded.")); | ||||
|         releaseJSONBufferLock(); | ||||
|       } | ||||
|  | ||||
|       uint16_t x, y, pix=0; //pixel | ||||
|       for (size_t pan = 0; pan < panel.size(); pan++) { | ||||
|         Panel &p = panel[pan]; | ||||
|         uint16_t h = p.vertical ? p.height : p.width; | ||||
|         uint16_t v = p.vertical ? p.width  : p.height; | ||||
|         for (size_t j = 0; j < v; j++){ | ||||
|           for(size_t i = 0; i < h; i++) { | ||||
|             y = (p.vertical?p.rightStart:p.bottomStart) ? v-j-1 : j; | ||||
|             x = (p.vertical?p.bottomStart:p.rightStart) ? h-i-1 : i; | ||||
|             x = p.serpentine && j%2 ? h-x-1 : x; | ||||
|             size_t index = (p.yOffset + (p.vertical?x:y)) * Segment::maxWidth + p.xOffset + (p.vertical?y:x); | ||||
|             if (!gapTable || (gapTable && gapTable[index] >  0)) customMappingTable[index] = pix; // a useful pixel (otherwise -1 is retained) | ||||
|             if (!gapTable || (gapTable && gapTable[index] >= 0)) pix++; // not a missing pixel | ||||
|           } | ||||
|         } | ||||
|       } | ||||
|  | ||||
|       // delete gap array as we no longer need it | ||||
|       if (gapTable) delete[] gapTable; | ||||
|  | ||||
|       #ifdef WLED_DEBUG | ||||
|       DEBUG_PRINT(F("Matrix ledmap:")); | ||||
|       for (uint16_t i=0; i<customMappingSize; i++) { | ||||
|       for (unsigned i=0; i<customMappingSize; i++) { | ||||
|         if (!(i%Segment::maxWidth)) DEBUG_PRINTLN(); | ||||
|         DEBUG_PRINTF("%4d,", customMappingTable[i]); | ||||
|       } | ||||
|       DEBUG_PRINTLN(); | ||||
|       #endif | ||||
|     } else { | ||||
|       // memory allocation error | ||||
|     } else { // memory allocation error | ||||
|       DEBUG_PRINTLN(F("Ledmap alloc error.")); | ||||
|       isMatrix = false; | ||||
|       panels = 0; | ||||
|       panel.clear(); | ||||
|       Segment::maxWidth = _length; | ||||
|       Segment::maxHeight = 1; | ||||
|       isMatrix = false; | ||||
|       return; | ||||
|       resetSegments(); | ||||
|     } | ||||
|   } else {  | ||||
|     // not a matrix set up | ||||
|     Segment::maxWidth = _length; | ||||
|     Segment::maxHeight = 1; | ||||
|   } | ||||
| #else | ||||
|   isMatrix = false; // no matter what config says | ||||
| #endif | ||||
| } | ||||
|  | ||||
| // absolute matrix version of setPixelColor() | ||||
| void IRAM_ATTR WS2812FX::setPixelColorXY(int x, int y, uint32_t col) | ||||
| { | ||||
| #ifndef WLED_DISABLE_2D | ||||
|   if (!isMatrix) return; // not a matrix set-up | ||||
|   uint16_t index = y * Segment::maxWidth + x; | ||||
|   if (index >= customMappingSize) return; // customMappingSize is always W * H of matrix in 2D setup | ||||
| #else | ||||
|   uint16_t index = x; | ||||
|   if (index >= _length) return; | ||||
| #endif | ||||
|   if (index < customMappingSize) index = customMappingTable[index]; | ||||
|   busses.setPixelColor(index, col); | ||||
| } | ||||
|  | ||||
| // returns RGBW values of pixel | ||||
| uint32_t WS2812FX::getPixelColorXY(uint16_t x, uint16_t y) { | ||||
| #ifndef WLED_DISABLE_2D | ||||
|   uint16_t index = (y * Segment::maxWidth + x); | ||||
|   if (index >= customMappingSize) return 0; // customMappingSize is always W * H of matrix in 2D setup | ||||
| #else | ||||
|   uint16_t index = x; | ||||
|   if (index >= _length) return 0; | ||||
| #endif | ||||
|   if (index < customMappingSize) index = customMappingTable[index]; | ||||
|   return busses.getPixelColor(index); | ||||
| } | ||||
|  | ||||
| /////////////////////////////////////////////////////////// | ||||
| // Segment:: routines | ||||
| @@ -144,20 +163,19 @@ uint32_t WS2812FX::getPixelColorXY(uint16_t x, uint16_t y) { | ||||
| #ifndef WLED_DISABLE_2D | ||||
|  | ||||
| // XY(x,y) - gets pixel index within current segment (often used to reference leds[] array element) | ||||
| uint16_t IRAM_ATTR Segment::XY(uint16_t x, uint16_t y) { | ||||
|   uint16_t width  = virtualWidth();   // segment width in logical pixels | ||||
|   uint16_t height = virtualHeight();  // segment height in logical pixels | ||||
|   return (x%width) + (y%height) * width; | ||||
| uint16_t IRAM_ATTR Segment::XY(uint16_t x, uint16_t y) | ||||
| { | ||||
|   uint16_t width  = virtualWidth();   // segment width in logical pixels (can be 0 if segment is inactive) | ||||
|   uint16_t height = virtualHeight();  // segment height in logical pixels (is always >= 1) | ||||
|   return isActive() ? (x%width) + (y%height) * width : 0; | ||||
| } | ||||
|  | ||||
| void IRAM_ATTR Segment::setPixelColorXY(int x, int y, uint32_t col) | ||||
| { | ||||
|   if (Segment::maxHeight==1) return; // not a matrix set-up | ||||
|   if (!isActive()) return; // not active | ||||
|   if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return;  // if pixel would fall out of virtual segment just exit | ||||
|  | ||||
|   if (leds) leds[XY(x,y)] = col; | ||||
|  | ||||
|   uint8_t _bri_t = currentBri(on ? opacity : 0); | ||||
|   uint8_t _bri_t = currentBri(); | ||||
|   if (_bri_t < 255) { | ||||
|     byte r = scale8(R(col), _bri_t); | ||||
|     byte g = scale8(G(col), _bri_t); | ||||
| @@ -174,23 +192,29 @@ void IRAM_ATTR Segment::setPixelColorXY(int x, int y, uint32_t col) | ||||
|   y *= groupLength(); // expand to physical pixels | ||||
|   if (x >= width() || y >= height()) return;  // if pixel would fall out of segment just exit | ||||
|  | ||||
|   uint32_t tmpCol = col; | ||||
|   for (int j = 0; j < grouping; j++) {   // groupping vertically | ||||
|     for (int g = 0; g < grouping; g++) { // groupping horizontally | ||||
|       uint16_t xX = (x+g), yY = (y+j); | ||||
|       if (xX >= width() || yY >= height()) continue; // we have reached one dimension's end | ||||
|  | ||||
|       strip.setPixelColorXY(start + xX, startY + yY, col); | ||||
| #ifndef WLED_DISABLE_MODE_BLEND | ||||
|       // if blending modes, blend with underlying pixel | ||||
|       if (_modeBlend) tmpCol = color_blend(strip.getPixelColorXY(start + xX, startY + yY), col, 0xFFFFU - progress(), true); | ||||
| #endif | ||||
|  | ||||
|       strip.setPixelColorXY(start + xX, startY + yY, tmpCol); | ||||
|  | ||||
|       if (mirror) { //set the corresponding horizontally mirrored pixel | ||||
|         if (transpose) strip.setPixelColorXY(start + xX, startY + height() - yY - 1, col); | ||||
|         else           strip.setPixelColorXY(start + width() - xX - 1, startY + yY, col); | ||||
|         if (transpose) strip.setPixelColorXY(start + xX, startY + height() - yY - 1, tmpCol); | ||||
|         else           strip.setPixelColorXY(start + width() - xX - 1, startY + yY, tmpCol); | ||||
|       } | ||||
|       if (mirror_y) { //set the corresponding vertically mirrored pixel | ||||
|         if (transpose) strip.setPixelColorXY(start + width() - xX - 1, startY + yY, col); | ||||
|         else           strip.setPixelColorXY(start + xX, startY + height() - yY - 1, col); | ||||
|         if (transpose) strip.setPixelColorXY(start + width() - xX - 1, startY + yY, tmpCol); | ||||
|         else           strip.setPixelColorXY(start + xX, startY + height() - yY - 1, tmpCol); | ||||
|       } | ||||
|       if (mirror_y && mirror) { //set the corresponding vertically AND horizontally mirrored pixel | ||||
|         strip.setPixelColorXY(width() - xX - 1, height() - yY - 1, col); | ||||
|         strip.setPixelColorXY(width() - xX - 1, height() - yY - 1, tmpCol); | ||||
|       } | ||||
|     } | ||||
|   } | ||||
| @@ -199,7 +223,7 @@ void IRAM_ATTR Segment::setPixelColorXY(int x, int y, uint32_t col) | ||||
| // anti-aliased version of setPixelColorXY() | ||||
| void Segment::setPixelColorXY(float x, float y, uint32_t col, bool aa) | ||||
| { | ||||
|   if (Segment::maxHeight==1) return; // not a matrix set-up | ||||
|   if (!isActive()) return; // not active | ||||
|   if (x<0.0f || x>1.0f || y<0.0f || y>1.0f) return; // not normalized | ||||
|  | ||||
|   const uint16_t cols = virtualWidth(); | ||||
| @@ -242,8 +266,8 @@ void Segment::setPixelColorXY(float x, float y, uint32_t col, bool aa) | ||||
|  | ||||
| // returns RGBW values of pixel | ||||
| uint32_t Segment::getPixelColorXY(uint16_t x, uint16_t y) { | ||||
|   int i = XY(x,y); | ||||
|   if (leds) return RGBW32(leds[i].r, leds[i].g, leds[i].b, 0); | ||||
|   if (!isActive()) return 0; // not active | ||||
|   if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return 0;  // if pixel would fall out of virtual segment just exit | ||||
|   if (reverse  ) x = virtualWidth()  - x - 1; | ||||
|   if (reverse_y) y = virtualHeight() - y - 1; | ||||
|   if (transpose) { uint16_t t = x; x = y; y = t; } // swap X & Y if segment transposed | ||||
| @@ -259,67 +283,76 @@ void Segment::blendPixelColorXY(uint16_t x, uint16_t y, uint32_t color, uint8_t | ||||
| } | ||||
|  | ||||
| // Adds the specified color with the existing pixel color perserving color balance. | ||||
| void Segment::addPixelColorXY(int x, int y, uint32_t color) { | ||||
|   setPixelColorXY(x, y, color_add(getPixelColorXY(x,y), color)); | ||||
| void Segment::addPixelColorXY(int x, int y, uint32_t color, bool fast) { | ||||
|   if (!isActive()) return; // not active | ||||
|   if (x >= virtualWidth() || y >= virtualHeight() || x<0 || y<0) return;  // if pixel would fall out of virtual segment just exit | ||||
|   setPixelColorXY(x, y, color_add(getPixelColorXY(x,y), color, fast)); | ||||
| } | ||||
|  | ||||
| void Segment::fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade) { | ||||
|   CRGB pix = CRGB(getPixelColorXY(x,y)).nscale8_video(fade); | ||||
|   setPixelColor(x, y, pix); | ||||
|   if (!isActive()) return; // not active | ||||
|   setPixelColorXY(x, y, color_fade(getPixelColorXY(x,y), fade, true)); | ||||
| } | ||||
|  | ||||
| // blurRow: perform a blur on a row of a rectangular matrix | ||||
| void Segment::blurRow(uint16_t row, fract8 blur_amount) { | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   if (!isActive() || blur_amount == 0) return; // not active | ||||
|   const uint_fast16_t cols = virtualWidth(); | ||||
|   const uint_fast16_t rows = virtualHeight(); | ||||
|  | ||||
|   if (row >= rows) return; | ||||
|   // blur one row | ||||
|   uint8_t keep = 255 - blur_amount; | ||||
|   uint8_t seep = blur_amount >> 1; | ||||
|   CRGB carryover = CRGB::Black; | ||||
|   for (uint16_t x = 0; x < cols; x++) { | ||||
|   for (unsigned x = 0; x < cols; x++) { | ||||
|     CRGB cur = getPixelColorXY(x, row); | ||||
|     CRGB before = cur;     // remember color before blur | ||||
|     CRGB part = cur; | ||||
|     part.nscale8(seep); | ||||
|     cur.nscale8(keep); | ||||
|     cur += carryover; | ||||
|     if (x) { | ||||
|     if (x>0) { | ||||
|       CRGB prev = CRGB(getPixelColorXY(x-1, row)) + part; | ||||
|       setPixelColorXY(x-1, row, prev); | ||||
|     } | ||||
|     setPixelColorXY(x, row, cur); | ||||
|     if (before != cur)         // optimization: only set pixel if color has changed | ||||
|       setPixelColorXY(x, row, cur); | ||||
|     carryover = part; | ||||
|   } | ||||
| } | ||||
|  | ||||
| // blurCol: perform a blur on a column of a rectangular matrix | ||||
| void Segment::blurCol(uint16_t col, fract8 blur_amount) { | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   if (!isActive() || blur_amount == 0) return; // not active | ||||
|   const uint_fast16_t cols = virtualWidth(); | ||||
|   const uint_fast16_t rows = virtualHeight(); | ||||
|  | ||||
|   if (col >= cols) return; | ||||
|   // blur one column | ||||
|   uint8_t keep = 255 - blur_amount; | ||||
|   uint8_t seep = blur_amount >> 1; | ||||
|   CRGB carryover = CRGB::Black; | ||||
|   for (uint16_t i = 0; i < rows; i++) { | ||||
|     CRGB cur = getPixelColorXY(col, i); | ||||
|   for (unsigned y = 0; y < rows; y++) { | ||||
|     CRGB cur = getPixelColorXY(col, y); | ||||
|     CRGB part = cur; | ||||
|     CRGB before = cur;     // remember color before blur | ||||
|     part.nscale8(seep); | ||||
|     cur.nscale8(keep); | ||||
|     cur += carryover; | ||||
|     if (i) { | ||||
|       CRGB prev = CRGB(getPixelColorXY(col, i-1)) + part; | ||||
|       setPixelColorXY(col, i-1, prev); | ||||
|     if (y>0) { | ||||
|       CRGB prev = CRGB(getPixelColorXY(col, y-1)) + part; | ||||
|       setPixelColorXY(col, y-1, prev); | ||||
|     } | ||||
|     setPixelColorXY(col, i, cur); | ||||
|     if (before != cur)         // optimization: only set pixel if color has changed | ||||
|       setPixelColorXY(col, y, cur); | ||||
|     carryover = part; | ||||
|   } | ||||
| } | ||||
|  | ||||
| // 1D Box blur (with added weight - blur_amount: [0=no blur, 255=max blur]) | ||||
| void Segment::box_blur(uint16_t i, bool vertical, fract8 blur_amount) { | ||||
|   if (!isActive() || blur_amount == 0) return; // not active | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   const uint16_t dim1 = vertical ? rows : cols; | ||||
| @@ -329,11 +362,11 @@ void Segment::box_blur(uint16_t i, bool vertical, fract8 blur_amount) { | ||||
|   const float keep = 3.f - 2.f*seep; | ||||
|   // 1D box blur | ||||
|   CRGB tmp[dim1]; | ||||
|   for (uint16_t j = 0; j < dim1; j++) { | ||||
|   for (int j = 0; j < dim1; j++) { | ||||
|     uint16_t x = vertical ? i : j; | ||||
|     uint16_t y = vertical ? j : i; | ||||
|     uint16_t xp = vertical ? x : x-1; | ||||
|     uint16_t yp = vertical ? y-1 : y; | ||||
|     int16_t xp = vertical ? x : x-1;  // "signed" to prevent underflow | ||||
|     int16_t yp = vertical ? y-1 : y;  // "signed" to prevent underflow | ||||
|     uint16_t xn = vertical ? x : x+1; | ||||
|     uint16_t yn = vertical ? y+1 : y; | ||||
|     CRGB curr = getPixelColorXY(x,y); | ||||
| @@ -345,7 +378,7 @@ void Segment::box_blur(uint16_t i, bool vertical, fract8 blur_amount) { | ||||
|     b = (curr.b*keep + (prev.b + next.b)*seep) / 3; | ||||
|     tmp[j] = CRGB(r,g,b); | ||||
|   } | ||||
|   for (uint16_t j = 0; j < dim1; j++) { | ||||
|   for (int j = 0; j < dim1; j++) { | ||||
|     uint16_t x = vertical ? i : j; | ||||
|     uint16_t y = vertical ? j : i; | ||||
|     setPixelColorXY(x, y, tmp[j]); | ||||
| @@ -368,62 +401,90 @@ void Segment::box_blur(uint16_t i, bool vertical, fract8 blur_amount) { | ||||
|  | ||||
| void Segment::blur1d(fract8 blur_amount) { | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   for (uint16_t y = 0; y < rows; y++) blurRow(y, blur_amount); | ||||
|   for (unsigned y = 0; y < rows; y++) blurRow(y, blur_amount); | ||||
| } | ||||
|  | ||||
| void Segment::moveX(int8_t delta) { | ||||
| void Segment::moveX(int8_t delta, bool wrap) { | ||||
|   if (!isActive()) return; // not active | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   if (!delta) return; | ||||
|   if (delta > 0) { | ||||
|     for (uint8_t y = 0; y < rows; y++) for (uint8_t x = 0; x < cols-1; x++) { | ||||
|       if (x + delta >= cols) break; | ||||
|       setPixelColorXY(x, y, getPixelColorXY((x + delta)%cols, y)); | ||||
|     } | ||||
|   } else { | ||||
|     for (uint8_t y = 0; y < rows; y++) for (int16_t x = cols-1; x >= 0; x--) { | ||||
|       if (x + delta < 0) break; | ||||
|       setPixelColorXY(x, y, getPixelColorXY(x + delta, y)); | ||||
|   if (!delta || abs(delta) >= cols) return; | ||||
|   uint32_t newPxCol[cols]; | ||||
|   for (int y = 0; y < rows; y++) { | ||||
|     if (delta > 0) { | ||||
|       for (int x = 0; x < cols-delta; x++)    newPxCol[x] = getPixelColorXY((x + delta), y); | ||||
|       for (int x = cols-delta; x < cols; x++) newPxCol[x] = getPixelColorXY(wrap ? (x + delta) - cols : x, y); | ||||
|     } else { | ||||
|       for (int x = cols-1; x >= -delta; x--) newPxCol[x] = getPixelColorXY((x + delta), y); | ||||
|       for (int x = -delta-1; x >= 0; x--)    newPxCol[x] = getPixelColorXY(wrap ? (x + delta) + cols : x, y); | ||||
|     } | ||||
|     for (int x = 0; x < cols; x++) setPixelColorXY(x, y, newPxCol[x]); | ||||
|   } | ||||
| } | ||||
|  | ||||
| void Segment::moveY(int8_t delta) { | ||||
| void Segment::moveY(int8_t delta, bool wrap) { | ||||
|   if (!isActive()) return; // not active | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   if (!delta) return; | ||||
|   if (delta > 0) { | ||||
|     for (uint8_t x = 0; x < cols; x++) for (uint8_t y = 0; y < rows-1; y++) { | ||||
|       if (y + delta >= rows) break; | ||||
|       setPixelColorXY(x, y, getPixelColorXY(x, (y + delta))); | ||||
|     } | ||||
|   } else { | ||||
|     for (uint8_t x = 0; x < cols; x++) for (int16_t y = rows-1; y >= 0; y--) { | ||||
|       if (y + delta < 0) break; | ||||
|       setPixelColorXY(x, y, getPixelColorXY(x, y + delta)); | ||||
|   if (!delta || abs(delta) >= rows) return; | ||||
|   uint32_t newPxCol[rows]; | ||||
|   for (int x = 0; x < cols; x++) { | ||||
|     if (delta > 0) { | ||||
|       for (int y = 0; y < rows-delta; y++)    newPxCol[y] = getPixelColorXY(x, (y + delta)); | ||||
|       for (int y = rows-delta; y < rows; y++) newPxCol[y] = getPixelColorXY(x, wrap ? (y + delta) - rows : y); | ||||
|     } else { | ||||
|       for (int y = rows-1; y >= -delta; y--) newPxCol[y] = getPixelColorXY(x, (y + delta)); | ||||
|       for (int y = -delta-1; y >= 0; y--)    newPxCol[y] = getPixelColorXY(x, wrap ? (y + delta) + rows : y); | ||||
|     } | ||||
|     for (int y = 0; y < rows; y++) setPixelColorXY(x, y, newPxCol[y]); | ||||
|   } | ||||
| } | ||||
|  | ||||
| // move() - move all pixels in desired direction delta number of pixels | ||||
| // @param dir direction: 0=left, 1=left-up, 2=up, 3=right-up, 4=right, 5=right-down, 6=down, 7=left-down | ||||
| // @param delta number of pixels to move | ||||
| void Segment::move(uint8_t dir, uint8_t delta) { | ||||
| // @param wrap around | ||||
| void Segment::move(uint8_t dir, uint8_t delta, bool wrap) { | ||||
|   if (delta==0) return; | ||||
|   switch (dir) { | ||||
|     case 0: moveX( delta);                break; | ||||
|     case 1: moveX( delta); moveY( delta); break; | ||||
|     case 2:                moveY( delta); break; | ||||
|     case 3: moveX(-delta); moveY( delta); break; | ||||
|     case 4: moveX(-delta);                break; | ||||
|     case 5: moveX(-delta); moveY(-delta); break; | ||||
|     case 6:                moveY(-delta); break; | ||||
|     case 7: moveX( delta); moveY(-delta); break; | ||||
|     case 0: moveX( delta, wrap);                      break; | ||||
|     case 1: moveX( delta, wrap); moveY( delta, wrap); break; | ||||
|     case 2:                      moveY( delta, wrap); break; | ||||
|     case 3: moveX(-delta, wrap); moveY( delta, wrap); break; | ||||
|     case 4: moveX(-delta, wrap);                      break; | ||||
|     case 5: moveX(-delta, wrap); moveY(-delta, wrap); break; | ||||
|     case 6:                      moveY(-delta, wrap); break; | ||||
|     case 7: moveX( delta, wrap); moveY(-delta, wrap); break; | ||||
|   } | ||||
| } | ||||
|  | ||||
| void Segment::draw_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB col) { | ||||
|   if (!isActive() || radius == 0) return; // not active | ||||
|   // Bresenham’s Algorithm | ||||
|   int d = 3 - (2*radius); | ||||
|   int y = radius, x = 0; | ||||
|   while (y >= x) { | ||||
|     setPixelColorXY(cx+x, cy+y, col); | ||||
|     setPixelColorXY(cx-x, cy+y, col); | ||||
|     setPixelColorXY(cx+x, cy-y, col); | ||||
|     setPixelColorXY(cx-x, cy-y, col); | ||||
|     setPixelColorXY(cx+y, cy+x, col); | ||||
|     setPixelColorXY(cx-y, cy+x, col); | ||||
|     setPixelColorXY(cx+y, cy-x, col); | ||||
|     setPixelColorXY(cx-y, cy-x, col); | ||||
|     x++; | ||||
|     if (d > 0) { | ||||
|       y--; | ||||
|       d += 4 * (x - y) + 10; | ||||
|     } else { | ||||
|       d += 4 * x + 6; | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| // by stepko, taken from https://editor.soulmatelights.com/gallery/573-blobs | ||||
| void Segment::fill_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB col) { | ||||
|   if (!isActive() || radius == 0) return; // not active | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   for (int16_t y = -radius; y <= radius; y++) { | ||||
| @@ -431,29 +492,31 @@ void Segment::fill_circle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB col) { | ||||
|       if (x * x + y * y <= radius * radius && | ||||
|           int16_t(cx)+x>=0 && int16_t(cy)+y>=0 && | ||||
|           int16_t(cx)+x<cols && int16_t(cy)+y<rows) | ||||
|         addPixelColorXY(cx + x, cy + y, col); | ||||
|         setPixelColorXY(cx + x, cy + y, col); | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
| void Segment::nscale8(uint8_t scale) { | ||||
|   if (!isActive()) return; // not active | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   for(uint16_t y = 0; y < rows; y++) for (uint16_t x = 0; x < cols; x++) { | ||||
|   for (int y = 0; y < rows; y++) for (int x = 0; x < cols; x++) { | ||||
|     setPixelColorXY(x, y, CRGB(getPixelColorXY(x, y)).nscale8(scale)); | ||||
|   } | ||||
| } | ||||
|  | ||||
| //line function | ||||
| void Segment::drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint32_t c) { | ||||
|   if (!isActive()) return; // not active | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   if (x0 >= cols || x1 >= cols || y0 >= rows || y1 >= rows) return; | ||||
|   const int16_t dx = abs(x1-x0), sx = x0<x1 ? 1 : -1; | ||||
|   const int16_t dy = abs(y1-y0), sy = y0<y1 ? 1 : -1;  | ||||
|   const int16_t dy = abs(y1-y0), sy = y0<y1 ? 1 : -1; | ||||
|   int16_t err = (dx>dy ? dx : -dy)/2, e2; | ||||
|   for (;;) { | ||||
|     addPixelColorXY(x0,y0,c); | ||||
|     setPixelColorXY(x0,y0,c); | ||||
|     if (x0==x1 && y0==y1) break; | ||||
|     e2 = err; | ||||
|     if (e2 >-dx) { err -= dy; x0 += sx; } | ||||
| @@ -469,18 +532,19 @@ void Segment::drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint3 | ||||
|  | ||||
| // draws a raster font character on canvas | ||||
| // only supports: 4x6=24, 5x8=40, 5x12=60, 6x8=48 and 7x9=63 fonts ATM | ||||
| void Segment::drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color) { | ||||
| void Segment::drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color, uint32_t col2, int8_t rotate) { | ||||
|   if (!isActive()) return; // not active | ||||
|   if (chr < 32 || chr > 126) return; // only ASCII 32-126 supported | ||||
|   chr -= 32; // align with font table entries | ||||
|   const uint16_t cols = virtualWidth(); | ||||
|   const uint16_t rows = virtualHeight(); | ||||
|   const int font = w*h; | ||||
|  | ||||
|   CRGB col = CRGB(color); | ||||
|   CRGBPalette16 grad = CRGBPalette16(col, col2 ? CRGB(col2) : col); | ||||
|  | ||||
|   //if (w<5 || w>6 || h!=8) return; | ||||
|   for (int i = 0; i<h; i++) { // character height | ||||
|     int16_t y0 = y + i; | ||||
|     if (y0 < 0) continue; // drawing off-screen | ||||
|     if (y0 >= rows) break; // drawing off-screen | ||||
|     uint8_t bits = 0; | ||||
|     switch (font) { | ||||
|       case 24: bits = pgm_read_byte_near(&console_font_4x6[(chr * h) + i]); break;  // 5x8 font | ||||
| @@ -490,10 +554,19 @@ void Segment::drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, | ||||
|       case 60: bits = pgm_read_byte_near(&console_font_5x12[(chr * h) + i]); break; // 5x12 font | ||||
|       default: return; | ||||
|     } | ||||
|     col = ColorFromPalette(grad, (i+1)*255/h, 255, NOBLEND); | ||||
|     for (int j = 0; j<w; j++) { // character width | ||||
|       int16_t x0 = x + (w-1) - j; | ||||
|       if ((x0 >= 0 || x0 < cols) && ((bits>>(j+(8-w))) & 0x01)) { // bit set & drawing on-screen | ||||
|         addPixelColorXY(x0, y0, color); | ||||
|       int x0, y0; | ||||
|       switch (rotate) { | ||||
|         case -1: x0 = x + (h-1) - i; y0 = y + (w-1) - j; break; // -90 deg | ||||
|         case -2: | ||||
|         case  2: x0 = x + j;         y0 = y + (h-1) - i; break; // 180 deg | ||||
|         case  1: x0 = x + i;         y0 = y + j;         break; // +90 deg | ||||
|         default: x0 = x + (w-1) - j; y0 = y + i;         break; // no rotation | ||||
|       } | ||||
|       if (x0 < 0 || x0 >= cols || y0 < 0 || y0 >= rows) continue; // drawing off-screen | ||||
|       if (((bits>>(j+(8-w))) & 0x01)) { // bit set | ||||
|         setPixelColorXY(x0, y0, col); | ||||
|       } | ||||
|     } | ||||
|   } | ||||
| @@ -501,6 +574,7 @@ void Segment::drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, | ||||
|  | ||||
| #define WU_WEIGHT(a,b) ((uint8_t) (((a)*(b)+(a)+(b))>>8)) | ||||
| void Segment::wu_pixel(uint32_t x, uint32_t y, CRGB c) {      //awesome wu_pixel procedure by reddit u/sutaburosu | ||||
|   if (!isActive()) return; // not active | ||||
|   // extract the fractional parts and derive their inverses | ||||
|   uint8_t xx = x & 0xff, yy = y & 0xff, ix = 255 - xx, iy = 255 - yy; | ||||
|   // calculate the intensities for each affected pixel | ||||
|   | ||||
							
								
								
									
										1141
									
								
								wled00/FX_fcn.cpp
									
									
									
									
									
								
							
							
						
						| @@ -9,9 +9,9 @@ | ||||
| #include <IPAddress.h> | ||||
|  | ||||
| #define NODE_TYPE_ID_UNDEFINED        0 | ||||
| #define NODE_TYPE_ID_ESP8266         82 | ||||
| #define NODE_TYPE_ID_ESP32           32 | ||||
| #define NODE_TYPE_ID_ESP32S2         33 | ||||
| #define NODE_TYPE_ID_ESP8266         82 // should be 1 | ||||
| #define NODE_TYPE_ID_ESP32           32 // should be 2 | ||||
| #define NODE_TYPE_ID_ESP32S2         33 // etc | ||||
| #define NODE_TYPE_ID_ESP32S3         34 | ||||
| #define NODE_TYPE_ID_ESP32C3         35 | ||||
|  | ||||
| @@ -23,7 +23,13 @@ struct NodeStruct | ||||
|   String    nodeName; | ||||
|   IPAddress ip; | ||||
|   uint8_t   age; | ||||
|   uint8_t   nodeType; | ||||
|   union { | ||||
|     uint8_t nodeType;   // a waste of space as we only have 5 types | ||||
|     struct { | ||||
|       uint8_t type : 7; // still a waste of space (4 bits would be enough and future-proof) | ||||
|       bool    on   : 1; | ||||
|     }; | ||||
|   }; | ||||
|   uint32_t  build; | ||||
|  | ||||
|   NodeStruct() : age(0), nodeType(0), build(0) | ||||
|   | ||||
| @@ -2,7 +2,7 @@ | ||||
|  | ||||
| /* | ||||
|  * Alexa Voice On/Off/Brightness/Color Control. Emulates a Philips Hue bridge to Alexa. | ||||
|  *  | ||||
|  * | ||||
|  * This was put together from these two excellent projects: | ||||
|  * https://github.com/kakopappa/arduino-esp8266-alexa-wemo-switch | ||||
|  * https://github.com/probonopd/ESP8266HueEmulator | ||||
| @@ -21,11 +21,11 @@ void alexaInit() | ||||
|   espalexaDevice = new EspalexaDevice(alexaInvocationName, onAlexaChange, EspalexaDeviceType::extendedcolor); | ||||
|   espalexa.addDevice(espalexaDevice); | ||||
|  | ||||
|   // up to 9 devices (added second, third, ... i.e. index 1 to 9) serve for switching on up to nine presets (preset IDs 1 to 9 in WLED),  | ||||
|   // up to 9 devices (added second, third, ... i.e. index 1 to 9) serve for switching on up to nine presets (preset IDs 1 to 9 in WLED), | ||||
|   // names are identical as the preset names, switching off can be done by switching off any of them | ||||
|   if (alexaNumPresets) { | ||||
|     String name = ""; | ||||
|     for (byte presetIndex = 1; presetIndex <= alexaNumPresets; presetIndex++)  | ||||
|     for (byte presetIndex = 1; presetIndex <= alexaNumPresets; presetIndex++) | ||||
|     { | ||||
|       if (!getPresetName(presetIndex, name)) break; // no more presets | ||||
|       EspalexaDevice* dev = new EspalexaDevice(name.c_str(), onAlexaChange, EspalexaDeviceType::extendedcolor); | ||||
| @@ -44,7 +44,7 @@ void handleAlexa() | ||||
| void onAlexaChange(EspalexaDevice* dev) | ||||
| { | ||||
|   EspalexaDeviceProperty m = dev->getLastChangedProperty(); | ||||
|    | ||||
|  | ||||
|   if (m == EspalexaDeviceProperty::on) | ||||
|   { | ||||
|     if (dev->getId() == 0) // Device 0 is for on/off or macros | ||||
| @@ -56,7 +56,7 @@ void onAlexaChange(EspalexaDevice* dev) | ||||
|           bri = briLast; | ||||
|           stateUpdated(CALL_MODE_ALEXA); | ||||
|         } | ||||
|       } else  | ||||
|       } else | ||||
|       { | ||||
|         applyPreset(macroAlexaOn, CALL_MODE_ALEXA); | ||||
|         if (bri == 0) dev->setValue(briLast); //stop Alexa from complaining if macroAlexaOn does not actually turn on | ||||
| @@ -82,7 +82,7 @@ void onAlexaChange(EspalexaDevice* dev) | ||||
|         bri = 0; | ||||
|         stateUpdated(CALL_MODE_ALEXA); | ||||
|       } | ||||
|     } else  | ||||
|     } else | ||||
|     { | ||||
|       applyPreset(macroAlexaOff, CALL_MODE_ALEXA); | ||||
|       // below for loop stops Alexa from complaining if macroAlexaOff does not actually turn off | ||||
| @@ -101,20 +101,27 @@ void onAlexaChange(EspalexaDevice* dev) | ||||
|     { | ||||
|       byte rgbw[4]; | ||||
|       uint16_t ct = dev->getCt(); | ||||
| 			if (!ct) return; | ||||
| 			uint16_t k = 1000000 / ct; //mireds to kelvin | ||||
| 			 | ||||
| 			if (strip.hasCCTBus()) { | ||||
| 				strip.setCCT(k); | ||||
| 				rgbw[0]= 0; rgbw[1]= 0; rgbw[2]= 0; rgbw[3]= 255; | ||||
| 			} else if (strip.hasWhiteChannel()) { | ||||
|       if (!ct) return; | ||||
|       uint16_t k = 1000000 / ct; //mireds to kelvin | ||||
|  | ||||
|       if (strip.hasCCTBus()) { | ||||
|         bool hasManualWhite = strip.getActiveSegsLightCapabilities(true) & SEG_CAPABILITY_W; | ||||
|  | ||||
|         strip.setCCT(k); | ||||
|         if (hasManualWhite) { | ||||
|           rgbw[0] = 0; rgbw[1] = 0; rgbw[2] = 0; rgbw[3] = 255; | ||||
|         } else { | ||||
|           rgbw[0] = 255; rgbw[1] = 255; rgbw[2] = 255; rgbw[3] = 0; | ||||
|           dev->setValue(255); | ||||
|         } | ||||
|       } else if (strip.hasWhiteChannel()) { | ||||
|         switch (ct) { //these values empirically look good on RGBW | ||||
|           case 199: rgbw[0]=255; rgbw[1]=255; rgbw[2]=255; rgbw[3]=255; break; | ||||
|           case 234: rgbw[0]=127; rgbw[1]=127; rgbw[2]=127; rgbw[3]=255; break; | ||||
|           case 284: rgbw[0]=  0; rgbw[1]=  0; rgbw[2]=  0; rgbw[3]=255; break; | ||||
|           case 350: rgbw[0]=130; rgbw[1]= 90; rgbw[2]=  0; rgbw[3]=255; break; | ||||
|           case 383: rgbw[0]=255; rgbw[1]=153; rgbw[2]=  0; rgbw[3]=255; break; | ||||
| 					default : colorKtoRGB(k, rgbw); | ||||
|           default : colorKtoRGB(k, rgbw); | ||||
|         } | ||||
|       } else { | ||||
|         colorKtoRGB(k, rgbw); | ||||
|   | ||||