Compare commits
	
		
			420 Commits
		
	
	
		
			alfa
			...
			adfb564ccc
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 
						 | 
					adfb564ccc | ||
| 
						 | 
					a3eaf16fd6 | ||
| 8b32ecc619 | |||
| 7ea4a90980 | |||
| 38b29a2a4a | |||
| 821c0926e8 | |||
| 3d3b073131 | |||
| 
						 | 
					485709d61f | ||
| 
						 | 
					1d44bd62e2 | ||
| 
						 | 
					75dab33c9a | ||
| 2410441b88 | |||
| 
						 | 
					1f49391b36 | ||
| 
						 | 
					c17e3090a8 | ||
| dc77534bad | |||
| 
						 | 
					cb45cf9e22 | ||
| 
						 | 
					47a5f71d9b | ||
| 
						 | 
					1642ece7f4 | ||
| 696ff07987 | |||
| 
						 | 
					1415c0cf2d | ||
| 
						 | 
					d9952a59fb | ||
| 
						 | 
					b5b2bb95a7 | ||
| bad58f82e2 | |||
| 
						 | 
					64b50ead9f | ||
| 
						 | 
					a3a87d39d2 | ||
| 
						 | 
					c4f36235ab | ||
| daa0e0a2c5 | |||
| 
						 | 
					464f229a16 | ||
| 
						 | 
					fe72097d75 | ||
| 
						 | 
					98efb779b1 | ||
| 30045b9f65 | |||
| f21293bc01 | |||
| bf79e9cee7 | |||
| cf30a1280d | |||
| e11023d1c9 | |||
| cfcfefefd8 | |||
| 09d78192b6 | |||
| 158220700b | |||
| 
						 | 
					76e036181a | ||
| 
						 | 
					39f44c8d03 | ||
| 
						 | 
					ee0ebff76a | ||
| 42443c8b58 | |||
| e95435a707 | |||
| 74f6779c63 | |||
| 181a65a99b | |||
| 
						 | 
					ff2c51d505 | ||
| 
						 | 
					879a63948f | ||
| 
						 | 
					52688a5e70 | ||
| 
						 | 
					3181c9dc72 | ||
| 
						 | 
					ac43bdaf64 | ||
| 
						 | 
					e65b046d47 | ||
| 
						 | 
					50a0d3036c | ||
| 
						 | 
					fffaf0e237 | ||
| 
						 | 
					e9b8e0a453 | ||
| 
						 | 
					0e3f571a0d | ||
| 
						 | 
					5ad11cbb10 | ||
| 
						 | 
					a4cdb250b9 | ||
| 
						 | 
					72e6f475d7 | ||
| 
						 | 
					4b94ef29c1 | ||
| 
						 | 
					8a00190850 | ||
| 
						 | 
					38cc436f4d | ||
| 
						 | 
					fef8cb2ed9 | ||
| 
						 | 
					f205df36ff | ||
| 
						 | 
					c448f72095 | ||
| 
						 | 
					9969d3ca91 | ||
| 
						 | 
					1e9395f9e7 | ||
| 
						 | 
					0c3d14754f | ||
| 
						 | 
					2117e9acac | ||
| 
						 | 
					6689b4285e | ||
| 
						 | 
					eba00c2744 | ||
| 
						 | 
					95c8e54199 | ||
| 
						 | 
					7533facf07 | ||
| 
						 | 
					e2c16072b9 | ||
| 
						 | 
					c7e18d6959 | ||
| 
						 | 
					ea00f7a295 | ||
| 
						 | 
					e9dace53e0 | ||
| 
						 | 
					64ccd91469 | ||
| 
						 | 
					513b13dcb8 | ||
| 
						 | 
					6b08b2785f | ||
| 
						 | 
					e2c9c31d2f | ||
| 
						 | 
					13ae5401f7 | ||
| 
						 | 
					31fb9dad37 | ||
| 
						 | 
					ab92a58289 | ||
| 
						 | 
					946a93a23b | ||
| 
						 | 
					1a3e659ca7 | ||
| 
						 | 
					5d998da30a | ||
| 
						 | 
					2cbf6fbb23 | ||
| 
						 | 
					f4a5beeb7b | ||
| 
						 | 
					24b0048f57 | ||
| 
						 | 
					2871dd49dd | ||
| 
						 | 
					a3a482c652 | ||
| 
						 | 
					0b954b79c0 | ||
| 
						 | 
					ce05533d29 | ||
| 
						 | 
					9dfaeb554d | ||
| 
						 | 
					6b7bd911f7 | ||
| 
						 | 
					740a2debf7 | ||
| 
						 | 
					5d32c2bfa4 | ||
| 
						 | 
					c410df1bd6 | ||
| 
						 | 
					3aab42d081 | ||
| 
						 | 
					dffaf8eb2e | ||
| 
						 | 
					3047ead205 | ||
| 
						 | 
					e39b6655e3 | ||
| 
						 | 
					b5d7904a61 | ||
| 
						 | 
					e3b7e866f0 | ||
| 
						 | 
					94d6576070 | ||
| 
						 | 
					51f7ce9dbd | ||
| 
						 | 
					a70caca58d | ||
| 
						 | 
					81dcc9da5b | ||
| 
						 | 
					c75c67d420 | ||
| 20469c65db | |||
| aafd5539c4 | |||
| 30da6e162b | |||
| 
						 | 
					cc804f36df | ||
| 
						 | 
					ed732e125a | ||
| 
						 | 
					2c6e7e2ecc | ||
| 32521d0ed3 | |||
| 6945d58eb6 | |||
| 50e161e1ce | |||
| 366f1c4db4 | |||
| b0514c1f3a | |||
| 
						 | 
					ca5b221bc1 | ||
| 
						 | 
					fc3d3d5930 | ||
| 
						 | 
					77d6e795d6 | ||
| 
						 | 
					3c456caeca | ||
| 
						 | 
					5647bb21a7 | ||
| 960859087a | |||
| 
						 | 
					8e33d226cd | ||
| 
						 | 
					9b9b67d01e | ||
| 
						 | 
					50bd53561e | ||
| 
						 | 
					6b0ab2d0ba | ||
| 0efbda0583 | |||
| 7f42d49634 | |||
| a6cb51f2f5 | |||
| b174022f9a | |||
| d404afe501 | |||
| ceca8fc057 | |||
| 7df378d794 | |||
| 98c603494d | |||
| 27c306cba7 | |||
| 70ef954b64 | |||
| 
						 | 
					6d44750804 | ||
| 
						 | 
					49d24f8e0e | ||
| 5ee1af2571 | |||
| 2185c62472 | |||
| 
						 | 
					bde466a5bd | ||
| 3d68df2658 | |||
| 880b01882a | |||
| 727ed03be7 | |||
| 0323323bb1 | |||
| fa10200bde | |||
| 03cc627b72 | |||
| 3665d0afd9 | |||
| be09f00b95 | |||
| 4b20c5fd0d | |||
| 5ba86edb69 | |||
| 67cc103db5 | |||
| 1a448663f0 | |||
| 1a27993a94 | |||
| 
						 | 
					82e5248658 | ||
| 
						 | 
					eba5301906 | ||
| 8a6185e329 | |||
| d013788249 | |||
| 14a33b83d0 | |||
| 05bd0dbc64 | |||
| 
						 | 
					d1b4597720 | ||
| dbbf42bc0d | |||
| 1996b08311 | |||
| 
						 | 
					275aa97688 | ||
| 
						 | 
					8ed3ab2f39 | ||
| 
						 | 
					7f5d348d07 | ||
| 
						 | 
					5f95548b92 | ||
| 
						 | 
					7a3beea274 | ||
| 
						 | 
					61a1b5057c | ||
| 
						 | 
					cdcddffc69 | ||
| 
						 | 
					3669fde596 | ||
| 
						 | 
					a1358c53fd | ||
| 
						 | 
					78c29482a6 | ||
| 
						 | 
					7954ae49b9 | ||
| 
						 | 
					2ddb2750ab | ||
| 
						 | 
					4c3aaa40bc | ||
| 
						 | 
					fc8891425d | ||
| 
						 | 
					348f8ab57d | ||
| 
						 | 
					b0650e7fbe | ||
| 
						 | 
					dcc7592c4f | ||
| 
						 | 
					cb6ab3bdda | ||
| 
						 | 
					41916a90bd | ||
| 
						 | 
					da975598c5 | ||
| 
						 | 
					35279a2b51 | ||
| 
						 | 
					804a5d1212 | ||
| 
						 | 
					aef5b5116d | ||
| 
						 | 
					ae0d5b86ad | ||
| 
						 | 
					c961bc2c88 | ||
| 
						 | 
					254a2cf97a | ||
| 
						 | 
					e7858ac4a3 | ||
| 
						 | 
					0b9f7486df | ||
| 
						 | 
					97408d31e9 | ||
| 
						 | 
					b2474fbdfb | ||
| 
						 | 
					0543f74977 | ||
| 
						 | 
					c3f11a4c66 | ||
| 
						 | 
					0929870cc9 | ||
| 
						 | 
					b036adf206 | ||
| 
						 | 
					4fbbf5acbf | ||
| 
						 | 
					b8b81626e8 | ||
| 
						 | 
					7af1eda141 | ||
| 
						 | 
					dc50d5d4d6 | ||
| 
						 | 
					e4d93c7add | ||
| 
						 | 
					6a20e9c684 | ||
| 
						 | 
					2c5d861011 | ||
| 
						 | 
					778e862b97 | ||
| 
						 | 
					862fc29bde | ||
| 
						 | 
					fef3c1e57f | ||
| 
						 | 
					1af11f3f58 | ||
| 
						 | 
					cb8bd40a7e | ||
| 
						 | 
					87c719e9e6 | ||
| 
						 | 
					090b9f7a7b | ||
| 
						 | 
					2f638d8091 | ||
| 
						 | 
					619386d391 | ||
| 
						 | 
					ded8a698f0 | ||
| 
						 | 
					c3d8a211ed | ||
| 
						 | 
					02ba4e5d6f | ||
| 
						 | 
					d7a5d35f54 | ||
| 
						 | 
					135338041a | ||
| 
						 | 
					cd895d3bcc | ||
| 
						 | 
					3d541999a1 | ||
| 
						 | 
					1070d8036c | ||
| 
						 | 
					26dab209bd | ||
| 
						 | 
					22e680e1d8 | ||
| 
						 | 
					9961016683 | ||
| 
						 | 
					c2203b452a | ||
| 
						 | 
					3981d9551d | ||
| 
						 | 
					6458e89dea | ||
| 
						 | 
					63e7c95415 | ||
| 
						 | 
					8d2af9181a | ||
| 
						 | 
					13678630f2 | ||
| 
						 | 
					27d2c4fa18 | ||
| 
						 | 
					6383034de1 | ||
| 
						 | 
					8f13c7ee5d | ||
| 
						 | 
					4113296f86 | ||
| 
						 | 
					c74f93890d | ||
| 
						 | 
					043cac1cba | ||
| 
						 | 
					23aa83ec9a | ||
| 
						 | 
					8b39b727e1 | ||
| 
						 | 
					f588a293ed | ||
| 
						 | 
					56891bda09 | ||
| 
						 | 
					a1cfb21a81 | ||
| 
						 | 
					c774ad90c2 | ||
| 
						 | 
					e0bbc09389 | ||
| 
						 | 
					a3d911d3ec | ||
| 
						 | 
					2560800efb | ||
| 
						 | 
					57501e2847 | ||
| 
						 | 
					8fd7fe8329 | ||
| 
						 | 
					e75de72afd | ||
| 
						 | 
					d137d08ff4 | ||
| 
						 | 
					09ad9c9eba | ||
| 
						 | 
					11e75cb18d | ||
| 
						 | 
					e4f37f7686 | ||
| 
						 | 
					119149bf5e | ||
| 
						 | 
					8300e47b76 | ||
| 
						 | 
					0f51826d3f | ||
| 
						 | 
					abff057943 | ||
| 
						 | 
					79016fed87 | ||
| 
						 | 
					fe787163d0 | ||
| 
						 | 
					5519d46ca2 | ||
| 
						 | 
					b4cfffc432 | ||
| 
						 | 
					84127bf7ab | ||
| 
						 | 
					34ee711182 | ||
| 
						 | 
					cdcc63a81a | ||
| 
						 | 
					bc0816e812 | ||
| 
						 | 
					3dbec89f7b | ||
| 
						 | 
					9367564bfe | ||
| 
						 | 
					048b9440e1 | ||
| 
						 | 
					a6453cf393 | ||
| 
						 | 
					386e7be130 | ||
| 
						 | 
					e8b2ad8599 | ||
| 
						 | 
					7548f409f2 | ||
| 
						 | 
					a13c30a5c3 | ||
| 
						 | 
					b326596e16 | ||
| 
						 | 
					ee65ea43c4 | ||
| 
						 | 
					0f49fd951a | ||
| 
						 | 
					ba836c9573 | ||
| 
						 | 
					1e6fe2a00e | ||
| 
						 | 
					bc76082860 | ||
| 
						 | 
					85b10e1098 | ||
| 
						 | 
					c520cf847c | ||
| 
						 | 
					8c96a6021a | ||
| 
						 | 
					bfebe6b534 | ||
| 
						 | 
					216db28e60 | ||
| 
						 | 
					e76d2bc5e5 | ||
| 
						 | 
					d51820b198 | ||
| 
						 | 
					c58804ad12 | ||
| 
						 | 
					06fdc71ca2 | ||
| 
						 | 
					bc9e9e16e7 | ||
| 
						 | 
					bc6acb470a | ||
| 
						 | 
					15dfc8464d | ||
| 
						 | 
					36690e6899 | ||
| 
						 | 
					79b79bdfa5 | ||
| 
						 | 
					44c4a122f7 | ||
| 
						 | 
					28490f5d67 | ||
| 
						 | 
					74c6426500 | ||
| 
						 | 
					dec5a9083a | ||
| 
						 | 
					a1337d795d | ||
| 
						 | 
					e22d98cf6a | ||
| 
						 | 
					0593bf09dd | ||
| 
						 | 
					4f1d2e18fc | ||
| 
						 | 
					15b0f97971 | ||
| 
						 | 
					2a33e070b8 | ||
| 
						 | 
					da01823b00 | ||
| 
						 | 
					12212d6c56 | ||
| 
						 | 
					b2a8734ed3 | ||
| 3feeaab086 | |||
| 8cacccbf88 | |||
| 
						 | 
					8ab0b043f9 | ||
| 
						 | 
					24072cb582 | ||
| 
						 | 
					801e26dda9 | ||
| 
						 | 
					ceeb002b6e | ||
| 
						 | 
					f570556d85 | ||
| b5d48be64a | |||
| 
						 | 
					e14a0edb3c | ||
| 
						 | 
					ca2cb2dbd2 | ||
| 
						 | 
					62449d2528 | ||
| 
						 | 
					0d0ba4ae50 | ||
| 
						 | 
					942c7a4bca | ||
| 
						 | 
					aaa713e646 | ||
| 
						 | 
					9d52a86aa8 | ||
| 
						 | 
					a2030d944f | ||
| 
						 | 
					0b92c0a84a | ||
| 
						 | 
					3ff5e0d660 | ||
| b158f4a042 | |||
| b05fa3e1ed | |||
| 50100fd4c5 | |||
| 7825cbb7aa | |||
| 
						 | 
					94f78af31b | ||
| 
						 | 
					6184f3815f | ||
| 
						 | 
					44c4c84292 | ||
| 
						 | 
					0d076eb67c | ||
| 
						 | 
					3a6706d1ac | ||
| 9a8ea80f37 | |||
| 
						 | 
					e8def0f4ae | ||
| 
						 | 
					f4ee4d5a7c | ||
| 437d6f32c0 | |||
| 
						 | 
					b16766c65e | ||
| 
						 | 
					b1b8c4925b | ||
| 
						 | 
					e2f7d72cb3 | ||
| 
						 | 
					a8daa51413 | ||
| 
						 | 
					9d9bdc192f | ||
| 
						 | 
					eb62f02510 | ||
| 
						 | 
					5d25eeccaf | ||
| 
						 | 
					f3ec7476b2 | ||
| 
						 | 
					029d75cd33 | ||
| 
						 | 
					4b1a26cc6f | ||
| 
						 | 
					74e427fee2 | ||
| 
						 | 
					1e973d2d8f | ||
| 
						 | 
					d8c7a54446 | ||
| 
						 | 
					edf0b1ceb4 | ||
| 
						 | 
					ccd064ad3c | ||
| 
						 | 
					dc4433899a | ||
| 
						 | 
					8a0f4d1956 | ||
| 
						 | 
					c43b751bd3 | ||
| 
						 | 
					5a06a6c85a | ||
| 
						 | 
					15d95dae1d | ||
| 
						 | 
					bcd5f52a65 | ||
| 
						 | 
					0b8ad755a0 | ||
| 
						 | 
					f0e82de775 | ||
| 
						 | 
					4ab9ad9c7c | ||
| 
						 | 
					1b5630215b | ||
| 
						 | 
					bc54e33621 | ||
| 
						 | 
					e76b3127f3 | ||
| 
						 | 
					a0fdd324e2 | ||
| 
						 | 
					cb95a0f9b8 | ||
| 
						 | 
					fc7689b5a6 | ||
| 
						 | 
					21bcff9660 | ||
| 
						 | 
					c499a83a0c | ||
| 
						 | 
					84f130faf3 | ||
| 
						 | 
					3479fb9c87 | ||
| 
						 | 
					f345419c39 | ||
| 
						 | 
					2dd2b3c6f7 | ||
| 
						 | 
					db3ab9dd95 | ||
| 
						 | 
					dd8743d33e | ||
| 
						 | 
					842cbde2d8 | ||
| 
						 | 
					ad89a18093 | ||
| 
						 | 
					6f0fa2f81e | ||
| 
						 | 
					8e9639c257 | ||
| 
						 | 
					1e5564a11a | ||
| 
						 | 
					e1a7b69fee | ||
| 
						 | 
					65e218e47b | ||
| 
						 | 
					cda98cdf77 | ||
| 
						 | 
					48fcd1a7c9 | ||
| 
						 | 
					2d7db196dd | ||
| 
						 | 
					ded59cc24a | ||
| 
						 | 
					b1dd8dc297 | ||
| 
						 | 
					eddccead63 | ||
| 
						 | 
					ff3c796484 | ||
| 
						 | 
					8b6a12c811 | ||
| 
						 | 
					55cc65eddb | ||
| 
						 | 
					3bca87a4b3 | ||
| 
						 | 
					563999e92d | ||
| 
						 | 
					b2e4da37bf | ||
| 
						 | 
					65439922b1 | ||
| 
						 | 
					4229c44678 | ||
| 
						 | 
					3fc6e931ef | ||
| 
						 | 
					e0ee40cb0d | ||
| 
						 | 
					0045d00abc | ||
| 
						 | 
					2b1ae58d55 | ||
| 
						 | 
					5418452da2 | ||
| 
						 | 
					d67bac14e9 | ||
| 
						 | 
					3b72bf85fd | ||
| 
						 | 
					b620ea6c8f | ||
| 
						 | 
					aef242ceca | ||
| 
						 | 
					8975eb785b | ||
| 
						 | 
					878186c2a2 | ||
| 
						 | 
					1e7f16d3b9 | ||
| 
						 | 
					79864c23fd | ||
| 
						 | 
					7337e3c7d9 | ||
| 
						 | 
					9e6968bf6c | ||
| 
						 | 
					3e71be821c | ||
| 
						 | 
					a5a5baffc9 | ||
| 
						 | 
					88152ebeae | ||
| 
						 | 
					2fdc1b5bcc | ||
| 
						 | 
					b26ab5c032 | ||
| 
						 | 
					6dbd4885e2 | ||
| 
						 | 
					7d2bc0c6d6 | 
							
								
								
									
										1
									
								
								.docker
									
									
									
									
									
										Submodule
									
								
							
							
								
								
								
								
								
							
						
						
									
										1
									
								
								.docker
									
									
									
									
									
										Submodule
									
								
							 Submodule .docker added at 0ee345e496
									
								
							@@ -3,29 +3,16 @@
 | 
			
		||||
root = true
 | 
			
		||||
 | 
			
		||||
[*]
 | 
			
		||||
tab_width                = 4
 | 
			
		||||
 | 
			
		||||
[*.{php,phpt,inc}]
 | 
			
		||||
charset                  = utf-8
 | 
			
		||||
end_of_line              = lf
 | 
			
		||||
indent_size              = 2
 | 
			
		||||
indent_style = tab
 | 
			
		||||
indent_size = 3
 | 
			
		||||
end_of_line = lf
 | 
			
		||||
charset = utf-8
 | 
			
		||||
trim_trailing_whitespace = true
 | 
			
		||||
insert_final_newline = true
 | 
			
		||||
 | 
			
		||||
[*.md]
 | 
			
		||||
charset                  = utf-8
 | 
			
		||||
end_of_line              = lf
 | 
			
		||||
indent_style             = tab
 | 
			
		||||
trim_trailing_whitespace = true
 | 
			
		||||
insert_final_newline     = true
 | 
			
		||||
max_line_length          = 80
 | 
			
		||||
 | 
			
		||||
[COMMIT_EDITMSG]
 | 
			
		||||
charset                  = utf-8
 | 
			
		||||
end_of_line              = lf
 | 
			
		||||
indent_size              = 4
 | 
			
		||||
indent_style             = tab
 | 
			
		||||
trim_trailing_whitespace = true
 | 
			
		||||
insert_final_newline     = true
 | 
			
		||||
max_line_length          = 80
 | 
			
		||||
@@ -3,3 +3,4 @@ _FIRMWARE
 | 
			
		||||
_INSTALATION
 | 
			
		||||
_README_IMG
 | 
			
		||||
README.md
 | 
			
		||||
.todo
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										14
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										14
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							@@ -1,7 +1,21 @@
 | 
			
		||||
 | 
			
		||||
.ftpconfig
 | 
			
		||||
.ftpconfig2
 | 
			
		||||
*.log
 | 
			
		||||
*.bin
 | 
			
		||||
config.php
 | 
			
		||||
 | 
			
		||||
_nemazat/index.html
 | 
			
		||||
_nemazat/css/main.css.map
 | 
			
		||||
_nemazat/css/main.css
 | 
			
		||||
_nemazat/css/font-awesome.min.css
 | 
			
		||||
 | 
			
		||||
.vscode/
 | 
			
		||||
.vscode/sftp.json
 | 
			
		||||
 | 
			
		||||
app/updater/*.bin
 | 
			
		||||
app/logs/*.log
 | 
			
		||||
backup/*.zip
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
vendor/
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										3
									
								
								.gitmodules
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										3
									
								
								.gitmodules
									
									
									
									
										vendored
									
									
										Normal file
									
								
							@@ -0,0 +1,3 @@
 | 
			
		||||
[submodule ".docker"]
 | 
			
		||||
	path = .docker
 | 
			
		||||
	url = https://github.com/GamerClassN7/Docker-Xamp-Server.git
 | 
			
		||||
							
								
								
									
										29
									
								
								.htaccess
									
									
									
									
									
								
							
							
						
						
									
										29
									
								
								.htaccess
									
									
									
									
									
								
							@@ -1,17 +1,22 @@
 | 
			
		||||
Options -Indexes
 | 
			
		||||
Options -MultiViews -Indexes
 | 
			
		||||
 | 
			
		||||
RewriteEngine On
 | 
			
		||||
RewriteBase /vasek/home/
 | 
			
		||||
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} !-f
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} !-d
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} !.css
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} !.js
 | 
			
		||||
RewriteRule (.*) index.php?url=$1 [QSA,L]
 | 
			
		||||
# require https
 | 
			
		||||
#RewriteCond %{HTTPS} off
 | 
			
		||||
#RewriteCond %{REQUEST_URI} !^/api/update
 | 
			
		||||
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 | 
			
		||||
 | 
			
		||||
RewriteCond %{HTTPS} off
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} !api.php
 | 
			
		||||
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 | 
			
		||||
#token to HTTP_AUTHORIZATION
 | 
			
		||||
RewriteCond %{HTTP:Authorization} ^(.*)
 | 
			
		||||
RewriteRule . - [e=HTTP_AUTHORIZATION:%1]
 | 
			
		||||
 | 
			
		||||
# serve all files from public subfolder
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} !.php
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} !.log
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} !.ttfnot
 | 
			
		||||
RewriteCond %{REQUEST_FILENAME} \.
 | 
			
		||||
RewriteRule (.*) ./public/$1 [L]
 | 
			
		||||
 | 
			
		||||
# serve all other request as query parameters
 | 
			
		||||
RewriteRule (.*) ./public/index.php?url=$1 [L,QSA]
 | 
			
		||||
 | 
			
		||||
AddType application/x-httpd-php .php .phtml
 | 
			
		||||
							
								
								
									
										13
									
								
								.todo
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								.todo
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,13 @@
 | 
			
		||||
//TODO: Automation last Run Time
 | 
			
		||||
//TODO: Check if every automation type Works
 | 
			
		||||
//TODO: Add Switch to Setting For debug mode
 | 
			
		||||
//TODO: hide menu item Debug When Debug mode is disabled
 | 
			
		||||
//TODO: Check if every setting works
 | 
			
		||||
//TODO: Add slector to automation execute all To execute only utomation whitch contain same day (as actual to speed up process)
 | 
			
		||||
//TODO: Check and fix time based automation
 | 
			
		||||
//TODO: 404 same like in ENergo COunter Project
 | 
			
		||||
//TODO: @FILIP Fix Editation of all Automations
 | 
			
		||||
//TODO: @FILIP test if registration work without an isuu even with notification
 | 
			
		||||
//TODO: Fix Default Room selection
 | 
			
		||||
//TODO: Fix User Delete button
 | 
			
		||||
//TODO: Fix new add email form
 | 
			
		||||
							
								
								
									
										2
									
								
								LICENSE
									
									
									
									
									
								
							
							
						
						
									
										2
									
								
								LICENSE
									
									
									
									
									
								
							@@ -1,6 +1,6 @@
 | 
			
		||||
MIT License
 | 
			
		||||
 | 
			
		||||
Copyright (c) 2019 JonatanRek
 | 
			
		||||
Copyright (c) 2019 JonatanRek<gamerclassn7@gamil.com> :)
 | 
			
		||||
 | 
			
		||||
Permission is hereby granted, free of charge, to any person obtaining a copy
 | 
			
		||||
of this software and associated documentation files (the "Software"), to deal
 | 
			
		||||
 
 | 
			
		||||
@@ -1,6 +1,7 @@
 | 
			
		||||
<pre>
 | 
			
		||||
	<?php
 | 
			
		||||
	var_dump($_POST);
 | 
			
		||||
	var_dump(file_exists("./app/updater/" . "3C71BF22FDCF" . ".bin"));
 | 
			
		||||
	?>
 | 
			
		||||
</pre>
 | 
			
		||||
 | 
			
		||||
							
								
								
									
										45
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										45
									
								
								README.md
									
									
									
									
									
								
							@@ -135,3 +135,48 @@ Distributed under the MIT License. See `LICENSE` for more information.
 | 
			
		||||
 | 
			
		||||
Project Link: [https://github.com/GamerClassN7/Smart_Home/](https://github.com/GamerClassN7/Smart_Home/) <br> <br>
 | 
			
		||||
<sup><sub>Tags (ignore): ESP32 ESP12 ESP08 ESP01 ESP Smart Home Automation System PWA PHP HTML JS DHT11 DHT22
 | 
			
		||||
 | 
			
		||||
## Code Statistics
 | 
			
		||||
Type | Files | Lines
 | 
			
		||||
-----|-------|-----------
 | 
			
		||||
php  | 2     | 2298 (89%)
 | 
			
		||||
md   | 1     | 171 (7%)
 | 
			
		||||
js   | 1     | 64 (2%)
 | 
			
		||||
sh   | 1     | 34 (1%)
 | 
			
		||||
json | 1     | 10 (0.4%)
 | 
			
		||||
-----|-------|-----------
 | 
			
		||||
All  | 6     | 2577
 | 
			
		||||
 | 
			
		||||
## Folder structure
 | 
			
		||||
```
 | 
			
		||||
- /app								# app specific files
 | 
			
		||||
	- /controllers
 | 
			
		||||
		- UserController.php
 | 
			
		||||
	- /library						# helpers etc.
 | 
			
		||||
	- /models
 | 
			
		||||
		- /types
 | 
			
		||||
			- Units.php
 | 
			
		||||
		- UserModal.php
 | 
			
		||||
	- /views
 | 
			
		||||
		- /layouts
 | 
			
		||||
			- default.phtml
 | 
			
		||||
		- /templates
 | 
			
		||||
			- /components
 | 
			
		||||
			- /pages
 | 
			
		||||
	- Bootstrap.php
 | 
			
		||||
	- Db.php
 | 
			
		||||
	- Routes.php
 | 
			
		||||
- /library 							# framework, 3rd libraries etc.
 | 
			
		||||
	- /vendor
 | 
			
		||||
	- Controller.php
 | 
			
		||||
	- Db.php
 | 
			
		||||
	- Router.php
 | 
			
		||||
- config
 | 
			
		||||
	- config.php /
 | 
			
		||||
- public
 | 
			
		||||
	- /css
 | 
			
		||||
	- /images
 | 
			
		||||
	- /js
 | 
			
		||||
	- .htaccess
 | 
			
		||||
	- index.php
 | 
			
		||||
```
 | 
			
		||||
 
 | 
			
		||||
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							@@ -1,213 +0,0 @@
 | 
			
		||||
; CH341SER.INF
 | 
			
		||||
; Driver for CH341 (USB=>SERIAL chip) V3.4
 | 
			
		||||
; WDM&VXD for Windows 98/Me/2000/XP/Server2003/Vista/64bit Vista/Server2008/Win7/64bit Win7
 | 
			
		||||
; Copyright (C) W.ch 2001-2014
 | 
			
		||||
;
 | 
			
		||||
 | 
			
		||||
[Version]
 | 
			
		||||
Signature = "$Chicago$"
 | 
			
		||||
Class     = Ports
 | 
			
		||||
ClassGuid = {4D36E978-E325-11CE-BFC1-08002BE10318}
 | 
			
		||||
Provider  = %WinChipHead%
 | 
			
		||||
DriverVer = 08/08/2014, 3.4.2014.08
 | 
			
		||||
CatalogFile = CH341SER.CAT
 | 
			
		||||
 | 
			
		||||
[ControlFlags]
 | 
			
		||||
ExcludeFromSelect = USB\VID_1A86&PID_7523
 | 
			
		||||
ExcludeFromSelect = USB\VID_1A86&PID_5523
 | 
			
		||||
ExcludeFromSelect = USB\VID_4348&PID_5523
 | 
			
		||||
ExcludeFromSelect = USB\VID_4348&PID_5523&REV_0250
 | 
			
		||||
ExcludeFromSelect = USBSERPORT\SER5523
 | 
			
		||||
ExcludeFromSelect = CH341PORT\SER5523
 | 
			
		||||
 | 
			
		||||
[Manufacturer]
 | 
			
		||||
%WinChipHead% = WinChipHead,NT,NTamd64,NTia64
 | 
			
		||||
 | 
			
		||||
[WinChipHead]
 | 
			
		||||
%CH340SER.DeviceDesc% = CH341SER_Install, USB\VID_1A86&PID_7523
 | 
			
		||||
%CH341ASER.DeviceDesc% = CH341SER_Install, USB\VID_1A86&PID_5523
 | 
			
		||||
%CH341SER.DeviceDesc% = CH341SER_Install, USB\VID_4348&PID_5523
 | 
			
		||||
%CH340SER.DeviceDesc% = CH341SER_Install, USB\VID_4348&PID_5523&REV_0250
 | 
			
		||||
%CH341S98.DeviceDesc% = CH341S98_Install, USBSERPORT\SER5523
 | 
			
		||||
%CH341S98.DeviceDesc% = CH341S98_Install, CH341PORT\SER5523
 | 
			
		||||
 | 
			
		||||
[WinChipHead.NT]
 | 
			
		||||
%CH340SER.DeviceDesc% = CH341SER_Install.NT, USB\VID_1A86&PID_7523
 | 
			
		||||
%CH341ASER.DeviceDesc% = CH341SER_Install.NT, USB\VID_1A86&PID_5523
 | 
			
		||||
%CH341SER.DeviceDesc% = CH341SER_Install.NT, USB\VID_4348&PID_5523
 | 
			
		||||
%CH340SER.DeviceDesc% = CH341SER_Install.NT, USB\VID_4348&PID_5523&REV_0250
 | 
			
		||||
 | 
			
		||||
[WinChipHead.NTamd64]
 | 
			
		||||
%CH340SER.DeviceDesc% = CH341SER_Inst.NTamd64, USB\VID_1A86&PID_7523
 | 
			
		||||
%CH341ASER.DeviceDesc% = CH341SER_Inst.NTamd64, USB\VID_1A86&PID_5523
 | 
			
		||||
%CH341SER.DeviceDesc% = CH341SER_Inst.NTamd64, USB\VID_4348&PID_5523
 | 
			
		||||
%CH340SER.DeviceDesc% = CH341SER_Inst.NTamd64, USB\VID_4348&PID_5523&REV_0250
 | 
			
		||||
 | 
			
		||||
[WinChipHead.NTia64]
 | 
			
		||||
%CH340SER.DeviceDesc% = CH341SER_Inst.NTia64, USB\VID_1A86&PID_7523
 | 
			
		||||
%CH341ASER.DeviceDesc% = CH341SER_Inst.NTia64, USB\VID_1A86&PID_5523
 | 
			
		||||
%CH341SER.DeviceDesc% = CH341SER_Inst.NTia64, USB\VID_4348&PID_5523
 | 
			
		||||
%CH340SER.DeviceDesc% = CH341SER_Inst.NTia64, USB\VID_4348&PID_5523&REV_0250
 | 
			
		||||
 | 
			
		||||
[CH341SER_Install]
 | 
			
		||||
DelFiles  = CH341S98.DelFiles.SYS
 | 
			
		||||
CopyFiles = CH341SER.CopyFiles.SYS, CH341SER.CopyFiles.DLL
 | 
			
		||||
AddReg    = CH341SER.9X.AddReg, CH341SER.AddReg
 | 
			
		||||
 | 
			
		||||
[CH341SER_Install.NT]
 | 
			
		||||
CopyFiles = CH341SER.NT.CopyFiles.SYS, CH341SER.CopyFiles.DLL
 | 
			
		||||
AddReg    = CH341SER.NT.AddReg, CH341SER.AddReg
 | 
			
		||||
 | 
			
		||||
[CH341SER_Install.NT.HW]
 | 
			
		||||
AddReg    = CH341SER.NT.HW.AddReg
 | 
			
		||||
 | 
			
		||||
[CH341SER_Inst.NTamd64]
 | 
			
		||||
CopyFiles = CH341SER.NT.CopyFiles.SYSA64
 | 
			
		||||
AddReg    = CH341SER.NT.AddReg, CH341SER.AddReg
 | 
			
		||||
 | 
			
		||||
[CH341SER_Inst.NTamd64.HW]
 | 
			
		||||
AddReg    = CH341SER.NT.HW.AddReg
 | 
			
		||||
 | 
			
		||||
[CH341SER_Inst.NTia64]
 | 
			
		||||
CopyFiles = CH341SER.NT.CopyFiles.SYSI64
 | 
			
		||||
AddReg    = CH341SER.NT.AddReg, CH341SER.AddReg
 | 
			
		||||
 | 
			
		||||
[CH341SER_Inst.NTia64.HW]
 | 
			
		||||
AddReg    = CH341SER.NT.HW.AddReg
 | 
			
		||||
 | 
			
		||||
[CH341S98_Install]
 | 
			
		||||
DelFiles  = CH341S98.DelFiles.SYS
 | 
			
		||||
CopyFiles = CH341S98.CopyFiles.VXD, CH341SER.CopyFiles.SYS
 | 
			
		||||
AddReg    = CH341S98.9X.AddReg, CH341S98.AddReg
 | 
			
		||||
 | 
			
		||||
;[CH341S98_Install.NT]
 | 
			
		||||
 | 
			
		||||
[CH341S98.DelFiles.SYS]
 | 
			
		||||
CH341S98.SYS, , , 1
 | 
			
		||||
 | 
			
		||||
[CH341SER.CopyFiles.SYS]
 | 
			
		||||
CH341S98.SYS, , , 2
 | 
			
		||||
 | 
			
		||||
[CH341SER.NT.CopyFiles.SYS]
 | 
			
		||||
CH341SER.SYS, , , 2
 | 
			
		||||
 | 
			
		||||
[CH341SER.NT.CopyFiles.SYSA64]
 | 
			
		||||
CH341S64.SYS, , , 2
 | 
			
		||||
 | 
			
		||||
[CH341SER.NT.CopyFiles.SYSI64]
 | 
			
		||||
;CH341I64.SYS, , , 2
 | 
			
		||||
 | 
			
		||||
[CH341S98.CopyFiles.VXD]
 | 
			
		||||
CH341SER.VXD, , , 2
 | 
			
		||||
 | 
			
		||||
[CH341SER.CopyFiles.DLL]
 | 
			
		||||
CH341PT.DLL, , , 2
 | 
			
		||||
;<3B><>װDLL<4C>ǿ<EFBFBD>ѡ<EFBFBD><D1A1>,DLL<4C><4C><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʶ<EFBFBD><CAB6>CH341<34>˿ںͼ<DABA><CDBC><EFBFBD>CH341<34>˿ڵIJ<DAB5><C4B2><EFBFBD><EFBFBD>¼<EFBFBD>
 | 
			
		||||
 | 
			
		||||
[CH341SER.9X.AddReg]
 | 
			
		||||
HKR, , DevLoader, , *NTKERN
 | 
			
		||||
HKR, , NTMPDriver, , CH341S98.SYS
 | 
			
		||||
 | 
			
		||||
[CH341SER.NT.AddReg]
 | 
			
		||||
HKR,,EnumPropPages32,,"MsPorts.dll,SerialPortPropPageProvider"
 | 
			
		||||
 | 
			
		||||
[CH341SER.NT.HW.AddReg]
 | 
			
		||||
HKR,,"UpperFilters",0x00010000,"serenum"
 | 
			
		||||
;<3B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ö<EFBFBD>ٽ<EFBFBD><D9BD>ڴ<EFBFBD><DAB4>ڵļ<DAB5><C4BC>弴<EFBFBD><E5BCB4><EFBFBD>豸,<2C><><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>DTR<54><52>RTS<54>ź<EFBFBD>,<2C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫö<D2AA><C3B6>,<2C>뽫<EFBFBD><EBBDAB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>еķֺ<C4B7>ȥ<EFBFBD><C8A5>
 | 
			
		||||
 | 
			
		||||
[CH341S98.9X.AddReg]
 | 
			
		||||
HKR, , DevLoader, , *vcomm
 | 
			
		||||
HKR, , PortDriver, , CH341SER.VXD
 | 
			
		||||
HKR, , Contention, , *vcd
 | 
			
		||||
HKR, , ConfigDialog, , serialui.dll
 | 
			
		||||
HKR, , DCB, 3, 1C,00,00,00, 80,25,00,00, 11,00,00,00, 00,00,0A,00, 0A,00,08,00, 00,11,13,00, 00,00,00,00
 | 
			
		||||
HKR, , PortSubClass, 1, 01
 | 
			
		||||
HKR, , EnumPropPages, , "serialui.dll,EnumPropPages"
 | 
			
		||||
HKR, , Enumerator, , serenum.vxd
 | 
			
		||||
;<3B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ö<EFBFBD>ٽ<EFBFBD><D9BD>ڴ<EFBFBD><DAB4>ڵļ<DAB5><C4BC>弴<EFBFBD><E5BCB4><EFBFBD>豸,<2C><><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>DTR<54><52>RTS<54>ź<EFBFBD>,<2C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫö<D2AA><C3B6>,<2C>뽫<EFBFBD><EBBDAB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>еķֺ<C4B7>ȥ<EFBFBD><C8A5>
 | 
			
		||||
 | 
			
		||||
[CH341SER.AddReg]
 | 
			
		||||
HKLM, SOFTWARE\WinChipHead\IC\CH341SER, WDM, 0x00010001, 0x00000034
 | 
			
		||||
HKLM, SOFTWARE\WinChipHead\IC\CH341PORT, DLL, 0x00010001, 0x00000010
 | 
			
		||||
HKLM, SOFTWARE\WinChipHead\IC\CH341SER, Function, , "USB=>Serial"
 | 
			
		||||
;HKLM, SYSTEM\CurrentControlSet\Services\CH341SER, UserRemoval, 0x00010001, 0x00000001
 | 
			
		||||
;<3B><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϵͳ<CFB5><CDB3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʾ<EFBFBD><CABE><EFBFBD><EFBFBD>ȫɾ<C8AB><C9BE>USBתSERIALӲ<4C><D3B2><EFBFBD>豸<EFBFBD><E8B1B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>û<EFBFBD><C3BB>ֹ<EFBFBD>ɾ<EFBFBD><C9BE>Ӳ<EFBFBD><D3B2>
 | 
			
		||||
 | 
			
		||||
[CH341S98.AddReg]
 | 
			
		||||
HKLM, SOFTWARE\WinChipHead\IC\CH341SER, VXD, 0x00010001, 0x00000023
 | 
			
		||||
 | 
			
		||||
[CH341SER_Install.NT.Services]
 | 
			
		||||
AddService = CH341SER, 2, CH341SER.Service
 | 
			
		||||
AddService = Serenum, , Serenum_Service_Inst
 | 
			
		||||
 | 
			
		||||
[CH341SER_Inst.NTamd64.Services]
 | 
			
		||||
AddService = CH341SER_A64, 2, CH341SER.ServiceA64
 | 
			
		||||
AddService = Serenum, , Serenum_Service_Inst
 | 
			
		||||
 | 
			
		||||
[CH341SER_Inst.NTia64.Services]
 | 
			
		||||
AddService = CH341SER_I64, 2, CH341SER.ServiceI64
 | 
			
		||||
AddService = Serenum, , Serenum_Service_Inst
 | 
			
		||||
 | 
			
		||||
[CH341SER.Service]
 | 
			
		||||
DisplayName   = "CH341SER"
 | 
			
		||||
ServiceType   = 1
 | 
			
		||||
StartType     = 3
 | 
			
		||||
ErrorControl  = 1
 | 
			
		||||
ServiceBinary = %10%\System32\Drivers\CH341SER.SYS
 | 
			
		||||
 | 
			
		||||
[CH341SER.ServiceA64]
 | 
			
		||||
DisplayName   = "CH341SER_A64"
 | 
			
		||||
ServiceType   = 1
 | 
			
		||||
StartType     = 3
 | 
			
		||||
ErrorControl  = 1
 | 
			
		||||
ServiceBinary = %10%\System32\Drivers\CH341S64.SYS
 | 
			
		||||
 | 
			
		||||
[CH341SER.ServiceI64]
 | 
			
		||||
DisplayName   = "CH341SER_I64"
 | 
			
		||||
ServiceType   = 1
 | 
			
		||||
StartType     = 3
 | 
			
		||||
ErrorControl  = 1
 | 
			
		||||
ServiceBinary = %10%\System32\Drivers\CH341I64.SYS
 | 
			
		||||
 | 
			
		||||
[Serenum_Service_Inst]
 | 
			
		||||
DisplayName    = "SerEnum"
 | 
			
		||||
ServiceType    = 1
 | 
			
		||||
StartType      = 3
 | 
			
		||||
ErrorControl   = 1
 | 
			
		||||
ServiceBinary  = %12%\serenum.sys
 | 
			
		||||
LoadOrderGroup = PNP Filter
 | 
			
		||||
 | 
			
		||||
[DestinationDirs]
 | 
			
		||||
DefaultDestDir      = 10, System32\Drivers
 | 
			
		||||
CH341S98.DelFiles.SYS = 11
 | 
			
		||||
CH341SER.CopyFiles.SYS = 10, System32\Drivers
 | 
			
		||||
CH341SER.NT.CopyFiles.SYS = 10, System32\Drivers
 | 
			
		||||
CH341S98.CopyFiles.VXD = 11
 | 
			
		||||
CH341SER.CopyFiles.DLL = 11
 | 
			
		||||
CH341SER.NT.CopyFiles.SYSA64 = 10, System32\Drivers
 | 
			
		||||
;CH341SER.NT.CopyFiles.SYSI64 = 10, System32\Drivers
 | 
			
		||||
 | 
			
		||||
[SourceDisksFiles]
 | 
			
		||||
CH341SER.SYS  = 1
 | 
			
		||||
CH341S98.SYS  = 1
 | 
			
		||||
CH341SER.VXD  = 1
 | 
			
		||||
CH341PT.DLL   = 1
 | 
			
		||||
CH341S64.SYS  = 1
 | 
			
		||||
;CH341I64.SYS  = 1
 | 
			
		||||
 | 
			
		||||
[SourceDisksNames]
 | 
			
		||||
1 = %DISK_NAME%, , ,
 | 
			
		||||
 | 
			
		||||
[SourceDisksNames.amd64]
 | 
			
		||||
1 = %DISK_NAME%, , ,
 | 
			
		||||
 | 
			
		||||
[SourceDisksNames.ia64]
 | 
			
		||||
1 = %DISK_NAME%, , ,
 | 
			
		||||
 | 
			
		||||
[Strings]
 | 
			
		||||
WinChipHead      = "wch.cn"
 | 
			
		||||
CH341SER.DeviceDesc = "USB-SERIAL CH341"
 | 
			
		||||
CH341S98.DeviceDesc = "USB-SERIAL CH341"
 | 
			
		||||
CH340SER.DeviceDesc = "USB-SERIAL CH340"
 | 
			
		||||
CH341ASER.DeviceDesc = "USB-SERIAL CH341A"
 | 
			
		||||
DISK_NAME = "CH341 Serial Installation Disk"
 | 
			
		||||
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							@@ -1,346 +0,0 @@
 | 
			
		||||
#include <ESP8266WiFi.h>
 | 
			
		||||
#include <WiFiClient.h>
 | 
			
		||||
#include <ESP8266WebServer.h>
 | 
			
		||||
#include <EEPROM.h>
 | 
			
		||||
#include <ESP8266HTTPClient.h>
 | 
			
		||||
#include <ArduinoJson.h>
 | 
			
		||||
#include "DHT.h"
 | 
			
		||||
 | 
			
		||||
String ssid = "";
 | 
			
		||||
String pasw = "";
 | 
			
		||||
String hwId = "";
 | 
			
		||||
String url = "";
 | 
			
		||||
 | 
			
		||||
//Pins
 | 
			
		||||
#define LIGHTPIN 13
 | 
			
		||||
#define DHTPIN 4
 | 
			
		||||
#define DHTTYPE DHT11
 | 
			
		||||
#define LED_BUILTIN 16
 | 
			
		||||
 | 
			
		||||
//Settings
 | 
			
		||||
bool deepSleepOn = true;
 | 
			
		||||
long sleepTime = 4;  //in minutes
 | 
			
		||||
bool lightSensor = true;
 | 
			
		||||
bool humiditySensor = true;
 | 
			
		||||
bool temperatureSensor = true;
 | 
			
		||||
 | 
			
		||||
ESP8266WebServer server(80); 
 | 
			
		||||
DHT dht(DHTPIN, DHTTYPE);
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
void setup() {
 | 
			
		||||
  Serial.begin(9600);
 | 
			
		||||
  Serial.setDebugOutput(true);
 | 
			
		||||
  EEPROM.begin(512);
 | 
			
		||||
  
 | 
			
		||||
  Serial.println("");  
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void loop() {
 | 
			
		||||
  restorSetting();
 | 
			
		||||
  if (!checkConnection()) {
 | 
			
		||||
    settingMode();
 | 
			
		||||
    while (true){ 
 | 
			
		||||
      Serial.println("CONECTION SETTING LOOP");
 | 
			
		||||
      server.handleClient();
 | 
			
		||||
    }
 | 
			
		||||
  } else {
 | 
			
		||||
    httpRequest();
 | 
			
		||||
    sleep();
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
//webpages
 | 
			
		||||
void handleRoot() {
 | 
			
		||||
  String s = "<!DOCTYPE html><html><head>";
 | 
			
		||||
  s += "<meta name=\"viewport\" content=\"width=device-width,user-scalable=0\">";
 | 
			
		||||
  s += "<title>";
 | 
			
		||||
  s += "Main";
 | 
			
		||||
  s += "</title>";
 | 
			
		||||
  s += "</head>";
 | 
			
		||||
  s += "<body>";
 | 
			
		||||
  s += "<a href=\"/restart\"><p>Restartovat</p><a/>";
 | 
			
		||||
  s += "<a href=\"/setting\"><p>Refrest WIFI Networks</p><a/>";
 | 
			
		||||
  s += "</body>";
 | 
			
		||||
  s += "</html>";
 | 
			
		||||
  server.send(200, "text/html", s);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void handleSetting() {
 | 
			
		||||
  String wifiList = "";
 | 
			
		||||
  int n = WiFi.scanNetworks();
 | 
			
		||||
  Serial.println("scan done");
 | 
			
		||||
  if (n == 0) {
 | 
			
		||||
    Serial.println("no networks found");
 | 
			
		||||
  } else {
 | 
			
		||||
    for (int i = 0; i < n; ++i) {
 | 
			
		||||
      //Serial.println("SSID: " + WiFi.SSID(i));
 | 
			
		||||
      wifiList = wifiList + String("<option value=\"");
 | 
			
		||||
      wifiList = wifiList + String(WiFi.SSID(i));
 | 
			
		||||
      wifiList = wifiList + String("\">");
 | 
			
		||||
      wifiList = wifiList + String(WiFi.SSID(i) + "(" + WiFi.RSSI() + ")");
 | 
			
		||||
      wifiList = wifiList + String("</option>");
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  String s = "<!DOCTYPE html><html><head>";
 | 
			
		||||
  s += "<meta name=\"viewport\" content=\"width=device-width,user-scalable=0\">";
 | 
			
		||||
  s += "<title>";
 | 
			
		||||
  s += "Main";
 | 
			
		||||
  s += "</title>";
 | 
			
		||||
  s += "</head>";
 | 
			
		||||
  s += "<body>";
 | 
			
		||||
  s += "<form method=\"get\" action=\"set\">";
 | 
			
		||||
  s += "<br>SSID: <select name=\"ssid\">";
 | 
			
		||||
  s += wifiList;
 | 
			
		||||
  s += "</select>";
 | 
			
		||||
  s += "<br>Password: <input name=\"pasw\" length=64 type=\"password\">";
 | 
			
		||||
  s += "<br>Token: <input name=\"token\" length=64 type=\"text\">";
 | 
			
		||||
  s += "<br>Api Url: <input name=\"url\" length=64 type=\"url\">";
 | 
			
		||||
  s += "<input type=\"submit\">";
 | 
			
		||||
  s += "</form>";
 | 
			
		||||
  s += "</body>";
 | 
			
		||||
  s += "</html>";
 | 
			
		||||
  server.send(200, "text/html", s);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//functions
 | 
			
		||||
bool restorSetting() {
 | 
			
		||||
  Serial.println("Reading EEPROM");
 | 
			
		||||
  ssid = "";
 | 
			
		||||
  pasw = "";
 | 
			
		||||
  hwId = "";
 | 
			
		||||
  url = "";
 | 
			
		||||
  if (EEPROM.read(0) != 0) {
 | 
			
		||||
    Serial.println("Reading EEPROM");
 | 
			
		||||
    for (int i = 0; i < 64; ++i) {
 | 
			
		||||
      ssid += char(EEPROM.read(i));
 | 
			
		||||
    }
 | 
			
		||||
    Serial.println("SSID: " + String(ssid));
 | 
			
		||||
    for (int i = 64; i < 128; ++i) {
 | 
			
		||||
      pasw += char(EEPROM.read(i));
 | 
			
		||||
    }
 | 
			
		||||
    Serial.println("PASS: " + String(pasw));
 | 
			
		||||
    for (int i = 128; i < 192; ++i) {
 | 
			
		||||
      hwId += char(EEPROM.read(i)); 
 | 
			
		||||
    }
 | 
			
		||||
    Serial.println("TOKEN: " + String(hwId));
 | 
			
		||||
    for (int i = 192; i < 256; ++i) {
 | 
			
		||||
      url += char(EEPROM.read(i));
 | 
			
		||||
    }
 | 
			
		||||
    Serial.println("URL: " + String(url));
 | 
			
		||||
    return true;
 | 
			
		||||
  } else {
 | 
			
		||||
    return false;
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
String urlDecode(String input) {
 | 
			
		||||
  String s = input;
 | 
			
		||||
  s.replace("%20", " ");
 | 
			
		||||
  s.replace("+", " ");
 | 
			
		||||
  s.replace("%21", "!");
 | 
			
		||||
  s.replace("%22", "\"");
 | 
			
		||||
  s.replace("%23", "#");
 | 
			
		||||
  s.replace("%24", "$");
 | 
			
		||||
  s.replace("%25", "%");
 | 
			
		||||
  s.replace("%26", "&");
 | 
			
		||||
  s.replace("%27", "\'");
 | 
			
		||||
  s.replace("%28", "(");
 | 
			
		||||
  s.replace("%29", ")");
 | 
			
		||||
  s.replace("%30", "*");
 | 
			
		||||
  s.replace("%31", "+");
 | 
			
		||||
  s.replace("%2C", ",");
 | 
			
		||||
  s.replace("%2E", ".");
 | 
			
		||||
  s.replace("%2F", "/");
 | 
			
		||||
  s.replace("%2C", ",");
 | 
			
		||||
  s.replace("%3A", ":");
 | 
			
		||||
  s.replace("%3A", ";");
 | 
			
		||||
  s.replace("%3C", "<");
 | 
			
		||||
  s.replace("%3D", "=");
 | 
			
		||||
  s.replace("%3E", ">");
 | 
			
		||||
  s.replace("%3F", "?");
 | 
			
		||||
  s.replace("%40", "@");
 | 
			
		||||
  s.replace("%5B", "[");
 | 
			
		||||
  s.replace("%5C", "\\");
 | 
			
		||||
  s.replace("%5D", "]");
 | 
			
		||||
  s.replace("%5E", "^");
 | 
			
		||||
  s.replace("%5F", "-");
 | 
			
		||||
  s.replace("%60", "`");
 | 
			
		||||
  return s;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
bool checkConnection() {
 | 
			
		||||
  int count = 0;
 | 
			
		||||
  WiFi.persistent(false);
 | 
			
		||||
  WiFi.mode(WIFI_STA);
 | 
			
		||||
  WiFi.forceSleepWake();
 | 
			
		||||
  WiFi.begin(ssid, pasw);
 | 
			
		||||
  Serial.print("Waiting for Wi-Fi connection");
 | 
			
		||||
  while ( count < 30 ) {
 | 
			
		||||
    if (WiFi.status() == WL_CONNECTED) {
 | 
			
		||||
      Serial.println();
 | 
			
		||||
      Serial.println("Connected!");
 | 
			
		||||
      return (true);
 | 
			
		||||
    }
 | 
			
		||||
    delay(500);
 | 
			
		||||
    Serial.print(".");
 | 
			
		||||
    count++;
 | 
			
		||||
  }
 | 
			
		||||
  Serial.println("Timed out.");
 | 
			
		||||
  return false;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void settingMode(){
 | 
			
		||||
  WiFi.mode(WIFI_AP);          
 | 
			
		||||
  WiFi.softAP("NodeMeter"); 
 | 
			
		||||
  
 | 
			
		||||
  IPAddress myIP = WiFi.softAPIP(); 
 | 
			
		||||
  Serial.print("HotSpt IP:");
 | 
			
		||||
  Serial.println(myIP);
 | 
			
		||||
  
 | 
			
		||||
  server.on("/", handleRoot); 
 | 
			
		||||
  server.on("/restart", []() {
 | 
			
		||||
    ESP.restart();
 | 
			
		||||
  });
 | 
			
		||||
  server.on("/setting", handleSetting);
 | 
			
		||||
  server.on("/set", []() {
 | 
			
		||||
    for (int i = 0; i < 96; ++i) {
 | 
			
		||||
      EEPROM.write(i, 'e');
 | 
			
		||||
    }
 | 
			
		||||
    EEPROM.commit();
 | 
			
		||||
    ssid = server.arg("ssid");
 | 
			
		||||
    pasw = server.arg("pasw");
 | 
			
		||||
    hwId = server.arg("token");
 | 
			
		||||
    url = server.arg("url");
 | 
			
		||||
    
 | 
			
		||||
    for (int i = 0; i < 256; ++i) {
 | 
			
		||||
      EEPROM.write(i, 0);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    Serial.println("Writing EEPROM...");
 | 
			
		||||
    Serial.println("SSID:" + ssid);
 | 
			
		||||
    for (int i = 0; i < ssid.length(); ++i) {
 | 
			
		||||
      EEPROM.write(i,ssid[i]);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    Serial.println("PASW:" + pasw);
 | 
			
		||||
    for (int i = 0; i < pasw.length(); ++i) {
 | 
			
		||||
      EEPROM.write(64 + i, pasw[i]);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    Serial.println("TOKEN:" + hwId);
 | 
			
		||||
    for (int i = 0; i < hwId.length(); ++i) {
 | 
			
		||||
      EEPROM.write(128 + i, hwId[i]);
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    Serial.println("URL:" + url);
 | 
			
		||||
    for (int i = 0; i < url.length(); ++i) {
 | 
			
		||||
      EEPROM.write(192 + i, url[i]);
 | 
			
		||||
    }
 | 
			
		||||
    EEPROM.commit();
 | 
			
		||||
    
 | 
			
		||||
    Serial.println("Write EEPROM done!");
 | 
			
		||||
    String s = "<h1>Setup complete.</h1><p>device will be connected to \"";
 | 
			
		||||
    s += ssid;
 | 
			
		||||
    s += "\" after the restart.";
 | 
			
		||||
    server.send(200, "text/html", s);
 | 
			
		||||
    ESP.restart();
 | 
			
		||||
  });
 | 
			
		||||
  
 | 
			
		||||
  server.begin();
 | 
			
		||||
  Serial.println("HTTP server started");
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
bool httpRequest(){
 | 
			
		||||
  StaticJsonDocument<1024> sendContent;
 | 
			
		||||
  sendContent["token"] = hwId;
 | 
			
		||||
  if (temperatureSensor){
 | 
			
		||||
    sendContent["values"]["temp"]["value"] = String(getTemperature());
 | 
			
		||||
    sendContent["values"]["temp"]["unit"] = "C";
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  if (humiditySensor){
 | 
			
		||||
    sendContent["values"]["humi"]["value"] = String(getHumidity());
 | 
			
		||||
    sendContent["values"]["humi"]["unit"] = "%";
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  if (lightSensor){
 | 
			
		||||
    sendContent["values"]["light"]["value"] = String(getLight());
 | 
			
		||||
    sendContent["values"]["light"]["unit"] = "";
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  String requestJson = "";
 | 
			
		||||
  serializeJson(sendContent, requestJson);
 | 
			
		||||
  Serial.println("JSON: " + requestJson);
 | 
			
		||||
  
 | 
			
		||||
  HTTPClient http;
 | 
			
		||||
  http.begin(String(url));
 | 
			
		||||
  http.addHeader("Content-Type", "application/json");  //Specify content-type header
 | 
			
		||||
  
 | 
			
		||||
  int httpCode = http.POST(requestJson);
 | 
			
		||||
  String payload = http.getString();  //Get the response payload
 | 
			
		||||
  http.end();
 | 
			
		||||
  
 | 
			
		||||
  DynamicJsonDocument doc(1024);
 | 
			
		||||
  deserializeJson(doc, payload);
 | 
			
		||||
  
 | 
			
		||||
  String hostname = doc["device"]["hostname"];
 | 
			
		||||
  sleepTime = doc["device"]["sleepTime"];
 | 
			
		||||
  WiFi.hostname(hostname);
 | 
			
		||||
  
 | 
			
		||||
  Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
 | 
			
		||||
  Serial.println("HTTP BODY: " + String(payload) + "");  //Print request response payload
 | 
			
		||||
  http.end();  //Close connection
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void sleep(){
 | 
			
		||||
  Serial.println("DISCONECTED FROM WIFI");
 | 
			
		||||
  WiFi.disconnect();
 | 
			
		||||
  
 | 
			
		||||
  if (deepSleepOn) {
 | 
			
		||||
    Serial.println("GOING TO SLEEP FOR " + String(sleepTime));
 | 
			
		||||
    ESP.deepSleep((sleepTime * 60) * 1000000, RF_DEFAULT);  // 20e6 is 20 microseconds
 | 
			
		||||
    delay(1000);
 | 
			
		||||
  } else {
 | 
			
		||||
    delay(1000);
 | 
			
		||||
    delay(sleepTime);
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//ReadTemperatures
 | 
			
		||||
float getTemperature() {
 | 
			
		||||
  float t = dht.readTemperature();
 | 
			
		||||
  //Serial.print(dht.readTemperature());
 | 
			
		||||
  //Serial.println(t);
 | 
			
		||||
  if (isnan(t)) {
 | 
			
		||||
    Serial.println( "Failed to read temperature from sensor!") ;
 | 
			
		||||
    return 999;
 | 
			
		||||
  }
 | 
			
		||||
  return t;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
float getHumidity() {
 | 
			
		||||
  float h = dht.readHumidity();
 | 
			
		||||
  //Serial.println(h);
 | 
			
		||||
  if (isnan(h)) {
 | 
			
		||||
    Serial.println("Failed to read humidity from sensor!");
 | 
			
		||||
    return 999;
 | 
			
		||||
  }
 | 
			
		||||
  return h;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
int getLight() {
 | 
			
		||||
  int l = analogRead(LIGHTPIN);
 | 
			
		||||
  if (l > 1000) {
 | 
			
		||||
    return 1;
 | 
			
		||||
  } else {
 | 
			
		||||
    return 0;
 | 
			
		||||
  }
 | 
			
		||||
  Serial.println("Failed to read light from sensor!");
 | 
			
		||||
  return 999;
 | 
			
		||||
}
 | 
			
		||||
@@ -1,92 +0,0 @@
 | 
			
		||||
//Includes
 | 
			
		||||
#include <ESP8266WiFi.h>
 | 
			
		||||
#include <ESP8266HTTPClient.h>
 | 
			
		||||
#include <ArduinoJson.h>
 | 
			
		||||
 | 
			
		||||
//Variables
 | 
			
		||||
const char* ssid = "";
 | 
			
		||||
const char* pasw = "";
 | 
			
		||||
const char* server = "http://ESP:ESP@dev.steelants.cz/projekty/rest_vasek/api/out.php";
 | 
			
		||||
const char* hwId = "";
 | 
			
		||||
int lastState = 0;
 | 
			
		||||
 | 
			
		||||
//Constant
 | 
			
		||||
#define SONOFF 12
 | 
			
		||||
#define SONOFF_LED 13
 | 
			
		||||
#define SONOFF_BUT 0
 | 
			
		||||
 | 
			
		||||
void setup() {
 | 
			
		||||
  Serial.begin(9600);
 | 
			
		||||
  Serial.println("HW: " + String(hwId));
 | 
			
		||||
  pinMode(SONOFF, OUTPUT);
 | 
			
		||||
  pinMode(SONOFF_LED, OUTPUT);
 | 
			
		||||
  pinMode(SONOFF_BUT, OUTPUT);
 | 
			
		||||
  pinMode(SONOFF_BUT, INPUT);
 | 
			
		||||
  // WI-FI CONECTING
 | 
			
		||||
  WiFi.persistent(false);
 | 
			
		||||
  WiFi.mode(WIFI_STA);
 | 
			
		||||
  WiFi.begin(ssid, pasw);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void loop() {
 | 
			
		||||
  if(WiFi.status() != WL_CONNECTED){
 | 
			
		||||
    WiFi.begin(ssid, pasw);
 | 
			
		||||
    while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
 | 
			
		||||
      digitalWrite(SONOFF_LED, LOW); // LOW will turn on the LED
 | 
			
		||||
      delay(1000);
 | 
			
		||||
      digitalWrite(SONOFF_LED, HIGH); // HIGH will turn off the LED
 | 
			
		||||
      delay(1000);
 | 
			
		||||
    }
 | 
			
		||||
    Serial.println("\nCONECTED TO WIFI");
 | 
			
		||||
    Serial.println("IP: " + String(WiFi.localIP()));
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  bool buttonState = digitalRead(SONOFF_BUT);
 | 
			
		||||
  HTTPClient http;
 | 
			
		||||
  http.begin(server);
 | 
			
		||||
  http.addHeader("Content-Type", "text/plain");  //Specify content-type header
 | 
			
		||||
  String requestJson = "{";
 | 
			
		||||
  requestJson += "\"tocken\":\"" + String(hwId) + "\"";
 | 
			
		||||
  
 | 
			
		||||
  if (buttonState == true) {
 | 
			
		||||
    requestJson += ",";
 | 
			
		||||
    requestJson += "\"on/off\":{";
 | 
			
		||||
    requestJson += "\"value\":\"" + String(~lastState) + "\",";
 | 
			
		||||
    requestJson += "\"unit\":\"\"";
 | 
			
		||||
    requestJson += "}";
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  while(buttonState == true) {
 | 
			
		||||
    delay(50); // keeps a small delay
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  requestJson += "}";
 | 
			
		||||
  Serial.println("JSON: " + requestJson);
 | 
			
		||||
  
 | 
			
		||||
  int httpCode = http.POST(requestJson);
 | 
			
		||||
  String payload = http.getString();  //Get the response payload
 | 
			
		||||
  
 | 
			
		||||
  Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
 | 
			
		||||
  Serial.println("HTTP BODY: " + String(payload) + "");  //Print request response payload
 | 
			
		||||
  
 | 
			
		||||
  DynamicJsonDocument doc(1024);
 | 
			
		||||
  deserializeJson(doc, payload);
 | 
			
		||||
  
 | 
			
		||||
  string hostname = doc["hostname"];
 | 
			
		||||
  WiFi.hostname(hostname);
 | 
			
		||||
  
 | 
			
		||||
  int state = doc["state"];
 | 
			
		||||
  
 | 
			
		||||
  if (state == 1 && lastState == 0) {
 | 
			
		||||
    Serial.println("ON");
 | 
			
		||||
    digitalWrite(SONOFF, HIGH);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
    digitalWrite(SONOFF_LED, LOW);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
  } else {
 | 
			
		||||
    Serial.println("OFF");
 | 
			
		||||
    digitalWrite(SONOFF, LOW);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
    digitalWrite(SONOFF_LED, HIGH);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  lastState = state;
 | 
			
		||||
  delay(1000);
 | 
			
		||||
}
 | 
			
		||||
@@ -1,94 +0,0 @@
 | 
			
		||||
//Includes
 | 
			
		||||
#include <ESP8266WiFi.h>
 | 
			
		||||
#include <ESP8266HTTPClient.h>
 | 
			
		||||
#include <ArduinoJson.h>
 | 
			
		||||
 | 
			
		||||
//Variables
 | 
			
		||||
const char* ssid = "";
 | 
			
		||||
const char* pasw = "";
 | 
			
		||||
const char* server = "http://ESP:ESP@dev.steelants.cz/projekty/rest_vasek/api/out.php";
 | 
			
		||||
const char* hwId = "";
 | 
			
		||||
int lastState = 0;
 | 
			
		||||
 | 
			
		||||
//Constant
 | 
			
		||||
#define SONOFF 12
 | 
			
		||||
#define SONOFF_LED 13
 | 
			
		||||
#define SONOFF_BUT 0
 | 
			
		||||
 | 
			
		||||
void setup() {
 | 
			
		||||
  Serial.begin(9600);
 | 
			
		||||
  Serial.println("HW: " + String(hwId));
 | 
			
		||||
  pinMode(SONOFF, OUTPUT);
 | 
			
		||||
  pinMode(SONOFF_LED, OUTPUT);
 | 
			
		||||
  pinMode(SONOFF_BUT, OUTPUT);
 | 
			
		||||
  pinMode(SONOFF_BUT, INPUT);
 | 
			
		||||
  // WI-FI CONECTING
 | 
			
		||||
  WiFi.persistent(false);
 | 
			
		||||
  WiFi.mode(WIFI_STA);
 | 
			
		||||
  WiFi.begin(ssid, pasw);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void loop() {
 | 
			
		||||
  if(WiFi.status() != WL_CONNECTED){
 | 
			
		||||
    WiFi.begin(ssid, pasw);
 | 
			
		||||
    while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
 | 
			
		||||
      digitalWrite(SONOFF_LED, LOW); // LOW will turn on the LED
 | 
			
		||||
      delay(1000);
 | 
			
		||||
      digitalWrite(SONOFF_LED, HIGH); // HIGH will turn off the LED
 | 
			
		||||
      delay(1000);
 | 
			
		||||
    }
 | 
			
		||||
    Serial.println("\nCONECTED TO WIFI");
 | 
			
		||||
    Serial.println("IP: " + String(WiFi.localIP()));
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  bool buttonState = digitalRead(SONOFF_BUT);
 | 
			
		||||
  HTTPClient http;
 | 
			
		||||
  http.begin(server);
 | 
			
		||||
  http.addHeader("Content-Type", "text/plain");  //Specify content-type header
 | 
			
		||||
  String requestJson = "{";
 | 
			
		||||
  requestJson += "\"tocken\":\"" + String(hwId) + "\"";
 | 
			
		||||
  
 | 
			
		||||
  if (buttonState == true) {
 | 
			
		||||
    requestJson += ",";
 | 
			
		||||
    requestJson += "\"on/off\":{";
 | 
			
		||||
    requestJson += "\"value\":\"" + String(~lastState) + "\",";
 | 
			
		||||
    requestJson += "\"unit\":\"\"";
 | 
			
		||||
    requestJson += "}";
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  while(buttonState == true) {
 | 
			
		||||
    delay(50); // keeps a small delay
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  requestJson += "}";
 | 
			
		||||
  Serial.println("JSON: " + requestJson);
 | 
			
		||||
  
 | 
			
		||||
  int httpCode = http.POST(requestJson);
 | 
			
		||||
  String payload = http.getString();  //Get the response payload
 | 
			
		||||
  
 | 
			
		||||
  Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
 | 
			
		||||
  Serial.println("HTTP BODY: " + String(payload) + "");  //Print request response payload
 | 
			
		||||
  
 | 
			
		||||
  DynamicJsonDocument doc(1024);
 | 
			
		||||
  deserializeJson(doc, payload);
 | 
			
		||||
  
 | 
			
		||||
  string hostname = doc["device"]["hostname"];
 | 
			
		||||
  sleepTime = doc["device"]["sleepTime"];
 | 
			
		||||
  
 | 
			
		||||
  WiFi.hostname(hostname);
 | 
			
		||||
  
 | 
			
		||||
  int state = doc["state"];
 | 
			
		||||
  
 | 
			
		||||
  if (state == 1 && lastState == 0) {
 | 
			
		||||
    Serial.println("ON");
 | 
			
		||||
    digitalWrite(SONOFF, HIGH);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
    digitalWrite(SONOFF_LED, LOW);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
  } else {
 | 
			
		||||
    Serial.println("OFF");
 | 
			
		||||
    digitalWrite(SONOFF, LOW);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
    digitalWrite(SONOFF_LED, HIGH);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
  }
 | 
			
		||||
  
 | 
			
		||||
  lastState = state;
 | 
			
		||||
  delay(1000);
 | 
			
		||||
}
 | 
			
		||||
@@ -1,94 +0,0 @@
 | 
			
		||||
//Includes
 | 
			
		||||
#include <ESP8266WiFi.h>
 | 
			
		||||
#include <ESP8266HTTPClient.h>
 | 
			
		||||
#include <ArduinoJson.h>
 | 
			
		||||
 | 
			
		||||
//Variables
 | 
			
		||||
const char* ssid = " ";
 | 
			
		||||
const char* pasw = "";
 | 
			
		||||
const char* server = "http://dev.steelants.cz/vasek/home/api.php";
 | 
			
		||||
const char* hwId = "";
 | 
			
		||||
int lastState = 0;
 | 
			
		||||
int reconectAtemptsMax = 10; //time to wait before restart
 | 
			
		||||
 | 
			
		||||
//Constant
 | 
			
		||||
#define SONOFF 12
 | 
			
		||||
#define SONOFF_LED 13
 | 
			
		||||
#define SONOFF_BUT 0
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
void setup() {
 | 
			
		||||
    Serial.begin(9600);
 | 
			
		||||
    delay(10);
 | 
			
		||||
    Serial.println('\n');
 | 
			
		||||
    Serial.println("HW: " + String(hwId));
 | 
			
		||||
    
 | 
			
		||||
    pinMode(SONOFF, OUTPUT);
 | 
			
		||||
    pinMode(SONOFF_LED, OUTPUT);
 | 
			
		||||
    pinMode(SONOFF_BUT, INPUT);
 | 
			
		||||
    
 | 
			
		||||
    WiFi.persistent(false);
 | 
			
		||||
    WiFi.mode(WIFI_STA);
 | 
			
		||||
    
 | 
			
		||||
    WiFi.begin(ssid, pasw);
 | 
			
		||||
    Serial.print("Connecting to ");
 | 
			
		||||
    Serial.print(ssid); Serial.println(" ...");
 | 
			
		||||
    
 | 
			
		||||
    int i = 0;
 | 
			
		||||
    while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
 | 
			
		||||
        delay(1000);
 | 
			
		||||
        Serial.print(++i); Serial.print(' ');
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    Serial.println('\n');
 | 
			
		||||
    Serial.println("Connection established!");  
 | 
			
		||||
    Serial.print("IP address:\t");
 | 
			
		||||
    Serial.println(WiFi.localIP());   
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
void loop() {
 | 
			
		||||
    StaticJsonDocument<200> jsonContent;
 | 
			
		||||
    jsonContent["token"] = hwId;
 | 
			
		||||
    
 | 
			
		||||
    if (!digitalRead(SONOFF_BUT)){
 | 
			
		||||
        jsonContent["values"]["on/off"]["value"] = (int) !lastState;
 | 
			
		||||
        if (!lastState == 1) {
 | 
			
		||||
            digitalWrite(SONOFF, HIGH)
 | 
			
		||||
        } else if (!lastState == 0){
 | 
			
		||||
            digitalWrite(SONOFF, LOW)
 | 
			
		||||
        }
 | 
			
		||||
        while(!digitalRead(SONOFF_BUT)) {
 | 
			
		||||
            delay(100);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    String requestJson = "";
 | 
			
		||||
    serializeJson(jsonContent, requestJson);
 | 
			
		||||
    Serial.println("JSON: " + requestJson);
 | 
			
		||||
    
 | 
			
		||||
    HTTPClient http;
 | 
			
		||||
    http.begin(server);
 | 
			
		||||
    http.addHeader("Content-Type", "text/plain");  //Specify content-type header
 | 
			
		||||
    int httpCode = http.POST(requestJson);
 | 
			
		||||
    String payload = http.getString();  //Get the response payload
 | 
			
		||||
    http.end();
 | 
			
		||||
    
 | 
			
		||||
    Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
 | 
			
		||||
    Serial.println("HTTP BODY: " + String(payload) + "");  //Print request response payload
 | 
			
		||||
    
 | 
			
		||||
    deserializeJson(jsonContent, payload);
 | 
			
		||||
    String hostname = jsonContent["device"]["hostname"];
 | 
			
		||||
    int state = jsonContent["value"];
 | 
			
		||||
    WiFi.hostname(hostname);
 | 
			
		||||
    
 | 
			
		||||
    if (state !=  lastState){
 | 
			
		||||
        if (state == 1 && lastState == 0) {
 | 
			
		||||
            Serial.println("ON");
 | 
			
		||||
            digitalWrite(SONOFF, HIGH);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
        } else {
 | 
			
		||||
            Serial.println("OFF");
 | 
			
		||||
            digitalWrite(SONOFF, LOW);   // Turn the LED on by making the voltage LOW
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    lastState = state;
 | 
			
		||||
}
 | 
			
		||||
										
											Binary file not shown.
										
									
								
							@@ -1,298 +0,0 @@
 | 
			
		||||
-- phpMyAdmin SQL Dump
 | 
			
		||||
-- version 4.6.6deb4
 | 
			
		||||
-- https://www.phpmyadmin.net/
 | 
			
		||||
--
 | 
			
		||||
-- Počítač: localhost:3306
 | 
			
		||||
-- Vytvořeno: Úte 08. říj 2019, 18:05
 | 
			
		||||
-- Verze serveru: 10.1.41-MariaDB-0+deb9u1
 | 
			
		||||
-- Verze PHP: 7.0.33-0+deb9u5
 | 
			
		||||
 | 
			
		||||
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
 | 
			
		||||
SET time_zone = "+00:00";
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
 | 
			
		||||
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
 | 
			
		||||
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
 | 
			
		||||
/*!40101 SET NAMES utf8mb4 */;
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Databáze: `smart-home`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `automation`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `automation` (
 | 
			
		||||
  `automation_id` int(11) NOT NULL,
 | 
			
		||||
  `name` varchar(255) NOT NULL,
 | 
			
		||||
  `on_days` varchar(255) NOT NULL,
 | 
			
		||||
  `if_something` varchar(255) NOT NULL,
 | 
			
		||||
  `do_something` varchar(255) NOT NULL,
 | 
			
		||||
  `executed` tinyint(4) NOT NULL,
 | 
			
		||||
  `active` tinyint(4) NOT NULL DEFAULT '1',
 | 
			
		||||
  `locked` tinyint(4) DEFAULT '0'
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `dashboard`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `dashboard` (
 | 
			
		||||
  `dashboard_id` int(11) NOT NULL,
 | 
			
		||||
  `user_id` int(11) NOT NULL,
 | 
			
		||||
  `subdevice_id` int(11) NOT NULL
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `devices`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `devices` (
 | 
			
		||||
  `device_id` int(11) NOT NULL,
 | 
			
		||||
  `room_id` int(11) DEFAULT NULL,
 | 
			
		||||
  `name` varchar(255) NOT NULL,
 | 
			
		||||
  `token` varchar(255) NOT NULL,
 | 
			
		||||
  `sleep_time` int(13) NOT NULL,
 | 
			
		||||
  `owner` int(13) NOT NULL,
 | 
			
		||||
  `permission` varchar(255) NOT NULL,
 | 
			
		||||
  `approved` int(11) NOT NULL,
 | 
			
		||||
  `icon` varchar(255) NOT NULL
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `notifications`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `notifications` (
 | 
			
		||||
  `id` int(13) NOT NULL,
 | 
			
		||||
  `user_id` varchar(255) NOT NULL,
 | 
			
		||||
  `token` varchar(255) NOT NULL
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `records`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `records` (
 | 
			
		||||
  `record_id` int(11) NOT NULL,
 | 
			
		||||
  `subdevice_id` int(11) NOT NULL,
 | 
			
		||||
  `value` smallint(6) NOT NULL,
 | 
			
		||||
  `time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 | 
			
		||||
  `execuded` tinyint(4) NOT NULL DEFAULT '0'
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `rooms`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `rooms` (
 | 
			
		||||
  `room_id` int(11) NOT NULL,
 | 
			
		||||
  `name` varchar(255) NOT NULL
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `scenes`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `scenes` (
 | 
			
		||||
  `scene_id` int(11) NOT NULL,
 | 
			
		||||
  `icon` varchar(255) NOT NULL,
 | 
			
		||||
  `name` varchar(255) NOT NULL,
 | 
			
		||||
  `do_something` varchar(255) NOT NULL
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `subdevices`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `subdevices` (
 | 
			
		||||
  `subdevice_id` int(11) NOT NULL,
 | 
			
		||||
  `device_id` int(11) NOT NULL,
 | 
			
		||||
  `type` varchar(255) NOT NULL,
 | 
			
		||||
  `unit` varchar(255) NOT NULL
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
-- --------------------------------------------------------
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Struktura tabulky `users`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
CREATE TABLE `users` (
 | 
			
		||||
  `user_id` int(11) NOT NULL,
 | 
			
		||||
  `username` varchar(255) NOT NULL,
 | 
			
		||||
  `password` varchar(255) NOT NULL,
 | 
			
		||||
  `startPage` int(11) NOT NULL,
 | 
			
		||||
  `at_home` varchar(255) NOT NULL DEFAULT 'false'
 | 
			
		||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Vypisuji data pro tabulku `users`
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
INSERT INTO `users` (`user_id`, `username`, `password`, `startPage`) VALUES
 | 
			
		||||
(2, 'Admin', '08abb3ff83dfae60fb4591125fc49dc80cf7ef28224c2d5df86e2d0d037c553bc7f30e859348fd745c9c07a4edde4863e866a7d45356cf08a22e5e1eafa13406', 1);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro exportované tabulky
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `automation`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `automation`
 | 
			
		||||
  ADD PRIMARY KEY (`automation_id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `dashboard`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `dashboard`
 | 
			
		||||
  ADD PRIMARY KEY (`dashboard_id`),
 | 
			
		||||
  ADD KEY `user_id` (`user_id`),
 | 
			
		||||
  ADD KEY `subdevice_id` (`subdevice_id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `devices`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `devices`
 | 
			
		||||
  ADD PRIMARY KEY (`device_id`),
 | 
			
		||||
  ADD KEY `room_id` (`room_id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `notifications`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `notifications`
 | 
			
		||||
  ADD PRIMARY KEY (`id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `records`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `records`
 | 
			
		||||
  ADD PRIMARY KEY (`record_id`),
 | 
			
		||||
  ADD KEY `device_id` (`subdevice_id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `rooms`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `rooms`
 | 
			
		||||
  ADD PRIMARY KEY (`room_id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `scenes`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `scenes`
 | 
			
		||||
  ADD PRIMARY KEY (`scene_id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `subdevices`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `subdevices`
 | 
			
		||||
  ADD PRIMARY KEY (`subdevice_id`),
 | 
			
		||||
  ADD KEY `device_id` (`device_id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Klíče pro tabulku `users`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `users`
 | 
			
		||||
  ADD PRIMARY KEY (`user_id`);
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulky
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `automation`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `automation`
 | 
			
		||||
  MODIFY `automation_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=58;
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `dashboard`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `dashboard`
 | 
			
		||||
  MODIFY `dashboard_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `devices`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `devices`
 | 
			
		||||
  MODIFY `device_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `notifications`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `notifications`
 | 
			
		||||
  MODIFY `id` int(13) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `records`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `records`
 | 
			
		||||
  MODIFY `record_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=352338;
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `rooms`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `rooms`
 | 
			
		||||
  MODIFY `room_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `scenes`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `scenes`
 | 
			
		||||
  MODIFY `scene_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20;
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `subdevices`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `subdevices`
 | 
			
		||||
  MODIFY `subdevice_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
 | 
			
		||||
--
 | 
			
		||||
-- AUTO_INCREMENT pro tabulku `users`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `users`
 | 
			
		||||
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
 | 
			
		||||
--
 | 
			
		||||
-- Omezení pro exportované tabulky
 | 
			
		||||
--
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Omezení pro tabulku `dashboard`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `dashboard`
 | 
			
		||||
  ADD CONSTRAINT `dashboard_ibfk_2` FOREIGN KEY (`subdevice_id`) REFERENCES `subdevices` (`subdevice_id`) ON DELETE CASCADE ON UPDATE NO ACTION,
 | 
			
		||||
  ADD CONSTRAINT `dashboard_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Omezení pro tabulku `devices`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `devices`
 | 
			
		||||
  ADD CONSTRAINT `devices_ibfk_1` FOREIGN KEY (`room_id`) REFERENCES `rooms` (`room_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Omezení pro tabulku `records`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `records`
 | 
			
		||||
  ADD CONSTRAINT `records_ibfk_1` FOREIGN KEY (`subdevice_id`) REFERENCES `subdevices` (`subdevice_id`) ON DELETE CASCADE ON UPDATE CASCADE;
 | 
			
		||||
 | 
			
		||||
--
 | 
			
		||||
-- Omezení pro tabulku `subdevices`
 | 
			
		||||
--
 | 
			
		||||
ALTER TABLE `subdevices`
 | 
			
		||||
  ADD CONSTRAINT `subdevices_ibfk_1` FOREIGN KEY (`device_id`) REFERENCES `devices` (`device_id`);
 | 
			
		||||
 | 
			
		||||
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
 | 
			
		||||
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
 | 
			
		||||
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
 | 
			
		||||
										
											Binary file not shown.
										
									
								
							| 
		 Before Width: | Height: | Size: 77 KiB  | 
										
											Binary file not shown.
										
									
								
							| 
		 Before Width: | Height: | Size: 66 KiB  | 
										
											Binary file not shown.
										
									
								
							| 
		 Before Width: | Height: | Size: 45 KiB  | 
										
											Binary file not shown.
										
									
								
							| 
		 Before Width: | Height: | Size: 108 KiB  | 
										
											Binary file not shown.
										
									
								
							| 
		 Before Width: | Height: | Size: 76 KiB  | 
										
											Binary file not shown.
										
									
								
							| 
		 Before Width: | Height: | Size: 58 KiB  | 
							
								
								
									
										2044
									
								
								adminer.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2044
									
								
								adminer.php
									
									
									
									
									
										Normal file
									
								
							
										
											
												File diff suppressed because one or more lines are too long
											
										
									
								
							
							
								
								
									
										234
									
								
								api.php
									
									
									
									
									
								
							
							
						
						
									
										234
									
								
								api.php
									
									
									
									
									
								
							@@ -1,234 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
/** Includes **/
 | 
			
		||||
include_once('./config.php');
 | 
			
		||||
 | 
			
		||||
//Autoloader
 | 
			
		||||
$files = scandir('./app/class/');
 | 
			
		||||
$files = array_diff($files, array(
 | 
			
		||||
	'.',
 | 
			
		||||
	'..',
 | 
			
		||||
	'app',
 | 
			
		||||
	'ChartJS.php',
 | 
			
		||||
	'ChartJS_Line.php',
 | 
			
		||||
	'ChartManager.php',
 | 
			
		||||
	'DashboardManager.php',
 | 
			
		||||
	'Partial.php',
 | 
			
		||||
	'Form.php',
 | 
			
		||||
	'Route.php',
 | 
			
		||||
	'Template.php',
 | 
			
		||||
	'Ajax.php',
 | 
			
		||||
));
 | 
			
		||||
 | 
			
		||||
foreach($files as $file) {
 | 
			
		||||
	include './app/class/'.  $file;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//Allow acces only wia Curl, Ajax ETC
 | 
			
		||||
$restAcess = 'XMLHttpRequest' == ( $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '' );
 | 
			
		||||
if (!$restAcess){
 | 
			
		||||
	header('Location: ./');
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//Log
 | 
			
		||||
$logManager = new LogManager();
 | 
			
		||||
 | 
			
		||||
//DB Conector
 | 
			
		||||
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
 | 
			
		||||
 | 
			
		||||
//Read API data
 | 
			
		||||
$json = file_get_contents('php://input');
 | 
			
		||||
$obj = json_decode($json, true);
 | 
			
		||||
 | 
			
		||||
//zabespecit proti Ddosu
 | 
			
		||||
if (isset($obj['user']) && $obj['user'] != ''){
 | 
			
		||||
	//user at home
 | 
			
		||||
	$user = UserManager::getUser($obj['user']);
 | 
			
		||||
	if (!empty($user)) {
 | 
			
		||||
		$userId = $user['user_id'];
 | 
			
		||||
		$atHome = $obj['atHome'];
 | 
			
		||||
		UserManager::atHome($userId, $atHome);
 | 
			
		||||
		$logManager->write("[Record] user " . $userId . "changet his home state to " . $atHome . RECORDTIMOUT , LogRecordType::WARNING);
 | 
			
		||||
		echo 'Saved: ' . $atHome;
 | 
			
		||||
		header("HTTP/1.1 200 OK");
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//Filtrování IP adress
 | 
			
		||||
if (DEBUGMOD != 1) {
 | 
			
		||||
	if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) {
 | 
			
		||||
		echo json_encode(array(
 | 
			
		||||
			'state' => 'unsuccess',
 | 
			
		||||
			'errorMSG' => "Using API from your IP insnt alowed!",
 | 
			
		||||
		));
 | 
			
		||||
		header("HTTP/1.1 401 Unauthorized");
 | 
			
		||||
		$logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING);
 | 
			
		||||
		exit();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//automationExecution
 | 
			
		||||
try {
 | 
			
		||||
	AutomationManager::executeAll();
 | 
			
		||||
} catch (\Exception $e) {
 | 
			
		||||
	$logManager->write("[Automation] Something happen during automation execution", LogRecordType::ERROR);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//Record Cleaning
 | 
			
		||||
try {
 | 
			
		||||
	RecordManager::clean(RECORDTIMOUT);
 | 
			
		||||
} catch (\Exception $e) {
 | 
			
		||||
	$logManager->write("[Record] cleaning record older that " . RECORDTIMOUT , LogRecordType::ERROR);
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
//Variables
 | 
			
		||||
$token = $obj['token'];
 | 
			
		||||
$values = null;
 | 
			
		||||
 | 
			
		||||
if (isset($obj['values'])) {
 | 
			
		||||
	$values = $obj['values'];
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//Checks
 | 
			
		||||
if ($token == null || $token == "") {
 | 
			
		||||
	echo json_encode(array(
 | 
			
		||||
		'state' => 'unsuccess',
 | 
			
		||||
		'errorMSG' => "Missing Value Token in JSON payload",
 | 
			
		||||
	));
 | 
			
		||||
	header("HTTP/1.1 401 Unauthorized");
 | 
			
		||||
	die();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//Vstupní Checky
 | 
			
		||||
if (!DeviceManager::registeret($token)) {
 | 
			
		||||
	$notificationData = [
 | 
			
		||||
		'title' => 'Info',
 | 
			
		||||
		'body' => 'New device Detected',
 | 
			
		||||
		'icon' => '',
 | 
			
		||||
	];
 | 
			
		||||
	$deviceId = DeviceManager::create($token, $token);
 | 
			
		||||
	foreach ($values as $key => $value) {
 | 
			
		||||
		if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
 | 
			
		||||
			SubDeviceManager::create($deviceId, $key, UNITS[$key]);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	//Notification for newly added Device
 | 
			
		||||
	$subscribers = $notificationMng::getSubscription();
 | 
			
		||||
	foreach ($subscribers as $key => $subscriber) {
 | 
			
		||||
		$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ");
 | 
			
		||||
		$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	header("HTTP/1.1 401 Unauthorized");
 | 
			
		||||
	echo json_encode(array(
 | 
			
		||||
		'state' => 'unsuccess',
 | 
			
		||||
		'errorMSG' => "Device not registeret",
 | 
			
		||||
	));
 | 
			
		||||
	$logManager->write("[API] Registering Device", LogRecordType::INFO);
 | 
			
		||||
	exit();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
if (!DeviceManager::approved($token)) {
 | 
			
		||||
	header("HTTP/1.1 401 Unauthorized");
 | 
			
		||||
	echo json_encode(array(
 | 
			
		||||
		'state' => 'unsuccess',
 | 
			
		||||
		'errorMSG' => "Unaproved Device",
 | 
			
		||||
	));
 | 
			
		||||
	exit();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Subdevices first data!
 | 
			
		||||
if ($values != null || $values != "") {
 | 
			
		||||
 | 
			
		||||
	//ZAPIS
 | 
			
		||||
	$device = DeviceManager::getDeviceByToken($token);
 | 
			
		||||
	$deviceId = $device['device_id'];
 | 
			
		||||
	foreach ($values as $key => $value) {
 | 
			
		||||
		if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
 | 
			
		||||
			SubDeviceManager::create($deviceId, $key, UNITS[$key]);
 | 
			
		||||
		}
 | 
			
		||||
		RecordManager::create($deviceId, $key, round($value['value'],2));
 | 
			
		||||
		$logManager->write("[API] Device_ID " . $deviceId . " writed value " . $key . ' ' . $value['value'], LogRecordType::INFO);
 | 
			
		||||
 | 
			
		||||
		//notification
 | 
			
		||||
		if ($key == 'door' || $key == 'water') {
 | 
			
		||||
			$notificationMng = new NotificationManager;
 | 
			
		||||
			$notificationData = [];
 | 
			
		||||
 | 
			
		||||
			switch ($key) {
 | 
			
		||||
				case 'door':
 | 
			
		||||
				$notificationData = [
 | 
			
		||||
					'title' => 'Info',
 | 
			
		||||
					'body' => 'Someone just open up '.$device['name'],
 | 
			
		||||
					'icon' => '',
 | 
			
		||||
				];
 | 
			
		||||
				break;
 | 
			
		||||
				case 'water':
 | 
			
		||||
				$notificationData = [
 | 
			
		||||
					'title' => 'Alert',
 | 
			
		||||
					'body' => 'Wather leak detected by '.$device['name'],
 | 
			
		||||
					'icon' => '',
 | 
			
		||||
				];
 | 
			
		||||
				break;
 | 
			
		||||
			}
 | 
			
		||||
			if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value'];
 | 
			
		||||
			if ($notificationData != []) {
 | 
			
		||||
				$subscribers = $notificationMng::getSubscription();
 | 
			
		||||
				foreach ($subscribers as $key => $subscriber) {
 | 
			
		||||
					$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ");
 | 
			
		||||
					$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	$hostname = strtolower($device['name']);
 | 
			
		||||
	$hostname = str_replace(' ', '_', $hostname);
 | 
			
		||||
	$jsonAnswer = [
 | 
			
		||||
		'device' => [
 | 
			
		||||
			'hostname' => $hostname,
 | 
			
		||||
		],
 | 
			
		||||
		'state' => 'succes',
 | 
			
		||||
	];
 | 
			
		||||
 | 
			
		||||
	$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId);
 | 
			
		||||
	if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) {
 | 
			
		||||
		$jsonAnswer['sleepTime'] = $device['sleep_time'];
 | 
			
		||||
	}
 | 
			
		||||
	echo json_encode($jsonAnswer);
 | 
			
		||||
	header("HTTP/1.1 200 OK");
 | 
			
		||||
} else {
 | 
			
		||||
	//Vypis
 | 
			
		||||
	//TODO: doděla uložení výpisu jinými slovy zda li byl comman vykonán
 | 
			
		||||
	$device = DeviceManager::getDeviceByToken($token);
 | 
			
		||||
	$deviceId = $device['device_id'];
 | 
			
		||||
 | 
			
		||||
	if (count(SubDeviceManager::getAllSubDevices($deviceId)) == 0) {
 | 
			
		||||
		SubDeviceManager::create($deviceId, 'on/off', UNITS[$key]);
 | 
			
		||||
		//RecordManager::create($deviceId, 'on/off', 0);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	$subDeviceId = SubDeviceManager::getAllSubDevices($deviceId)[0]['subdevice_id'];
 | 
			
		||||
	$subDeviceLastReord = RecordManager::getLastRecord($subDeviceId);
 | 
			
		||||
	$subDeviceLastReordValue = $subDeviceLastReord['value'];
 | 
			
		||||
 | 
			
		||||
	if ($subDeviceLastReord['execuded'] == 0){
 | 
			
		||||
		$logManager->write("[API] subDevice id ".$subDeviceId . " executed comand with value " .$subDeviceLastReordValue . " record id " . $subDeviceLastReord['record_id'] . " executed " . $subDeviceLastReord['execuded']);
 | 
			
		||||
		RecordManager::setExecuted($subDeviceLastReord['record_id']);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	echo json_encode(array(
 | 
			
		||||
		'device' => [
 | 
			
		||||
			'hostname' => $device['name'],
 | 
			
		||||
			'sleepTime' => $device['sleep_time'],
 | 
			
		||||
			],
 | 
			
		||||
			'state' => 'succes',
 | 
			
		||||
			'value' => $subDeviceLastReordValue
 | 
			
		||||
		));
 | 
			
		||||
		header("HTTP/1.1 200 OK");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	unset($logManager);
 | 
			
		||||
	Db::disconect();
 | 
			
		||||
	die();
 | 
			
		||||
							
								
								
									
										119
									
								
								app/Bootstrap.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										119
									
								
								app/Bootstrap.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,119 @@
 | 
			
		||||
<?php
 | 
			
		||||
//Debug
 | 
			
		||||
error_reporting(E_ALL);
 | 
			
		||||
ini_set( 'display_errors','1');
 | 
			
		||||
 | 
			
		||||
//setup
 | 
			
		||||
parse_str($_SERVER['QUERY_STRING'], $params);
 | 
			
		||||
if (defined ("BASEDIR")) {
 | 
			
		||||
	$urlSes = BASEDIR;
 | 
			
		||||
} else {
 | 
			
		||||
	$urlSes = str_replace((!empty ($params['url']) ? $params['url'] : ""), "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI']));
 | 
			
		||||
}
 | 
			
		||||
if (defined ("BASEDIR") && defined ("BASEURL")) {
 | 
			
		||||
	$domain = str_replace("http://", "", str_replace("https://", "", str_replace(BASEDIR, "", BASEURL)));
 | 
			
		||||
} else {
 | 
			
		||||
	$domain = str_replace("/var/www/", "", $_SERVER['DOCUMENT_ROOT']);
 | 
			
		||||
}
 | 
			
		||||
session_set_cookie_params(
 | 
			
		||||
    1209600,
 | 
			
		||||
    $urlSes,
 | 
			
		||||
    $domain,
 | 
			
		||||
    true,
 | 
			
		||||
    true
 | 
			
		||||
);
 | 
			
		||||
/*ini_set ('session.cookie_httponly', '1');
 | 
			
		||||
ini_set('session.cookie_domain', $_SERVER['HTTP_HOST']);
 | 
			
		||||
ini_set('session.cookie_path', str_replace('login', "", str_replace('https://' . $_SERVER['HTTP_HOST'], "", $_SERVER['REQUEST_URI'])));
 | 
			
		||||
ini_set('session.cookie_secure', '1');
 | 
			
		||||
ini_set('session.gc_maxlifetime', 1209600);*/
 | 
			
		||||
mb_internal_encoding ("UTF-8");
 | 
			
		||||
 | 
			
		||||
session_start();
 | 
			
		||||
 | 
			
		||||
// import configs
 | 
			
		||||
require_once '../library/Debugger.php';
 | 
			
		||||
 | 
			
		||||
Debugger::flag('loaders');
 | 
			
		||||
 | 
			
		||||
//Autoloader
 | 
			
		||||
class Autoloader {
 | 
			
		||||
	protected static $extension = ".php";
 | 
			
		||||
	protected static $root = __DIR__;
 | 
			
		||||
	protected static $files = [];
 | 
			
		||||
 | 
			
		||||
	static function ClassLoader ($className = ""){
 | 
			
		||||
		$directorys = new RecursiveDirectoryIterator(static::$root, RecursiveDirectoryIterator::SKIP_DOTS);
 | 
			
		||||
 | 
			
		||||
		//echo '<pre>';
 | 
			
		||||
		//var_dump($directorys);
 | 
			
		||||
		//echo '</pre>';
 | 
			
		||||
 | 
			
		||||
		$files = new RecursiveIteratorIterator($directorys, RecursiveIteratorIterator::LEAVES_ONLY);
 | 
			
		||||
 | 
			
		||||
		$filename = $className . static::$extension;
 | 
			
		||||
 | 
			
		||||
		foreach ($files as $key => $file) {
 | 
			
		||||
			if (strtolower($file->getFilename()) === strtolower($filename) && $file->isReadable()) {
 | 
			
		||||
				include_once $file->getPathname();
 | 
			
		||||
				return;
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function setRoot($rootPath){
 | 
			
		||||
		static::$root = $rootPath;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
spl_autoload_register("Autoloader::ClassLoader");
 | 
			
		||||
Autoloader::setRoot('/var/www/dev.steelants.cz/vasek/home-update/');
 | 
			
		||||
 | 
			
		||||
// import configs
 | 
			
		||||
require_once '../config/config.php';
 | 
			
		||||
 | 
			
		||||
class ErrorHandler {
 | 
			
		||||
	static function exception($exception){
 | 
			
		||||
		error_log($exception);
 | 
			
		||||
		http_response_code($exception->getCode());
 | 
			
		||||
		$message = [
 | 
			
		||||
			'code' => $exception->getCode(),
 | 
			
		||||
			'message' => $exception->getMessage(),
 | 
			
		||||
			'file' => $exception->getFile(),
 | 
			
		||||
			'line' => $exception->getLine(),
 | 
			
		||||
			'trace' => $exception->getTrace(),
 | 
			
		||||
		];
 | 
			
		||||
		echo json_encode($message);
 | 
			
		||||
 | 
			
		||||
		$apiLogManager = new LogManager('../logs/apache/'. date("Y-m-d").'.log');
 | 
			
		||||
		$apiLogManager->setLevel(LOGLEVEL);
 | 
			
		||||
		$apiLogManager->write("[APACHE]\n" . json_encode($message, JSON_PRETTY_PRINT), LogRecordTypes::ERROR);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
set_exception_handler("ErrorHandler::exception");
 | 
			
		||||
 | 
			
		||||
Debugger::flag('preload');
 | 
			
		||||
 | 
			
		||||
$json = file_get_contents('php://input');
 | 
			
		||||
$obj = json_decode($json, true);
 | 
			
		||||
 | 
			
		||||
$apiLogManager = new LogManager('../logs/api/'. date("Y-m-d").'.log');
 | 
			
		||||
$apiLogManager->setLevel(LOGLEVEL);
 | 
			
		||||
 | 
			
		||||
$apiLogManager->write("[API] headers\n" . json_encode($_SERVER, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
$apiLogManager->write("[API] POST  body\n" . json_encode($_POST, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
$apiLogManager->write("[API] GET body\n" . json_encode($_GET, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
Debugger::flag('dbconnect');
 | 
			
		||||
//D B Conector
 | 
			
		||||
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
 | 
			
		||||
 | 
			
		||||
Debugger::flag('routes');
 | 
			
		||||
// import routes
 | 
			
		||||
require_once '../app/Routes.php';
 | 
			
		||||
 | 
			
		||||
Debugger::flag('done');
 | 
			
		||||
// echo Debugger::showFlags(false);
 | 
			
		||||
							
								
								
									
										83
									
								
								app/Routes.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										83
									
								
								app/Routes.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,83 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
$router = new Router();
 | 
			
		||||
 | 
			
		||||
$router->setDefault(function(){
 | 
			
		||||
	echo $_GET['url'].': 404';
 | 
			
		||||
	$logManager = new LogManager();
 | 
			
		||||
	$logManager->setLevel(LOGLEVEL);
 | 
			
		||||
	$logManager->write("[ROUTER]" . $_GET['url'] . "not found", LogRecordTypes::WARNING);
 | 
			
		||||
	unset($logManager);
 | 
			
		||||
});
 | 
			
		||||
 | 
			
		||||
//Pages
 | 
			
		||||
$router->any('/', 'Log');
 | 
			
		||||
$router->any('/log', 'Log');
 | 
			
		||||
$router->any('/server', 'Server');
 | 
			
		||||
$router->any('/login', 'Login');
 | 
			
		||||
$router->any('/logout', 'Logout');
 | 
			
		||||
$router->any('/automation', 'Automation');
 | 
			
		||||
$router->any('/setting', 'Setting');
 | 
			
		||||
$router->any('/device', 'Device');
 | 
			
		||||
$router->any('/device/{sortBy}/{sortType}', 'Device');
 | 
			
		||||
$router->any('/plugins', 'Plugins');
 | 
			
		||||
$router->any('/ajax', 'Ajax');
 | 
			
		||||
$router->any('/oauth', 'Oauth');
 | 
			
		||||
 | 
			
		||||
//Vue APP - Authentication
 | 
			
		||||
$router->post('/api/login', 'AuthApi@login');
 | 
			
		||||
$router->post('/api/logout', 'AuthApi@logout');
 | 
			
		||||
 | 
			
		||||
//Vue APP - Rooms
 | 
			
		||||
$router->get('/api/rooms', 'RoomsApi@default');
 | 
			
		||||
$router->get('/api/rooms/{roomId}/update', 'RoomsApi@update');
 | 
			
		||||
 | 
			
		||||
$router->get('/api/devices', 'DevicesApi@default');
 | 
			
		||||
 | 
			
		||||
$router->get('/api/plugins', 'PluginsApi@default');
 | 
			
		||||
 | 
			
		||||
$router->get('/api/users', 'UsersApi@default');
 | 
			
		||||
 | 
			
		||||
//Vue APP - Server Info
 | 
			
		||||
$router->get('/api/server', 'ServerApi@default');
 | 
			
		||||
$router->get('/api/server/log', 'ServerApi@logStatus');
 | 
			
		||||
 | 
			
		||||
//Vue APP - Widgets
 | 
			
		||||
$router->post('/api/widgets/{widgetId}/run', 'WidgetApi@run');
 | 
			
		||||
$router->get('/api/widgets/{widgetId}/detail', 'WidgetApi@detail');
 | 
			
		||||
$router->get('/api/widgets/{widgetId}/detail/{period}', 'WidgetApi@detail');
 | 
			
		||||
 | 
			
		||||
//Vue APP - Automations Endpoints
 | 
			
		||||
$router->get('/api/automations', 'AutomationsApi@default');
 | 
			
		||||
$router->get('/api/automations/{automationId}/detail', 'AutomationsApi@detail');
 | 
			
		||||
$router->post('/api/automations/create', 'AutomationsApi@create');
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
//cron
 | 
			
		||||
$router->post('/cron/clean', 'CronApi@clean');
 | 
			
		||||
$router->post('/cron/fetch', 'CronApi@fetch');
 | 
			
		||||
$router->post('/cron/automations', 'CronApi@automations');
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
//Google Home - API
 | 
			
		||||
$router->any('/api/HA/auth', 'Oauth');
 | 
			
		||||
$router->any('/api/HA', 'GoogleHomeApi@response');
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
//Endpoints API
 | 
			
		||||
$router->post('/api/endpoint/', 'EndpointsApi@default');
 | 
			
		||||
$router->any('/api/update/', 'UpdatesApi@default');
 | 
			
		||||
$router->any('/api/users/status', 'UsersApi@status');
 | 
			
		||||
$router->any('/api/users/subscribe', 'UsersApi@subscribe');
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
// examples
 | 
			
		||||
$router->any('/api/example', 'ExampleApi@example');
 | 
			
		||||
$router->any('/example', 'ExampleController@index');
 | 
			
		||||
$router->any('/example/subpage', 'ExampleController@subpage');
 | 
			
		||||
 | 
			
		||||
//module routes
 | 
			
		||||
//$router->any('/plugins/spotify/callback', 'Spotify@callback');
 | 
			
		||||
 | 
			
		||||
$router->run($_SERVER['REQUEST_METHOD'], '/'.(isset($_GET['url']) ? $_GET['url'] : ''));
 | 
			
		||||
							
								
								
									
										25
									
								
								app/api/AuthApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								app/api/AuthApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,25 @@
 | 
			
		||||
<?php
 | 
			
		||||
class AuthApi extends ApiController {
 | 
			
		||||
	public function login(){
 | 
			
		||||
		$token = (new AuthManager)->getToken($this->input['username'],$this->input['password']);
 | 
			
		||||
		if (!$token) {
 | 
			
		||||
			throw new Exception("Auth failed", 401);
 | 
			
		||||
		}
 | 
			
		||||
		$this->response(['token' => $token]);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function logout(){
 | 
			
		||||
		$authenticationBearrer = $_SERVER['HTTP_AUTHORIZATION'];
 | 
			
		||||
		if (!(new AuthManager)->deleteToken($authenticationBearrer)) {
 | 
			
		||||
			throw new Exception("logout Failed", 401);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function registration(){
 | 
			
		||||
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function restartPassword(){
 | 
			
		||||
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										34
									
								
								app/api/AutomationsApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										34
									
								
								app/api/AutomationsApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,34 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
class AutomationsApi extends ApiController
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
	public function	default()
 | 
			
		||||
	{
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		$response = [];
 | 
			
		||||
		$response = AutomationManager::getAll(["automation_id","name","enabled"]);
 | 
			
		||||
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function detail($automationId)
 | 
			
		||||
	{
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		$response = [];
 | 
			
		||||
		$response = AutomationManager::getById($automationId, ["automation_id", "last_execution_time", "owner_id", "conditions", "tasks"]);
 | 
			
		||||
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function create()
 | 
			
		||||
	{
 | 
			
		||||
		$this->requireAuth();
 | 
			
		||||
		$obj = $this->input;
 | 
			
		||||
 | 
			
		||||
		$response = [];
 | 
			
		||||
		$response = AutomationManager::create($obj['name'],$obj['days'], $obj['tasks'], $obj['conditions']);
 | 
			
		||||
 | 
			
		||||
		$this->response(['value'=>'OK']);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										67
									
								
								app/api/CronApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										67
									
								
								app/api/CronApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,67 @@
 | 
			
		||||
<?php
 | 
			
		||||
class CronApi extends ApiController
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
	public function clean()
 | 
			
		||||
	{
 | 
			
		||||
		//Log Cleaning
 | 
			
		||||
		$logKeeper = new LogMaintainer();
 | 
			
		||||
		$logKeeper->purge(LOGTIMOUT);
 | 
			
		||||
 | 
			
		||||
		//Database Backup Cleanup
 | 
			
		||||
		$backupWorker = new DatabaseBackup();
 | 
			
		||||
		$backupWorker->purge(5);
 | 
			
		||||
 | 
			
		||||
		//Old Records Cleanup
 | 
			
		||||
		foreach (SubDeviceManager::getAllSubDevices() as $key => $value) {
 | 
			
		||||
			RecordManager::setHistory($value['subdevice_id']);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$this->response(['Value' => 'OK']);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function fetch(){
 | 
			
		||||
		//Run Plugins
 | 
			
		||||
		$result = [];
 | 
			
		||||
		$dir = $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/';
 | 
			
		||||
		$pluginsFiles = array_diff(scandir($dir), ['..', '.']);
 | 
			
		||||
		foreach ($pluginsFiles as $key => $pluginFile) {
 | 
			
		||||
			if (strpos($pluginFile, "!") === false) {
 | 
			
		||||
				$className = str_replace(".php", "", $pluginFile);
 | 
			
		||||
				if (strpos($pluginFile, '_') === true) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
				if (!class_exists($className)) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
				$pluginMakeClass = new $className;
 | 
			
		||||
				if (!method_exists($pluginMakeClass, 'make')) {
 | 
			
		||||
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
				$result[$className] = $pluginMakeClass->make();
 | 
			
		||||
			} else {
 | 
			
		||||
				$className = str_replace("!", "", str_replace(".php", "", $pluginFile));
 | 
			
		||||
				if (strpos($pluginFile, '_') === true) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
				if (!class_exists($className)) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
				$pluginMakeClass = new $className;
 | 
			
		||||
				if (!method_exists($pluginMakeClass, 'disable')) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
				$result[$className] = $pluginMakeClass->disable();
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		//Print Result
 | 
			
		||||
		$this->response($result);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function automations(){
 | 
			
		||||
		AutomationManager:executeAll();
 | 
			
		||||
		$this->response(['Value' => 'OK']);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										15
									
								
								app/api/DevicesApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								app/api/DevicesApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,15 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
class DevicesApi extends ApiController{
 | 
			
		||||
 | 
			
		||||
	public function default(){
 | 
			
		||||
		$this->requireAuth();
 | 
			
		||||
		$response = [];
 | 
			
		||||
 | 
			
		||||
		// TODO: process the request
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getDevicesByRoom($roomId){
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										196
									
								
								app/api/EndpointsApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										196
									
								
								app/api/EndpointsApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,196 @@
 | 
			
		||||
<?php
 | 
			
		||||
class EndpointsApi extends ApiController{
 | 
			
		||||
	public function default(){
 | 
			
		||||
		// $this->requireAuth();
 | 
			
		||||
		$obj = $this->input;
 | 
			
		||||
 | 
			
		||||
		//variables Definition
 | 
			
		||||
		$command = "null";
 | 
			
		||||
 | 
			
		||||
		//Log
 | 
			
		||||
		$logManager = new LogManager('../logs/api/'. date("Y-m-d").'.log');
 | 
			
		||||
		$logManager->setLevel(LOGLEVEL);
 | 
			
		||||
 | 
			
		||||
		//Token Checks
 | 
			
		||||
		if ($obj['token'] == null || !isset($obj['token'])) {
 | 
			
		||||
			$this->response([
 | 
			
		||||
				'state' => 'unsuccess',
 | 
			
		||||
				'errorMSG' => "Missing Value Token in JSON payload",
 | 
			
		||||
			], 401);
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		//Vstupní Checky
 | 
			
		||||
		if (!DeviceManager::registeret($obj['token'])) {
 | 
			
		||||
			//Notification data setup
 | 
			
		||||
			$notificationMng = new NotificationManager;
 | 
			
		||||
			$notificationData = [
 | 
			
		||||
				'title' => 'Info',
 | 
			
		||||
				'body' => 'New device Detected Found',
 | 
			
		||||
				'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
 | 
			
		||||
			];
 | 
			
		||||
 | 
			
		||||
			//Subdevice Registration
 | 
			
		||||
			$device = DeviceManager::create($obj['token'], $obj['token']);
 | 
			
		||||
			foreach ($obj['values'] as $key => $value) {
 | 
			
		||||
				if (!SubDeviceManager::getSubDeviceByMaster($device['device_id'], $key)) {
 | 
			
		||||
					SubDeviceManager::create($device['device_id'], $key, UNITS[$key]);
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
 | 
			
		||||
			//Notification for newly added Device
 | 
			
		||||
			if ($notificationData != []) {
 | 
			
		||||
				$subscribers = $notificationMng::getSubscription();
 | 
			
		||||
				foreach ($subscribers as $key => $subscriber) {
 | 
			
		||||
					$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordTypes::INFO);
 | 
			
		||||
					$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
 | 
			
		||||
			$logManager->write("[API] Registering Device", LogRecordTypes::INFO);
 | 
			
		||||
			$this->response([
 | 
			
		||||
				'state' => 'unsuccess',
 | 
			
		||||
				'errorMSG' => "Device not registeret",
 | 
			
		||||
			], 401);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if (!DeviceManager::approved($obj['token'])) {
 | 
			
		||||
			$this->response([
 | 
			
		||||
				'state' => 'unsuccess',
 | 
			
		||||
				'errorMSG' => "Unaproved Device",
 | 
			
		||||
			], 401);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$device = DeviceManager::getDeviceByToken($obj['token']);
 | 
			
		||||
		DeviceManager::setHeartbeat($device['device_id']);
 | 
			
		||||
 | 
			
		||||
		//Diagnostic
 | 
			
		||||
		if (isset($obj['settings'])){
 | 
			
		||||
			$data = ['mac' => $obj['settings']["network"]["mac"], 'ip_address' => $obj['settings']["network"]["ip"]];
 | 
			
		||||
			if (array_key_exists("firmware_hash", $obj['settings'])) {
 | 
			
		||||
				$data['firmware_hash'] = $obj['settings']["firmware_hash"];
 | 
			
		||||
			}
 | 
			
		||||
			DeviceManager::editByToken($obj['token'], $data);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		//Log Data Save
 | 
			
		||||
		if (isset($obj['logs'])){
 | 
			
		||||
			foreach ($obj['logs'] as $log) {
 | 
			
		||||
				$deviceLogManager = new LogManager('../logs/devices/'. date("Y-m-d").'.log');
 | 
			
		||||
				$deviceLogManager->setLevel(LOGLEVEL);
 | 
			
		||||
				if ($log != 'HTTP_UPDATE_FAILD code-102 messageFile Not Found (404)'){
 | 
			
		||||
					$deviceLogManager->write("[Device Log Msg] Device_ID " . $device['device_id'] . "->" . $log, LogRecordTypes::ERROR);
 | 
			
		||||
				}
 | 
			
		||||
				unset($deviceLogManager);
 | 
			
		||||
			}
 | 
			
		||||
			$this->response([
 | 
			
		||||
				'state' => 'succes',
 | 
			
		||||
				'command' => $command,
 | 
			
		||||
			], 200);
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		// Issuing command
 | 
			
		||||
		if ($command == "null"){
 | 
			
		||||
			$deviceCommand = $device["command"];
 | 
			
		||||
			if ($deviceCommand != '' && $deviceCommand != null && $deviceCommand != "null")
 | 
			
		||||
			{
 | 
			
		||||
				$command = $deviceCommand;
 | 
			
		||||
				$data = [
 | 
			
		||||
					'command'=>'null'
 | 
			
		||||
				];
 | 
			
		||||
				DeviceManager::editByToken($obj['token'], $data);
 | 
			
		||||
				$logManager->write("[API] Device_ID " . $device['device_id'] . " executing command " . $command, LogRecordTypes::INFO);
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$jsonAnswer = [];
 | 
			
		||||
		$subDeviceLastReordValue = [];
 | 
			
		||||
 | 
			
		||||
		if (isset($obj['values'])) {
 | 
			
		||||
			//ZAPIS
 | 
			
		||||
			foreach ($obj['values'] as $key => $value) {
 | 
			
		||||
				if (!SubDeviceManager::getSubDeviceByMaster($device['device_id'], $key)) {
 | 
			
		||||
					SubDeviceManager::create($device['device_id'], $key, UNITS[$key]);
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				$subDeviceLastReordValue[$key] = $value['value'];
 | 
			
		||||
				RecordManager::create($device['device_id'], $key, round($value['value'],3), 'device');
 | 
			
		||||
				$logManager->write("[API] Device_ID " . $device['device_id'] . " writed value " . $key . ' ' . $value['value'], LogRecordTypes::INFO);
 | 
			
		||||
 | 
			
		||||
				//notification
 | 
			
		||||
				if ($key == 'door' || $key == 'water') {
 | 
			
		||||
					$notificationMng = new NotificationManager;
 | 
			
		||||
					$notificationData = [];
 | 
			
		||||
 | 
			
		||||
					switch ($key) {
 | 
			
		||||
						case 'door':
 | 
			
		||||
							$notificationData = [
 | 
			
		||||
								'title' => 'Info',
 | 
			
		||||
								'body' => 'Someone just open up '.$device['name'],
 | 
			
		||||
								'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
 | 
			
		||||
							];
 | 
			
		||||
 | 
			
		||||
						break;
 | 
			
		||||
						case 'water':
 | 
			
		||||
							$notificationData = [
 | 
			
		||||
								'title' => 'Alert',
 | 
			
		||||
								'body' => 'Wather leak detected by '.$device['name'],
 | 
			
		||||
								'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
 | 
			
		||||
							];
 | 
			
		||||
						break;
 | 
			
		||||
					}
 | 
			
		||||
					if (DEBUGMOD) $notificationData['body'] .= ' value='.$value['value'];
 | 
			
		||||
					if ($notificationData != []) {
 | 
			
		||||
						$subscribers = $notificationMng::getSubscription();
 | 
			
		||||
						foreach ($subscribers as $key => $subscriber) {
 | 
			
		||||
							$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordTypes::INFO);
 | 
			
		||||
							$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
 | 
			
		||||
						}
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
			//upravit format na setings-> netvork etc
 | 
			
		||||
 | 
			
		||||
			$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($device['device_id']);
 | 
			
		||||
			if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) {
 | 
			
		||||
				$jsonAnswer['device']['sleepTime'] = $device['sleep_time'];
 | 
			
		||||
			}
 | 
			
		||||
		} else {
 | 
			
		||||
			if (count(SubDeviceManager::getAllSubDevices($device['device_id'])) == 0) {
 | 
			
		||||
				//SubDeviceManager::create($device['device_id'], 'on/off', UNITS[$key]);
 | 
			
		||||
				//RecordManager::create($device['device_id'], 'on/off', 0);
 | 
			
		||||
			}
 | 
			
		||||
 | 
			
		||||
			$subDevicesData = SubDeviceManager::getAllSubDevices($device['device_id']);
 | 
			
		||||
 | 
			
		||||
			foreach ($subDevicesData as $key => $subDeviceData) {
 | 
			
		||||
				$subDeviceId = $subDeviceData['subdevice_id'];
 | 
			
		||||
				$subDeviceLastReord = RecordManager::getLastRecord($subDeviceId);
 | 
			
		||||
				if (!empty ($subDeviceLastReord)) {
 | 
			
		||||
					$subDeviceLastReordValue[$subDeviceData['type']] = $subDeviceLastReord['value'];
 | 
			
		||||
					if ($subDeviceLastReord['execuded'] == 0){
 | 
			
		||||
						$logManager->write("[API] subDevice_ID " . $subDeviceId . " executed comand with value " . json_encode($subDeviceLastReordValue) . " executed " . $subDeviceLastReord['execuded'], LogRecordTypes::INFO);
 | 
			
		||||
						RecordManager::setExecuted($subDeviceLastReord['record_id']);
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$hostname = "";
 | 
			
		||||
		$hostname = strtolower($device['name']);
 | 
			
		||||
		$hostname = str_replace(' ', '_', $hostname);
 | 
			
		||||
 | 
			
		||||
		$jsonAnswer['device']['hostname'] = $hostname;
 | 
			
		||||
		$jsonAnswer['state'] = 'succes';
 | 
			
		||||
		$jsonAnswer['values'] = $subDeviceLastReordValue;
 | 
			
		||||
		$jsonAnswer['command'] = $command;
 | 
			
		||||
 | 
			
		||||
		$this->response($jsonAnswer);
 | 
			
		||||
		// this method returns response as json
 | 
			
		||||
		//unset($logManager); //TODO: Opravit
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										24
									
								
								app/api/ExampleApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										24
									
								
								app/api/ExampleApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,24 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
class ExampleApi extends ApiController{
 | 
			
		||||
 | 
			
		||||
	public function example(){
 | 
			
		||||
		// if this function should be accessible only for logged users uncomment next line
 | 
			
		||||
		// $this->requireAuth();
 | 
			
		||||
		// if user is logged in, next lines will be processed
 | 
			
		||||
		// otherwise script get terminated with 401 UNAUTHORIZED
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		// input data are stored in $this->input
 | 
			
		||||
		// in this example we just copy input to response
 | 
			
		||||
		$response = $this->input;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		// this method returns response as json
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
		// you can specify returned http code by second optional parameter
 | 
			
		||||
		// default value is 200
 | 
			
		||||
		// $this->response($response, $httpCode);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										56
									
								
								app/api/GoogleHomeApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										56
									
								
								app/api/GoogleHomeApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,56 @@
 | 
			
		||||
<?php
 | 
			
		||||
class GoogleHomeApi{
 | 
			
		||||
	static function response(){
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		$json = file_get_contents('php://input');
 | 
			
		||||
		$obj = json_decode($json, true);
 | 
			
		||||
 | 
			
		||||
		$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
 | 
			
		||||
		$apiLogManager->setLevel(LOGLEVEL);
 | 
			
		||||
 | 
			
		||||
		header('Content-Type: application/json');
 | 
			
		||||
 | 
			
		||||
		switch ($obj['inputs'][0]['intent']) {
 | 
			
		||||
			case 'action.devices.SYNC':
 | 
			
		||||
			GoogleHome::sync($obj['requestId']);
 | 
			
		||||
			$apiLogManager->write("[Google Home] action.devices.SYNC", LogRecordTypes::INFO);
 | 
			
		||||
			break;
 | 
			
		||||
 | 
			
		||||
			case 'action.devices.QUERY':
 | 
			
		||||
			GoogleHome::query($obj['requestId'], $obj['inputs'][0]['payload']);
 | 
			
		||||
			$apiLogManager->write("[Google Home] action.devices.QUERY", LogRecordTypes::INFO);
 | 
			
		||||
			$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
			break;
 | 
			
		||||
 | 
			
		||||
			case 'action.devices.EXECUTE':
 | 
			
		||||
 | 
			
		||||
			GoogleHome::execute($obj['requestId'], $obj['inputs'][0]['payload']);
 | 
			
		||||
			$apiLogManager->write("[Google Home] action.devices.EXECUTE", LogRecordTypes::INFO);
 | 
			
		||||
			$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
 | 
			
		||||
			break;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		unset($apiLogManager);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function autorize(){
 | 
			
		||||
		$json = file_get_contents('php://input');
 | 
			
		||||
		$obj = json_decode($json, true);
 | 
			
		||||
 | 
			
		||||
		$apiLogManager = new LogManager('../logs/google-home/'. date("Y-m-d").'.log');
 | 
			
		||||
		$apiLogManager->setLevel(LOGLEVEL);
 | 
			
		||||
		$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
		$apiLogManager->write("[API] GET body\n" . json_encode($_GET, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
		unset($apiLogManager);
 | 
			
		||||
 | 
			
		||||
		$get = [
 | 
			
		||||
			"access_token"=>"2222255888", //TODO: FIX
 | 
			
		||||
			"token_type"=>"Bearer",
 | 
			
		||||
			"state"=>$_GET["state"],
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		echo $_GET["redirect_uri"] . '#' . http_build_query($get) ;
 | 
			
		||||
		echo '<a href="'.$_GET["redirect_uri"] . '#' . http_build_query($get) . '">FINISH</a>';
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										12
									
								
								app/api/PluginsApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								app/api/PluginsApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,12 @@
 | 
			
		||||
<?php
 | 
			
		||||
class PluginsApi extends ApiController{
 | 
			
		||||
 | 
			
		||||
	public function default(){
 | 
			
		||||
		$this->requireAuth();
 | 
			
		||||
		$response = [];
 | 
			
		||||
 | 
			
		||||
		// TODO: process the request
 | 
			
		||||
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										26
									
								
								app/api/RecordApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										26
									
								
								app/api/RecordApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,26 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
class RecordApi extends ApiController{
 | 
			
		||||
 | 
			
		||||
	public function default(){
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		$response = [];
 | 
			
		||||
		$roomIds = [];
 | 
			
		||||
		$roomsData = RoomManager::getRoomsDefault();
 | 
			
		||||
 | 
			
		||||
		foreach ($roomsData as $roomKey => $room) {
 | 
			
		||||
			$roomIds[] = $room['room_id'];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds);
 | 
			
		||||
 | 
			
		||||
		foreach ($roomsData as $roomKey => $roomData) {
 | 
			
		||||
			$response[] = [
 | 
			
		||||
				'room_id' => $roomData['room_id'],
 | 
			
		||||
				'name' => $roomData['name'],
 | 
			
		||||
				'widgets' => isset($subDevicesData[$roomData['room_id']]) ? $subDevicesData[$roomData['room_id']] : [],
 | 
			
		||||
			];
 | 
			
		||||
		}
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										75
									
								
								app/api/RoomsApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										75
									
								
								app/api/RoomsApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,75 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
class RoomsApi extends ApiController
 | 
			
		||||
{
 | 
			
		||||
	
 | 
			
		||||
	public function	default()
 | 
			
		||||
	{
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		$response = [];
 | 
			
		||||
		$roomIds = [];
 | 
			
		||||
		$roomsData = RoomManager::getRoomsDefault();
 | 
			
		||||
		
 | 
			
		||||
		foreach ($roomsData as $roomKey => $room) {
 | 
			
		||||
			$roomIds[] = $room['room_id'];
 | 
			
		||||
		}
 | 
			
		||||
		
 | 
			
		||||
		//Translation Of Numeric Walues
 | 
			
		||||
		$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds($roomIds);
 | 
			
		||||
		foreach ($subDevicesData as $subDeviceKey => $subDevice) {
 | 
			
		||||
			foreach ($subDevice as $key => $value) {
 | 
			
		||||
				//Type Handling
 | 
			
		||||
				$type = null;
 | 
			
		||||
				if (strpos($subDevicesData[$subDeviceKey][$key]['type'], '-') !== false) {
 | 
			
		||||
					$type = $subDevicesData[$subDeviceKey][$key]['type'];
 | 
			
		||||
				} else if (strpos(SubDeviceManager::getSubDeviceMaster($subDevicesData[$subDeviceKey][$key]['subdevice_id'])['type'], '-') !== false) {
 | 
			
		||||
					$type = SubDeviceManager::getSubDeviceMaster($subDevicesData[$subDeviceKey][$key]['subdevice_id'])['type'];
 | 
			
		||||
				}
 | 
			
		||||
				
 | 
			
		||||
				//Connection Error Creation
 | 
			
		||||
				$connectionError = true;
 | 
			
		||||
				$LastRecordTime = new DateTime($subDevicesData[$subDeviceKey][$key]['time']);
 | 
			
		||||
				$interval = $LastRecordTime->diff(new DateTime());
 | 
			
		||||
				$lastSeen = ($interval->format('%h') * 60 + $interval->format('%i'));
 | 
			
		||||
				
 | 
			
		||||
				if ($subDevicesData[$subDeviceKey][$key]['sleep_time'] == NULL || $subDevicesData[$subDeviceKey][$key]['sleep_time'] == 0 || $lastSeen < $subDevicesData[$subDeviceKey][$key]['sleep_time']) {
 | 
			
		||||
					$connectionError = false;
 | 
			
		||||
				}
 | 
			
		||||
				$subDevicesData[$subDeviceKey][$key]['connection_error'] = $connectionError;
 | 
			
		||||
 | 
			
		||||
				//Record Translation
 | 
			
		||||
				$cammelCaseClass = "";
 | 
			
		||||
				foreach (explode('-', $type) as $word) {
 | 
			
		||||
					$cammelCaseClass .= ucfirst($word);
 | 
			
		||||
				}
 | 
			
		||||
				if (class_exists($cammelCaseClass)) {
 | 
			
		||||
					$deviceClass = new $cammelCaseClass;
 | 
			
		||||
					if (method_exists($deviceClass, 'translate')) {
 | 
			
		||||
						$subDevicesData[$subDeviceKey][$key]['value'] = $deviceClass->translate($subDevicesData[$subDeviceKey][$key]['value']);
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		
 | 
			
		||||
		foreach ($roomsData as $roomKey => $roomData) {
 | 
			
		||||
			if ($roomData['device_count'] == 0) continue;
 | 
			
		||||
			$subDevicesSorted = isset($subDevicesData[$roomData['room_id']]) ? Utilities::sortArrayByKey($subDevicesData[$roomData['room_id']], 'connection_error', 'asc') : [];
 | 
			
		||||
			if (count($subDevicesSorted) == 0) continue;
 | 
			
		||||
			$response[] = [
 | 
			
		||||
				'room_id' => $roomData['room_id'],
 | 
			
		||||
				'name' => $roomData['name'],
 | 
			
		||||
				'widgets' => $subDevicesSorted,
 | 
			
		||||
			];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
	}
 | 
			
		||||
	
 | 
			
		||||
	public function update($roomId)
 | 
			
		||||
	{
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		
 | 
			
		||||
		$subDevicesData = SubDeviceManager::getSubdevicesByRoomIds([$roomId]);
 | 
			
		||||
		$this->response($subDevicesData);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										43
									
								
								app/api/ServerApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										43
									
								
								app/api/ServerApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,43 @@
 | 
			
		||||
<?php
 | 
			
		||||
class ServerApi extends ApiController {
 | 
			
		||||
    private function getSystemMemInfo()
 | 
			
		||||
	{
 | 
			
		||||
		$data = explode("\n", file_get_contents("/proc/meminfo"));
 | 
			
		||||
		$meminfo = array();
 | 
			
		||||
		foreach ($data as $line) {
 | 
			
		||||
			$data = explode(":", $line);
 | 
			
		||||
			if (count($data)!=2) continue;
 | 
			
		||||
			$meminfo[$data[0]] = trim($data[1]);
 | 
			
		||||
		}
 | 
			
		||||
		return $meminfo;
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private function getProcessorUsage(){
 | 
			
		||||
		$loads=sys_getloadavg();
 | 
			
		||||
		$core_nums=trim(shell_exec("grep -P '^physical id' /proc/cpuinfo|wc -l"));
 | 
			
		||||
		$load = round($loads[0]/($core_nums + 1)*100, 2);
 | 
			
		||||
		return $load;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
    public function default(){
 | 
			
		||||
        //$this->requireAuth();
 | 
			
		||||
        $response = [
 | 
			
		||||
            "cpu_load" => $this->getProcessorUsage(),
 | 
			
		||||
            "uptime" => shell_exec('uptime -p'),
 | 
			
		||||
            "ramFree" => $this->getSystemMemInfo()["MemFree"],
 | 
			
		||||
            "ramTotal" => $this->getSystemMemInfo()["MemTotal"],
 | 
			
		||||
            "diskFree" => disk_free_space("/"),
 | 
			
		||||
            "diskTotal" => disk_total_space("/"),
 | 
			
		||||
            "serverTime" => date('m. d. Y H:i:s'),
 | 
			
		||||
            "serverTimeZone" => date('e'),
 | 
			
		||||
        ];
 | 
			
		||||
        $this->response($response);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public function logStatus()
 | 
			
		||||
    {
 | 
			
		||||
        $logKeeper = new LogMaintainer();
 | 
			
		||||
        $response = $logKeeper::getStats();
 | 
			
		||||
        $this->response($response);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										85
									
								
								app/api/UpdatesApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										85
									
								
								app/api/UpdatesApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,85 @@
 | 
			
		||||
<?php
 | 
			
		||||
class UpdatesApi {
 | 
			
		||||
    private function sendFile($path)	{
 | 
			
		||||
        header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK', true, 200);
 | 
			
		||||
        header('Content-Type: application/octet-stream', true);
 | 
			
		||||
        header('Content-Disposition: attachment; filename=' . basename($path));
 | 
			
		||||
        header('Content-Length: ' . filesize($path), true);
 | 
			
		||||
        header('x-MD5: ' . md5_file($path), true);
 | 
			
		||||
        readfile($path);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    private function validateHeader($headers){
 | 
			
		||||
        if (
 | 
			
		||||
            isset($_SERVER['HTTP_X_ESP8266_STA_MAC']) &&
 | 
			
		||||
            isset($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'])
 | 
			
		||||
        ) {
 | 
			
		||||
            return true;
 | 
			
		||||
        }
 | 
			
		||||
        return false;
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    public function default(){
 | 
			
		||||
        $logManager = new LogManager('../logs/ota/'. date("Y-m-d").'.log');
 | 
			
		||||
        $logManager->setLevel(LOGLEVEL);
 | 
			
		||||
        $logManager->write("[Updater] Client Connected", LogRecordTypes::INFO);
 | 
			
		||||
 | 
			
		||||
      //   if($this->validateHeader($_SERVER)){
 | 
			
		||||
      //       header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Header");
 | 
			
		||||
      //       die();
 | 
			
		||||
      //   }
 | 
			
		||||
 | 
			
		||||
        header('Content-type: text/plain; charset=utf8', true);
 | 
			
		||||
 | 
			
		||||
        // //Filtrování IP adress
 | 
			
		||||
        // if (DEBUGMOD != 1) {
 | 
			
		||||
        //     if (!in_array($_SERVER['REMOTE_ADDR'], HOMEIP)) {
 | 
			
		||||
        //         echo json_encode(array(
 | 
			
		||||
        //             'state' => 'unsuccess',
 | 
			
		||||
        //             'errorMSG' => "Using API from your IP insnt alowed!",
 | 
			
		||||
        //         ));
 | 
			
		||||
        //         header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
 | 
			
		||||
        //         $logManager->write("[Updater] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordTypes::INFO);
 | 
			
		||||
        //         exit();
 | 
			
		||||
        //     }
 | 
			
		||||
        // }
 | 
			
		||||
 | 
			
		||||
        $macAddress = $_SERVER['HTTP_X_ESP8266_STA_MAC'];
 | 
			
		||||
        $localBinary = "../updater/" . str_replace(':', '', $macAddress) . ".bin";
 | 
			
		||||
        $logManager->write("[Updater] url: " . $localBinary, LogRecordTypes::INFO);
 | 
			
		||||
        $logManager->write("[Updater] version:      " . $_SERVER['HTTP_X_ESP8266_SKETCH_MD5'], LogRecordTypes::INFO);
 | 
			
		||||
        if (file_exists($localBinary)) {
 | 
			
		||||
            $logManager->write("[Updater] version PHP: " . md5_file($localBinary), LogRecordTypes::INFO);
 | 
			
		||||
            if ($_SERVER['HTTP_X_ESP8266_SKETCH_MD5'] != md5_file($localBinary)) {
 | 
			
		||||
                $this->sendFile($localBinary);
 | 
			
		||||
                //get device data
 | 
			
		||||
                $device = DeviceManager::getDeviceByMac($macAddress);
 | 
			
		||||
                $deviceName = $device['name'];
 | 
			
		||||
                $deviceId = $device['device_id'];
 | 
			
		||||
                //logfile write
 | 
			
		||||
                $logManager->write("[Device] device_ID " . $deviceId . " was just updated to new version", LogRecordTypes::INFO);
 | 
			
		||||
                $logManager->write("[Device] version hash: " . md5_file($localBinary), LogRecordTypes::INFO);
 | 
			
		||||
                //notification
 | 
			
		||||
                $notificationMng = new NotificationManager;
 | 
			
		||||
                $notificationData = [
 | 
			
		||||
                    'title' => 'Info',
 | 
			
		||||
                    'body' => $deviceName.' was just updated to new version',
 | 
			
		||||
                    'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
 | 
			
		||||
                ];
 | 
			
		||||
                if ($notificationData != []) {
 | 
			
		||||
                    $subscribers = $notificationMng->getSubscription();
 | 
			
		||||
                    foreach ($subscribers as $key => $subscriber) {
 | 
			
		||||
                        $logManager->write("[NOTIFICATION] SENDING TO " . $subscriber['id'] . " ", LogRecordTypes::INFO);
 | 
			
		||||
                        $answer = $notificationMng->sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
            } else {
 | 
			
		||||
                header($_SERVER["SERVER_PROTOCOL"].' 304 Not Modified', true, 304);
 | 
			
		||||
            }
 | 
			
		||||
        } else {
 | 
			
		||||
            header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
 | 
			
		||||
        }
 | 
			
		||||
        die();
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										47
									
								
								app/api/UsersApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										47
									
								
								app/api/UsersApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,47 @@
 | 
			
		||||
<?php
 | 
			
		||||
class UsersApi extends ApiController{
 | 
			
		||||
	public function default(){
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		$response = null;
 | 
			
		||||
 | 
			
		||||
		$users = UserManager::getUsers(["user_id", "username", "at_home"]);
 | 
			
		||||
 | 
			
		||||
		foreach ($users as $key => $user) {
 | 
			
		||||
			$response[] = [
 | 
			
		||||
				"userName" => $user['username'],
 | 
			
		||||
				"homeStatus" => ($user['at_home'] == 'true') ? true : false,
 | 
			
		||||
				"avatarUrl" => UserManager::getAvatarUrl($user['user_id']),
 | 
			
		||||
			];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function status(){
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		$response = null;
 | 
			
		||||
		$obj = $this->input;
 | 
			
		||||
		$atHome = $obj['atHome'];
 | 
			
		||||
 | 
			
		||||
		$user = UserManager::getUser($obj['user']);
 | 
			
		||||
		$userAtHome = $user['at_home'];
 | 
			
		||||
		$userId = $user['user_id'];
 | 
			
		||||
 | 
			
		||||
		if (!empty($user)) {
 | 
			
		||||
			if($userAtHome != $atHome){
 | 
			
		||||
				UserManager::atHome($userId, $atHome);
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		$this->response(['value'=>'OK']);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function subscribe(){
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
		$bearer = $_SERVER['HTTP_AUTHORIZATION'];
 | 
			
		||||
		$authManager = new AuthManager();
 | 
			
		||||
		$userId = $authManager->getUserId($bearer);
 | 
			
		||||
 | 
			
		||||
		NotificationManager::addSubscriber($userId, $this->input['pushtoken']);
 | 
			
		||||
		$this->response(['value'=>'OK']);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										137
									
								
								app/api/WidgetApi.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										137
									
								
								app/api/WidgetApi.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,137 @@
 | 
			
		||||
<?php
 | 
			
		||||
class WidgetApi extends ApiController
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
	public function run($subDeviceId)
 | 
			
		||||
	{
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
 | 
			
		||||
		$response = null;
 | 
			
		||||
		if (RecordManager::getLastRecord($subDeviceId)['execuded'] === 0) {
 | 
			
		||||
			throw new Exception("Unreachable", 409);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$subDeviceData = SubDeviceManager::getSubDevice($subDeviceId);
 | 
			
		||||
		if ($subDeviceData['type'] == 'on/off') {
 | 
			
		||||
			$lastValue = RecordManager::getLastRecord($subDeviceData['subdevice_id'])['value'];
 | 
			
		||||
			RecordManager::create($subDeviceData['device_id'], 'on/off', (int) !$lastValue, "vue-app");
 | 
			
		||||
			$response = !$lastValue;
 | 
			
		||||
		} else {
 | 
			
		||||
			throw new Exception("Bad Request", 403);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$i = 0;
 | 
			
		||||
		$timeout = 20;
 | 
			
		||||
		while (RecordManager::getLastRecord($subDeviceId)['execuded'] == 0) {
 | 
			
		||||
			if ($i == $timeout) {
 | 
			
		||||
				throw new Exception("Timeout", 444);
 | 
			
		||||
			}
 | 
			
		||||
			$i++;
 | 
			
		||||
			usleep(250000);
 | 
			
		||||
		}
 | 
			
		||||
		$this->response(['value' => $response]);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function detail($subDeviceId, $period = "day")
 | 
			
		||||
	{
 | 
			
		||||
		//$this->requireAuth();
 | 
			
		||||
 | 
			
		||||
		$groupBy = [
 | 
			
		||||
			"year" => "month",
 | 
			
		||||
			"month" => "day",
 | 
			
		||||
			"day" => "hour",
 | 
			
		||||
			"hout" => "minute",
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		$response = null;
 | 
			
		||||
		$subDeviceData = SubDeviceManager::getSubdeviceDetailById($subDeviceId);
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		//TODO: zeptat se @Patrik Je Graf Dobře Seřazený na DESC ?
 | 
			
		||||
		$events = RecordManager::getAllRecordForGraph($subDeviceId, $period, $groupBy[$period]);
 | 
			
		||||
		if ( count($events) == 0){
 | 
			
		||||
			throw new Exception("No Records", 404);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		//Striping executed value from dataset if pasiv device such as Senzor ETC
 | 
			
		||||
		if ($subDeviceData['type'] != "on/off") {
 | 
			
		||||
			foreach ($events as $key => $event) {
 | 
			
		||||
				unset($events[$key]['execuded']);
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$LastRecordTime = new DateTime(reset($events)['time']);
 | 
			
		||||
		$niceTime = Utilities::ago($LastRecordTime);
 | 
			
		||||
 | 
			
		||||
		$labels = [];
 | 
			
		||||
		$values = [];
 | 
			
		||||
		foreach ($events as $key => $event) {
 | 
			
		||||
			$recordDatetime = new DateTime($event['time']);
 | 
			
		||||
			if ($key == 0){
 | 
			
		||||
				$labels[] = 'now';
 | 
			
		||||
			} else {
 | 
			
		||||
				$labels[] = $recordDatetime->format('H:i');
 | 
			
		||||
			}
 | 
			
		||||
			$values[] = [
 | 
			
		||||
				'y' => $event['value'],
 | 
			
		||||
				't' => $recordDatetime->getTimestamp() * 1000,
 | 
			
		||||
			];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$response = [
 | 
			
		||||
			'room_id' => $subDeviceData['room_id'],
 | 
			
		||||
			'device_id' => $subDeviceData['device_id'],
 | 
			
		||||
			'lastConnectionTime' => (empty($niceTime) ? "00:00" : $niceTime),
 | 
			
		||||
			'records' => $events,
 | 
			
		||||
			'graph' => [
 | 
			
		||||
				'type' => $this->getDeviceConfig($subDeviceData['type'])['graph'],
 | 
			
		||||
				'data' => [
 | 
			
		||||
					'labels' => $labels,
 | 
			
		||||
					'datasets' => [[
 | 
			
		||||
						//'label' => 'FUCK you',
 | 
			
		||||
						'data' => $values,
 | 
			
		||||
					]],
 | 
			
		||||
				],
 | 
			
		||||
				'options' => [
 | 
			
		||||
					'scales' => [
 | 
			
		||||
						'xAxis' => [[
 | 
			
		||||
							'type' => 'time',
 | 
			
		||||
							'distribution' => 'linear',
 | 
			
		||||
						]],
 | 
			
		||||
 | 
			
		||||
					],
 | 
			
		||||
					'legend' => [
 | 
			
		||||
						'display' => false
 | 
			
		||||
					],
 | 
			
		||||
					'tooltips' => [
 | 
			
		||||
						'enabled' => true
 | 
			
		||||
					],
 | 
			
		||||
					'hover' => [
 | 
			
		||||
						'mode' => true
 | 
			
		||||
					],
 | 
			
		||||
				],
 | 
			
		||||
			],
 | 
			
		||||
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		//TODO: Make Cleaner
 | 
			
		||||
		if (isset(RANGES[$subDeviceData['type']])){
 | 
			
		||||
			$response['graph']['options']['scales']['yAxes'] = [[
 | 
			
		||||
				'ticks' => [
 | 
			
		||||
					'min' => RANGES[$subDeviceData['type']]['min'],
 | 
			
		||||
					'max' => RANGES[$subDeviceData['type']]['max'],
 | 
			
		||||
					'steps' => RANGES[$subDeviceData['type']]['scale'],
 | 
			
		||||
				]
 | 
			
		||||
			]];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$this->response($response);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	private function getDeviceConfig($type){
 | 
			
		||||
		if (isset(RANGES[$type])){
 | 
			
		||||
			return RANGES[$type];
 | 
			
		||||
		}
 | 
			
		||||
		return RANGES[''];
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,39 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
/**
 | 
			
		||||
*
 | 
			
		||||
*/
 | 
			
		||||
 | 
			
		||||
class LogRecordType{
 | 
			
		||||
	const WARNING = 'warning';
 | 
			
		||||
	const ERROR = 'error';
 | 
			
		||||
	const INFO = 'info';
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
class LogManager
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
	private $logFile;
 | 
			
		||||
	function __construct($fileName = "")
 | 
			
		||||
	{
 | 
			
		||||
		if ($fileName == ""){
 | 
			
		||||
			$fileName = './app/logs/'. date("Y-m-d").'.log';
 | 
			
		||||
		}
 | 
			
		||||
		if(!is_dir("./app/logs/"))
 | 
			
		||||
		{
 | 
			
		||||
			mkdir("./app/logs/");
 | 
			
		||||
		}
 | 
			
		||||
		$this->logFile = fopen($fileName, "a") or die("Unable to open file!");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function write($value, $type = LogRecordType::ERROR){
 | 
			
		||||
		$record = "[".date("H:m:s")."][".$type."]" . $value . "\n";
 | 
			
		||||
		$record = Utilities::stringInsert($record,"\n",65);
 | 
			
		||||
		fwrite($this->logFile, $record);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function __destruct(){
 | 
			
		||||
		if (isset($this->logFile)) {
 | 
			
		||||
			fclose($this->logFile);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,26 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
class RoomManager{
 | 
			
		||||
	public static $rooms;
 | 
			
		||||
 | 
			
		||||
	function getAllRooms () {
 | 
			
		||||
		$allRoom = Db::loadAll ("SELECT rooms.*, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id");
 | 
			
		||||
		return $allRoom;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function create ($name) {
 | 
			
		||||
		$room = array (
 | 
			
		||||
			'name' => $name,
 | 
			
		||||
		);
 | 
			
		||||
		try {
 | 
			
		||||
			Db::add ('rooms', $room);
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function delete ($roomId) {
 | 
			
		||||
		Db::command ('DELETE FROM rooms WHERE room_id=?', array ($roomId));
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
@@ -1,30 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
class Route{
 | 
			
		||||
	private $urls = [];
 | 
			
		||||
	private $views = [];
 | 
			
		||||
 | 
			
		||||
	function __construct() {
 | 
			
		||||
		// code...
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function add($url, $view = "", $conrol = "") {
 | 
			
		||||
		$this->urls[] = '/'.trim($url, '/');
 | 
			
		||||
		if (!empty($view)) {
 | 
			
		||||
			$this->views[] = $view;
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function submit(){
 | 
			
		||||
		$urlGetParam = isset($_GET['url']) ? '/' . $_GET['url'] : '/';
 | 
			
		||||
		foreach ($this->urls as $urlKey => $urlValue) {
 | 
			
		||||
			if ($urlValue === $urlGetParam) {
 | 
			
		||||
				$useView = $this->views[$urlKey];
 | 
			
		||||
				new $useView();
 | 
			
		||||
				die();
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		echo 'Not Fount 404';
 | 
			
		||||
		die();
 | 
			
		||||
		//TODO: 404 přidělat
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,71 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
class SubDeviceManager
 | 
			
		||||
{
 | 
			
		||||
	public static $devices;
 | 
			
		||||
 | 
			
		||||
	public function getAllSubDevices($deviceId)
 | 
			
		||||
	{
 | 
			
		||||
		return Db::loadAll("SELECT * FROM subdevices WHERE device_id = ?", array($deviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getSubDeviceMaster($subDeviceId)
 | 
			
		||||
	{
 | 
			
		||||
		return Db::loadOne("SELECT * FROM devices WHERE device_id = (SELECT device_id FROM subdevices WHERE subdevice_id = ?)", array($subDeviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getSubDeviceByMaster($deviceId, $subDeviceType = null)
 | 
			
		||||
	{
 | 
			
		||||
		if ($subDeviceType == null) {
 | 
			
		||||
			return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
 | 
			
		||||
		} else {
 | 
			
		||||
			return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ? AND type = ?;", array($deviceId, $subDeviceType));
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getSubDeviceByMasterAndType($deviceId, $subDeviceType = null)
 | 
			
		||||
	{
 | 
			
		||||
		if (!empty($subDeviceType)) {
 | 
			
		||||
			return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
 | 
			
		||||
		} else {
 | 
			
		||||
			return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ? AND type = ?;", array($deviceId, $subDeviceType));
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getSubDevice($subDeviceId)
 | 
			
		||||
	{
 | 
			
		||||
		return Db::loadOne("SELECT * FROM subdevices WHERE subdevice_id = ?;", array($subDeviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getSubDevicesTypeForMater($deviceId)
 | 
			
		||||
	{
 | 
			
		||||
		$parsedTypes = [];
 | 
			
		||||
		$types = Db::loadAll("SELECT type FROM subdevices WHERE device_id = ?;", array($deviceId));
 | 
			
		||||
		foreach ($types as $orderNum => $type) {
 | 
			
		||||
			$parsedTypes[$orderNum] = $type['type'];
 | 
			
		||||
		}
 | 
			
		||||
		return $parsedTypes;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	//check if dubdevice exist
 | 
			
		||||
 | 
			
		||||
	public function create($deviceId, $type, $unit)
 | 
			
		||||
	{
 | 
			
		||||
		$record = array(
 | 
			
		||||
			'device_id' => $deviceId,
 | 
			
		||||
			'type' => $type,
 | 
			
		||||
			'unit' => $unit,
 | 
			
		||||
		);
 | 
			
		||||
		try {
 | 
			
		||||
			Db::add('subdevices', $record);
 | 
			
		||||
		} catch (PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function remove($subDeviceId)
 | 
			
		||||
	{
 | 
			
		||||
		RecordManager::cleanSubdeviceRecords($subDeviceId);
 | 
			
		||||
		return Db::loadAll("DELETE FROM subdevices WHERE subdevice_id = ?", array($subDeviceId));
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,34 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
class Template extends Partial{
 | 
			
		||||
	var $assignedValues = [];
 | 
			
		||||
	var $partBuffer;
 | 
			
		||||
	var $path;
 | 
			
		||||
	var $debug;
 | 
			
		||||
 | 
			
		||||
	function __construct($path = "", $debug = false) {
 | 
			
		||||
		$this->debug = $debug;
 | 
			
		||||
		if (!empty('app/templates/' . $path . '.phtml') && file_exists('app/templates/' . $path . '.phtml')) {
 | 
			
		||||
			$this->path = $path;
 | 
			
		||||
		} else {
 | 
			
		||||
			echo '<pre>';
 | 
			
		||||
			echo 'PHTML: Template File ' . $path . ' not found';
 | 
			
		||||
			echo '</pre>';
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function prepare($searchS, $repleaceS) {
 | 
			
		||||
		if (!empty($searchS)) {
 | 
			
		||||
			$this->assignedValues[strtoupper($searchS)] = $repleaceS;
 | 
			
		||||
		}
 | 
			
		||||
		echo ($this->debug == true ? var_dump($this->assignedValues) : '');
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function render() {
 | 
			
		||||
		extract($this->assignedValues);
 | 
			
		||||
		if (!empty('app/controls/' . $this->path . '.php') && file_exists('app/controls/' . $this->path . '.php')) {
 | 
			
		||||
			require_once('app/controls/' . $this->path . '.php');
 | 
			
		||||
		}
 | 
			
		||||
		require_once('app/templates/' . $this->path . '.phtml');
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,142 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
/**
 | 
			
		||||
*
 | 
			
		||||
*/
 | 
			
		||||
class Utilities
 | 
			
		||||
{
 | 
			
		||||
	function cleanString($text) {
 | 
			
		||||
		$utf8 = array(
 | 
			
		||||
			'/[áàâãªä]/u'   =>   'a',
 | 
			
		||||
			'/[ÁÀÂÃÄ]/u'    =>   'A',
 | 
			
		||||
			'/[ÍÌÎÏ]/u'     =>   'I',
 | 
			
		||||
			'/[íìîï]/u'     =>   'i',
 | 
			
		||||
			'/[ěéèêë]/u'     =>   'e',
 | 
			
		||||
			'/[ĚÉÈÊË]/u'     =>   'E',
 | 
			
		||||
			'/[óòôõºö]/u'   =>   'o',
 | 
			
		||||
			'/[ÓÒÔÕÖ]/u'    =>   'O',
 | 
			
		||||
			'/[úùûü]/u'     =>   'u',
 | 
			
		||||
			'/[ÚÙÛÜ]/u'     =>   'U',
 | 
			
		||||
			'/Š/'     		=>   'S',
 | 
			
		||||
			'/š/'     		=>   's',
 | 
			
		||||
			'/Č/'     		=>   'C',
 | 
			
		||||
			'/č/'     		=>   'c',
 | 
			
		||||
			'/ř/'     		=>   'r',
 | 
			
		||||
			'/Ř/'     		=>   'R',
 | 
			
		||||
			'/Ý/'     		=>   'Y',
 | 
			
		||||
			'/ý/'     		=>   'y',
 | 
			
		||||
			'/ç/'           =>   'c',
 | 
			
		||||
			'/Ç/'           =>   'C',
 | 
			
		||||
			'/ñ/'           =>   'n',
 | 
			
		||||
			'/Ñ/'           =>   'N',
 | 
			
		||||
			'/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
 | 
			
		||||
			'/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
 | 
			
		||||
			'/[“”«»„]/u'    =>   ' ', // Double quote
 | 
			
		||||
			'/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
 | 
			
		||||
		);
 | 
			
		||||
		return preg_replace(array_keys($utf8), array_values($utf8), $text);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function stringInsert($str,$insertstr,$pos)
 | 
			
		||||
	{
 | 
			
		||||
		$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
 | 
			
		||||
		return $str;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	* [generateGraphJson description]
 | 
			
		||||
	* @param  string $type    [line/bar]
 | 
			
		||||
	* @param  array  $data    [description]
 | 
			
		||||
	* @param  array  $options [description]
 | 
			
		||||
	* @return [type]          [description]
 | 
			
		||||
	*/
 | 
			
		||||
 | 
			
		||||
	function generateGraphJson(string $type = 'line', array $data = [], array $options = []){
 | 
			
		||||
		$array = [
 | 
			
		||||
			'type' => $type,
 | 
			
		||||
			'data' => [
 | 
			
		||||
				'datasets' => [
 | 
			
		||||
					[
 | 
			
		||||
						'data' => $data
 | 
			
		||||
					]
 | 
			
		||||
				]
 | 
			
		||||
			],
 | 
			
		||||
			'options' => [
 | 
			
		||||
				'scales' => [
 | 
			
		||||
					'xAxes' => [
 | 
			
		||||
						[
 | 
			
		||||
							'type' => 'time',
 | 
			
		||||
							'distribution' => 'linear',
 | 
			
		||||
						]
 | 
			
		||||
					],
 | 
			
		||||
					'yAxes' => [
 | 
			
		||||
						[
 | 
			
		||||
							'ticks' => [
 | 
			
		||||
								'min' => $options['min'],
 | 
			
		||||
								'max' => $options['max'],
 | 
			
		||||
								'steps' => $options['scale']
 | 
			
		||||
							]
 | 
			
		||||
						]
 | 
			
		||||
					]
 | 
			
		||||
				],
 | 
			
		||||
				'legend' => [
 | 
			
		||||
					'display' => false
 | 
			
		||||
				],
 | 
			
		||||
				'tooltips' => [
 | 
			
		||||
					'enabled' => true
 | 
			
		||||
				],
 | 
			
		||||
				'hover' => [
 | 
			
		||||
					'mode' => true
 | 
			
		||||
				]
 | 
			
		||||
			]
 | 
			
		||||
		];
 | 
			
		||||
		return json_encode($array, JSON_PRETTY_PRINT);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function ago( $datetime )
 | 
			
		||||
	{
 | 
			
		||||
		$interval = date_create('now')->diff( $datetime );
 | 
			
		||||
		$suffix = ( $interval->invert ? ' ago' : '' );
 | 
			
		||||
		if ( $v = $interval->y >= 1 ) return self::pluralize( $interval->m, 'month' ) . $suffix;
 | 
			
		||||
		if ( $v = $interval->d >= 1 ) return self::pluralize( $interval->d, 'day' ) . $suffix;
 | 
			
		||||
		if ( $v = $interval->h >= 1 ) return self::pluralize( $interval->h, 'hour' ) . $suffix;
 | 
			
		||||
		if ( $v = $interval->i >= 1 ) return self::pluralize( $interval->i, 'minute' ) . $suffix;
 | 
			
		||||
		return self::pluralize( $interval->s, 'second' ) . $suffix;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function pluralize( $count, $text )
 | 
			
		||||
	{
 | 
			
		||||
		return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function checkOperator($value1, $operator, $value2) {
 | 
			
		||||
		switch ($operator) {
 | 
			
		||||
			case '<': // Less than
 | 
			
		||||
			return $value1 < $value2;
 | 
			
		||||
			case '<=': // Less than or equal to
 | 
			
		||||
			return $value1 <= $value2;
 | 
			
		||||
			case '>': // Greater than
 | 
			
		||||
			return $value1 > $value2;
 | 
			
		||||
			case '>=': // Greater than or equal to
 | 
			
		||||
			return $value1 >= $value2;
 | 
			
		||||
			case '==': // Equal
 | 
			
		||||
			return $value1 == $value2;
 | 
			
		||||
			case '===': // Identical
 | 
			
		||||
			return $value1 === $value2;
 | 
			
		||||
			case '!==': // Not Identical
 | 
			
		||||
			return $value1 !== $value2;
 | 
			
		||||
			case '!=': // Not equal
 | 
			
		||||
			case '<>': // Not equal
 | 
			
		||||
			return $value1 != $value2;
 | 
			
		||||
			case '||': // Or
 | 
			
		||||
			case 'or': // Or
 | 
			
		||||
			return $value1 || $value2;
 | 
			
		||||
			case '&&': // And
 | 
			
		||||
			case 'and': // And
 | 
			
		||||
			return $value1 && $value2;
 | 
			
		||||
			case 'xor': // Or
 | 
			
		||||
			return $value1 xor $value2;
 | 
			
		||||
			default:
 | 
			
		||||
			return FALSE;
 | 
			
		||||
		} // end switch
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										14
									
								
								app/controllers/ExampleController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										14
									
								
								app/controllers/ExampleController.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,14 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
class ExampleController extends Controller{
 | 
			
		||||
 | 
			
		||||
	public function index(){
 | 
			
		||||
		$this->view->title = 'Example title';
 | 
			
		||||
		$this->view->render('example.phtml');
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function subpage(){
 | 
			
		||||
		echo 'subpage';
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										77
									
								
								app/controllers/automationController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										77
									
								
								app/controllers/automationController.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,77 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (isset($_POST) && !empty($_POST)){
 | 
			
		||||
	if (isset($_POST['modalFinal']) && $_POST['action'] == "add") {
 | 
			
		||||
		$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
 | 
			
		||||
 | 
			
		||||
		$value = $_POST['atSelector'];
 | 
			
		||||
		if ($_POST['atSelector'] == 'time'){
 | 
			
		||||
			  $value = $_POST['atSelectorValue'];
 | 
			
		||||
		} else if ($_POST['atSelector'] == 'atDeviceValue') {
 | 
			
		||||
			$value = json_decode($_POST['atSelectorValue']);
 | 
			
		||||
		} else if ($_POST['atSelector'] == 'inHome' || $_POST['atSelector'] == 'outHome') {
 | 
			
		||||
			$value = UserManager::getUserData('user_id');
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		$ifCode = json_encode([
 | 
			
		||||
			"type" => $_POST['atSelector'],
 | 
			
		||||
			"value" => $value,
 | 
			
		||||
		], JSON_PRETTY_PRINT);
 | 
			
		||||
		$onDays = $_POST['atDays'];
 | 
			
		||||
 | 
			
		||||
		//Debug
 | 
			
		||||
		// if (DEBUGMOD == 1) {
 | 
			
		||||
		// 	echo '<pre>';
 | 
			
		||||
		// 	echo $permissionsInJson;
 | 
			
		||||
		// 	echo $deviceId;
 | 
			
		||||
		// 	var_dump(json_decode ($permissionsInJson));
 | 
			
		||||
		// 	echo '</pre>';
 | 
			
		||||
		// 	echo '<a href="' . BASEDIR .'">CONTINUE</a>';
 | 
			
		||||
		// 	die();
 | 
			
		||||
		// }
 | 
			
		||||
 | 
			
		||||
		AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode);
 | 
			
		||||
 | 
			
		||||
		header('Location: ' . BASEURL . strtolower(basename(__FILE__, '.php')));
 | 
			
		||||
		die();
 | 
			
		||||
	} else if (isset($_POST['modalFinal']) && $_POST['action'] == "edit") {
 | 
			
		||||
		$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
 | 
			
		||||
 | 
			
		||||
		if (isset ($_POST['atDeviceValue'])) {
 | 
			
		||||
			$subDeviceId = $_POST['atDeviceValue'];
 | 
			
		||||
			$subDeviceValue = $_POST['atDeviceValueInt'];
 | 
			
		||||
			$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
 | 
			
		||||
			$subDeviceMaster = SubDeviceManager::getSubDeviceMaster($subDeviceId,$subDevice['type']);
 | 
			
		||||
 | 
			
		||||
			$device = [
 | 
			
		||||
				'deviceID' => $subDeviceMaster['device_id'],
 | 
			
		||||
				'type'=> $subDevice['type'],
 | 
			
		||||
				'value'=> $subDeviceValue,
 | 
			
		||||
			];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		$value = $_POST['atSelector'];
 | 
			
		||||
		if (isset($_POST['atTime'])){
 | 
			
		||||
				$value = $_POST['atTime'];
 | 
			
		||||
		} else if (isset($_POST['atDeviceValue'])) {
 | 
			
		||||
			$value = $device;
 | 
			
		||||
		}  else if ($_POST['atSelector'] == 'inHome' || $_POST['atSelector'] == 'outHome') {
 | 
			
		||||
			//TODO: opravit edit aby vkládal id původního uživatele
 | 
			
		||||
			$value = UserManager::getUserData('user_id');
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$value = (isset($_POST['atTime']) ? $_POST['atTime'] : (isset($_POST['atDeviceValue']) ? $device : $_POST['atSelector']));
 | 
			
		||||
		$ifCode = json_encode([
 | 
			
		||||
			"type" => $_POST['atSelector'],
 | 
			
		||||
			"value" => $value,
 | 
			
		||||
		], JSON_PRETTY_PRINT);
 | 
			
		||||
		$onDays = ($_POST['day'] != '' ? json_encode($_POST['day']) : '');
 | 
			
		||||
 | 
			
		||||
		AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode, (isset ($_POST['automation_id']) ? $_POST['automation_id'] : ""));
 | 
			
		||||
 | 
			
		||||
		header('Location: ' . BASEURL . strtolower(basename(__FILE__, '.php')));
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
							
								
								
									
										36
									
								
								app/controllers/deviceController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								app/controllers/deviceController.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,36 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (!empty ($_POST)){
 | 
			
		||||
	$deviceManager = new DeviceManager ();
 | 
			
		||||
	$subDeviceManager = new SubDeviceManager ();
 | 
			
		||||
	if (!empty ($_FILES['deviceFirmware']) && !empty ($_FILES['deviceFirmware']['tmp_name']) && !empty ($_POST['deviceId'])) {
 | 
			
		||||
		$file = $_FILES['deviceFirmware'];
 | 
			
		||||
		$deviceMac = $deviceManager->getDeviceById ($_POST['deviceId'])['mac'];
 | 
			
		||||
		$fileName = (!empty ($deviceMac) ? str_replace (":", "", $deviceMac) . ".bin" : "");
 | 
			
		||||
 | 
			
		||||
		if ($fileName != "" && file_exists ("../updater/" . $fileName)) {
 | 
			
		||||
			unlink("../updater/" . $fileName);
 | 
			
		||||
		}
 | 
			
		||||
		if ($fileName != "") {
 | 
			
		||||
			copy ($file['tmp_name'], "../updater/" . $fileName);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	if (isset ($_POST['deviceCommand'])  && !empty ($_POST['deviceId'])) {
 | 
			
		||||
		$deviceManager->edit ($_POST['deviceId'], array ('command' => $_POST['deviceCommand']));
 | 
			
		||||
	} else if (!empty ($_POST['deviceCommand'])) {
 | 
			
		||||
		$devices = $deviceManager->getAllDevices();
 | 
			
		||||
		foreach ($devices as $key => $device) {
 | 
			
		||||
			$deviceManager->edit ($device['device_id'], array ('command' => $_POST['deviceCommand']));
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	if (!empty ($_POST['deviceRoomId'])  && !empty ($_POST['deviceId'])) {
 | 
			
		||||
		$deviceManager->edit ($_POST['deviceId'], array ('room_id' => $_POST['deviceRoomId']));
 | 
			
		||||
	}
 | 
			
		||||
	if (!empty ($_POST['deviceName'])  && !empty ($_POST['deviceId'])) {
 | 
			
		||||
		$deviceManager->edit ($_POST['deviceId'], array ('name' => $_POST['deviceName']));
 | 
			
		||||
	}
 | 
			
		||||
	if (isset ($_POST['deviceHistory']) && !empty ($_POST['deviceId'])) {
 | 
			
		||||
		$subDeviceManager->editSubDevicesByDevice($_POST['deviceId'], array ('history' => $_POST['deviceHistory']));
 | 
			
		||||
	}
 | 
			
		||||
	header('Location: ' . BASEURL . str_replace(BASEDIR, "", $_SERVER['REQUEST_URI']));
 | 
			
		||||
	die();
 | 
			
		||||
}
 | 
			
		||||
@@ -1,5 +1,5 @@
 | 
			
		||||
<?php
 | 
			
		||||
global $userManager;
 | 
			
		||||
$userManager = new UserManager();
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
if (
 | 
			
		||||
@@ -15,7 +15,7 @@ if (
 | 
			
		||||
	$ota = $userManager->haveOtaEnabled($userName);
 | 
			
		||||
	if ($ota == "") {
 | 
			
		||||
		$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
 | 
			
		||||
		header('Location: ' . BASEDIR . $landingPage);
 | 
			
		||||
		header('Location: ' . BASEURL . $landingPage);
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
@@ -27,7 +27,6 @@ if (
 | 
			
		||||
	isset($_POST['otaCode']) &&
 | 
			
		||||
	$_POST['otaCode'] != ''
 | 
			
		||||
) {
 | 
			
		||||
 | 
			
		||||
	$otaCode = $_POST['otaCode'];
 | 
			
		||||
	$otaSecret = $_POST['otaSecret'];
 | 
			
		||||
 | 
			
		||||
@@ -40,7 +39,7 @@ if (
 | 
			
		||||
	$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2);    // 2 = 2*30sec clock tolerance
 | 
			
		||||
	if ($checkResult) {
 | 
			
		||||
		$landingPage = $userManager->login($userName, $userPassword, $rememberMe);
 | 
			
		||||
		header('Location: ' . BASEDIR . $landingPage);
 | 
			
		||||
		header('Location: ' . BASEURL . '/');
 | 
			
		||||
		echo 'OK';
 | 
			
		||||
	} else {
 | 
			
		||||
		echo 'FAILED';
 | 
			
		||||
							
								
								
									
										75
									
								
								app/controllers/oauthController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										75
									
								
								app/controllers/oauthController.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,75 @@
 | 
			
		||||
<?php
 | 
			
		||||
$userManager = new UserManager();
 | 
			
		||||
 | 
			
		||||
if (
 | 
			
		||||
	isset($_POST['username']) &&
 | 
			
		||||
	$_POST['username'] != '' &&
 | 
			
		||||
	isset($_POST['password']) &&
 | 
			
		||||
	$_POST['password'] != ''
 | 
			
		||||
){
 | 
			
		||||
	$ota = false;
 | 
			
		||||
	$userName = $_POST['username'];
 | 
			
		||||
	echo $_POST['username'];
 | 
			
		||||
	$userPassword = $_POST['password'];
 | 
			
		||||
	$state = $_POST["state"];
 | 
			
		||||
	$clientId = $_POST["clientId"];
 | 
			
		||||
	$ota = $userManager->haveOtaEnabled($userName);
 | 
			
		||||
	if ($ota == "") {
 | 
			
		||||
		$token = (new AuthManager)->getToken($userName,$userPassword, $clientId);
 | 
			
		||||
		if (!$token) {
 | 
			
		||||
			throw new Exception("Auth failed", 401);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$get = [
 | 
			
		||||
			"access_token"=>$token,
 | 
			
		||||
			"token_type"=>"Bearer",
 | 
			
		||||
			"state"=>$state,
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		header('Location: ' . $_POST["redirectUrl"] . '#' . http_build_query($get));
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	$_SESSION['USERNAME'] = $userName;
 | 
			
		||||
	$_SESSION['PASSWORD'] = $userPassword;
 | 
			
		||||
	$_SESSION['OTA'] = $ota;
 | 
			
		||||
	$_SESSION['STATE'] = $state;
 | 
			
		||||
	$_SESSION['REDIRECT'] = $_POST["redirectUrl"];
 | 
			
		||||
	$_SESSION['CLIENT'] = $clientId;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
} else if (
 | 
			
		||||
	isset($_POST['otaCode']) &&
 | 
			
		||||
	$_POST['otaCode'] != ''
 | 
			
		||||
) {
 | 
			
		||||
	$otaCode = $_POST['otaCode'];
 | 
			
		||||
	$otaSecret = $_POST['otaSecret'];
 | 
			
		||||
 | 
			
		||||
	$userName = $_SESSION['USERNAME'];
 | 
			
		||||
	$userPassword = $_SESSION['PASSWORD'];
 | 
			
		||||
	$ota = $_SESSION['OTA'];
 | 
			
		||||
	$oauthState = $_SESSION['STATE'];
 | 
			
		||||
	$oauthRedirect = $_SESSION['REDIRECT'];
 | 
			
		||||
	$oauthClientId = $_SESSION['CLIENT'];
 | 
			
		||||
 | 
			
		||||
	$ga = new PHPGangsta_GoogleAuthenticator();
 | 
			
		||||
	$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2);    // 2 = 2*30sec clock tolerance
 | 
			
		||||
	if ($checkResult) {
 | 
			
		||||
		$token = (new AuthManager)->getToken($userName,$userPassword, $oauthClientId);
 | 
			
		||||
		if (!$token) {
 | 
			
		||||
			throw new Exception("Auth failed", 401);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$get = [
 | 
			
		||||
			"access_token"=>$token,
 | 
			
		||||
			"token_type"=>"Bearer",
 | 
			
		||||
			"state"=>$oauthState,
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		header('Location: ' . $oauthRedirect . '#' . http_build_query($get));
 | 
			
		||||
		echo 'OK';
 | 
			
		||||
	} else {
 | 
			
		||||
		echo 'FAILED';
 | 
			
		||||
	}
 | 
			
		||||
	die();
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										28
									
								
								app/controllers/pluginsController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								app/controllers/pluginsController.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,28 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (!empty ($_POST)){
 | 
			
		||||
	if (
 | 
			
		||||
		isset ($_POST['name']) &&
 | 
			
		||||
		$_POST['name'] != '' &&
 | 
			
		||||
		!isset ($_POST['remove'])
 | 
			
		||||
	) {
 | 
			
		||||
		if ($_POST['status'] == "true") {
 | 
			
		||||
			if (file_exists ($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php")) {
 | 
			
		||||
				rename($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php", $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php");
 | 
			
		||||
			}
 | 
			
		||||
		} else {
 | 
			
		||||
			if (file_exists ($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php")) {
 | 
			
		||||
				rename($_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/' . $_POST['name'] . ".php", $_SERVER['DOCUMENT_ROOT'] . BASEDIR . 'app/plugins/!' . $_POST['name'] . ".php");
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		header('Location: ./plugins');
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if (
 | 
			
		||||
		isset ($_POST['name']) &&
 | 
			
		||||
		$_POST['name'] != '' &&
 | 
			
		||||
		isset ($_POST['remove'])
 | 
			
		||||
	) {
 | 
			
		||||
		//
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										45
									
								
								app/controllers/settingController.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										45
									
								
								app/controllers/settingController.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,45 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (isset($_POST) && !empty($_POST)){
 | 
			
		||||
	$userManager = new UserManager();
 | 
			
		||||
	if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
 | 
			
		||||
		$oldPassword = $_POST['oldPassword'];
 | 
			
		||||
		$newPassword = $_POST['newPassword1'];
 | 
			
		||||
		$newPassword2 = $_POST['newPassword2'];
 | 
			
		||||
		$userManager->changePassword($oldPassword, $newPassword, $newPassword2);
 | 
			
		||||
		header('Location: ' . BASEURL . 'logout');
 | 
			
		||||
		die();
 | 
			
		||||
	} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
 | 
			
		||||
		$userName = $_POST['userName'];
 | 
			
		||||
		$password = $_POST['userPassword'];
 | 
			
		||||
		$email = $_POST['userEmail'];
 | 
			
		||||
		$userManager->createUser($userName, $password, $email);
 | 
			
		||||
		header('Location: ' . BASEURL . 'setting');
 | 
			
		||||
		die();
 | 
			
		||||
	} else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
 | 
			
		||||
		$otaCode = $_POST['otaCode'];
 | 
			
		||||
		$otaSecret = $_POST['otaSecret'];
 | 
			
		||||
 | 
			
		||||
		$ga = new PHPGangsta_GoogleAuthenticator();
 | 
			
		||||
		$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2);    // 2 = 2*30sec clock tolerance
 | 
			
		||||
		if ($checkResult) {
 | 
			
		||||
			$userManager->setOta($otaCode, $otaSecret);
 | 
			
		||||
		}
 | 
			
		||||
		header('Location: ' . BASEURL . 'setting');
 | 
			
		||||
		die();
 | 
			
		||||
	} else if (isset ($_POST['userPermission']) && !empty ($_POST['userID'])) {
 | 
			
		||||
		$userManager->setUserDataAdmin("permission", $_POST['userPermission'], $_POST['userID']);
 | 
			
		||||
		header('Location: ' . BASEURL . 'setting');
 | 
			
		||||
		die();
 | 
			
		||||
	} else {
 | 
			
		||||
		foreach ($_POST as $key => $value) {
 | 
			
		||||
			if ($key == 'submit') continue;
 | 
			
		||||
			$settingMng = new SettingsManager();
 | 
			
		||||
			if ($settingMng->getByName($key)) {
 | 
			
		||||
				$settingMng->update($key, $value);
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		header('Location: ' . BASEURL . 'setting');
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,56 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (isset($_POST) && !empty($_POST)){
 | 
			
		||||
	if (isset($_POST['modalFinal']) && $_POST['action'] == "add") {
 | 
			
		||||
		$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
 | 
			
		||||
		$ifCode = json_encode([
 | 
			
		||||
			"type" => $_POST['atSelector'],
 | 
			
		||||
			"value" => $_POST['atSelectorValue'],
 | 
			
		||||
		], JSON_PRETTY_PRINT);
 | 
			
		||||
		$onDays = $_POST['atDays'];
 | 
			
		||||
 | 
			
		||||
		//Debug
 | 
			
		||||
		if (DEBUGMOD == 1) {
 | 
			
		||||
			echo '<pre>';
 | 
			
		||||
			echo $permissionsInJson;
 | 
			
		||||
			echo $deviceId;
 | 
			
		||||
			var_dump(json_decode ($permissionsInJson));
 | 
			
		||||
			echo '</pre>';
 | 
			
		||||
			echo '<a href="' . BASEDIR .'">CONTINUE</a>';
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode);
 | 
			
		||||
 | 
			
		||||
		header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
 | 
			
		||||
		die();
 | 
			
		||||
	} else if (isset($_POST['modalFinal']) && $_POST['action'] == "edit") {
 | 
			
		||||
		$doCode = json_encode($_POST['device'], JSON_PRETTY_PRINT);
 | 
			
		||||
 | 
			
		||||
		if (isset ($_POST['atDeviceValue'])) {
 | 
			
		||||
			$subDeviceId = $_POST['atDeviceValue'];
 | 
			
		||||
			$subDeviceValue = $_POST['atDeviceValueInt'];
 | 
			
		||||
			$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
 | 
			
		||||
			$subDeviceMaster = SubDeviceManager::getSubDeviceMaster($subDeviceId,$subDevice['type']);
 | 
			
		||||
 | 
			
		||||
			$json = json_encode([
 | 
			
		||||
				'deviceID' => $subDeviceMaster['device_id'],
 | 
			
		||||
				'type'=> $subDevice['type'],
 | 
			
		||||
				'value'=> $subDeviceValue,
 | 
			
		||||
			]);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		$_POST['atSelectorValue'] = (isset($_POST['atTime']) ? $_POST['atTime'] : (isset($_POST['atDeviceValue']) ? $json : $_POST['atSelector']));
 | 
			
		||||
		$ifCode = json_encode([
 | 
			
		||||
			"type" => $_POST['atSelector'],
 | 
			
		||||
			"value" => $_POST['atSelectorValue'],
 | 
			
		||||
		], JSON_PRETTY_PRINT);
 | 
			
		||||
		$onDays = ($_POST['day'] != '' ? json_encode($_POST['day']) : '');
 | 
			
		||||
 | 
			
		||||
		AutomationManager::create($_POST['name'], $onDays, $doCode, $ifCode, (isset ($_POST['automation_id']) ? $_POST['automation_id'] : ""));
 | 
			
		||||
 | 
			
		||||
		header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
@@ -1,13 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (isset($_POST) && !empty($_POST)){
 | 
			
		||||
 | 
			
		||||
	if (isset($_POST['modalFinal']) && $_POST['modalFinal'] != "") {
 | 
			
		||||
		$subDeviceIds = $_POST['devices'];
 | 
			
		||||
		foreach ($subDeviceIds as $subDeviceId) {
 | 
			
		||||
			DashboardManager::Add($subDeviceId);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
 | 
			
		||||
	die();
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
@@ -1,73 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (isset($_POST) && !empty($_POST)){
 | 
			
		||||
	if (isset($_POST['saveDevice']) && $_POST['saveDevice'] != "") {
 | 
			
		||||
		$deviceId = $_POST['deviceId'];
 | 
			
		||||
		$deviceName = $_POST['deviceName'];
 | 
			
		||||
		$deviceIcon = $_POST['deviceIcon'];
 | 
			
		||||
		$sleepTime = 0;
 | 
			
		||||
		if (isset($_POST['sleepTime'])) {
 | 
			
		||||
			$sleepTime = $_POST['sleepTime'];
 | 
			
		||||
		}
 | 
			
		||||
		//TODO: if device isnt on off
 | 
			
		||||
		$permissionsInJson = json_encode([
 | 
			
		||||
			(int) $_POST['permissionOwner'],
 | 
			
		||||
			(int) $_POST['permissionOther'],
 | 
			
		||||
		]);
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		$deviceOwnerUserId = $_POST['deviceOwnerUserId'];
 | 
			
		||||
		$deviceOwnerRoomId = $_POST['deviceOwnerId'];
 | 
			
		||||
 | 
			
		||||
		try {
 | 
			
		||||
			$args = array(
 | 
			
		||||
				'owner' => $deviceOwnerUserId,
 | 
			
		||||
				'name' => $deviceName,
 | 
			
		||||
				'icon' => $deviceIcon,
 | 
			
		||||
				'permission' => $permissionsInJson,
 | 
			
		||||
				'sleep_time' => $sleepTime,
 | 
			
		||||
				'room_id' => $deviceOwnerRoomId,
 | 
			
		||||
			);
 | 
			
		||||
			DeviceManager::edit($deviceId, $args);
 | 
			
		||||
		} catch (\Exception $e) {
 | 
			
		||||
			echo $e->message();
 | 
			
		||||
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		//Debug
 | 
			
		||||
		if (DEBUGMOD == 1) {
 | 
			
		||||
			echo '<pre>';
 | 
			
		||||
			echo $permissionsInJson;
 | 
			
		||||
			echo $deviceId;
 | 
			
		||||
			var_dump(json_decode ($permissionsInJson));
 | 
			
		||||
			echo '</pre>';
 | 
			
		||||
			echo '<a href="' . BASEDIR .'">CONTINUE</a>';
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	} else if (isset($_POST['approveDevice'])) {
 | 
			
		||||
		$deviceId = $_POST['deviceId'];
 | 
			
		||||
		$args = array(
 | 
			
		||||
			'approved' => 1,
 | 
			
		||||
		);
 | 
			
		||||
		DeviceManager::edit($deviceId, $args);
 | 
			
		||||
	} else if (isset($_POST['disableDevice'])) {
 | 
			
		||||
		$deviceId = $_POST['deviceId'];
 | 
			
		||||
		$args = array(
 | 
			
		||||
			'approved' => 2,
 | 
			
		||||
		);
 | 
			
		||||
		DeviceManager::edit($deviceId, $args);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	//Debug
 | 
			
		||||
	if (DEBUGMOD == 1) {
 | 
			
		||||
		echo '<pre>';
 | 
			
		||||
		var_dump($POST);
 | 
			
		||||
		echo '</pre>';
 | 
			
		||||
		echo '<a href="' . BASEDIR . '">CONTINUE</a>';
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
	header('Location: ' . BASEDIR );
 | 
			
		||||
	die();
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
@@ -1,18 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
if (isset($_POST) && !empty($_POST)){
 | 
			
		||||
	if (isset($_POST['submitFinal']) && $_POST['submitFinal'] != "") {
 | 
			
		||||
		SceneManager::create($_POST['sceneIcon'], $_POST['sceneName'], json_encode($_POST['devices']));
 | 
			
		||||
		header('Location: ' . BASEDIR . strtolower(basename(__FILE__, '.php')));
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	//Debug
 | 
			
		||||
	if (DEBUGMOD == 1) {
 | 
			
		||||
		echo '<pre>';
 | 
			
		||||
		var_dump($_POST);
 | 
			
		||||
		echo '</pre>';
 | 
			
		||||
		echo '<a href="/' . BASEDIR . strtolower(basename(__FILE__, '.php')).'">CONTINUE</a>';
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,29 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (isset($_POST) && !empty($_POST)){
 | 
			
		||||
	if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
 | 
			
		||||
		$oldPassword = $_POST['oldPassword'];
 | 
			
		||||
		$newPassword = $_POST['newPassword1'];
 | 
			
		||||
		$newPassword2 = $_POST['newPassword2'];
 | 
			
		||||
		UserManager::changePassword($oldPassword, $newPassword, $newPassword2);
 | 
			
		||||
		header('Location: ' . BASEDIR . 'logout');
 | 
			
		||||
		die();
 | 
			
		||||
	} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
 | 
			
		||||
		$userName = $_POST['userName'];
 | 
			
		||||
		$password = $_POST['userPassword'];
 | 
			
		||||
		UserManager::createUser($userName, $password);
 | 
			
		||||
		header('Location: ' . BASEDIR . 'setting');
 | 
			
		||||
		die();
 | 
			
		||||
	} else if (isset($_POST['submitEnableOta']) && $_POST['submitEnableOta'] != "") {
 | 
			
		||||
		echo $otaCode = $_POST['otaCode'];
 | 
			
		||||
		echo $otaSecret = $_POST['otaSecret'];
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		$ga = new PHPGangsta_GoogleAuthenticator();
 | 
			
		||||
		$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2);    // 2 = 2*30sec clock tolerance
 | 
			
		||||
		 if ($checkResult) {
 | 
			
		||||
			 UserManager::setOta($otaCode, $otaSecret);
 | 
			
		||||
		 }
 | 
			
		||||
		header('Location: ' . BASEDIR . 'setting');
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,17 +0,0 @@
 | 
			
		||||
<?php
 | 
			
		||||
if (isset($_POST) && !empty($_POST)){
 | 
			
		||||
	if (isset($_POST['submitPasswordChange']) && $_POST['submitPasswordChange'] != "") {
 | 
			
		||||
		$oldPassword = $_POST['oldPassword'];
 | 
			
		||||
		$newPassword = $_POST['newPassword1'];
 | 
			
		||||
		$newPassword2 = $_POST['newPassword2'];
 | 
			
		||||
		UserManager::changePassword($oldPassword, $newPassword, $newPassword2);
 | 
			
		||||
		header('Location: ' . BASEDIR . 'logout');
 | 
			
		||||
		die();
 | 
			
		||||
	} else if (isset($_POST['submitCreateUser']) && $_POST['submitCreateUser'] != "") {
 | 
			
		||||
		$userName = $_POST['userName'];
 | 
			
		||||
		$password = $_POST['userPassword'];
 | 
			
		||||
		UserManager::createUser($userName, $password);
 | 
			
		||||
		header('Location: ' . BASEDIR . 'setting');
 | 
			
		||||
		die();
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										498
									
								
								app/models/GoogleHome.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										498
									
								
								app/models/GoogleHome.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,498 @@
 | 
			
		||||
<?php
 | 
			
		||||
class GoogleHome
 | 
			
		||||
{
 | 
			
		||||
	static function sync($requestId)
 | 
			
		||||
	{
 | 
			
		||||
		$devices = [];
 | 
			
		||||
		$roomsData = RoomManager::getAllRooms();
 | 
			
		||||
		foreach ($roomsData as $roomKey => $roomData) {
 | 
			
		||||
			$devicesData = DeviceManager::getAllDevicesInRoom($roomData['room_id']);
 | 
			
		||||
			foreach ($devicesData as $deviceKey => $deviceData) {
 | 
			
		||||
				$traids = [];
 | 
			
		||||
				$attributes = [];
 | 
			
		||||
 | 
			
		||||
				//Google Compatibile Action Type
 | 
			
		||||
				$actionType = GoogleHomeDeviceTypes::getAction($deviceData['type']);
 | 
			
		||||
				if ($actionType == "") continue;
 | 
			
		||||
 | 
			
		||||
				$subDevicesData = SubDeviceManager::getAllSubDevices($deviceData['device_id']);
 | 
			
		||||
				foreach ($subDevicesData as $subDeviceKey => $subDeviceData) {
 | 
			
		||||
					$deviceTraid = GoogleHomeDeviceTypes::getTraid($subDeviceData['type']);
 | 
			
		||||
					if ($deviceTraid != "") {
 | 
			
		||||
						$traids[] = $deviceTraid;
 | 
			
		||||
					}
 | 
			
		||||
 | 
			
		||||
					$deviceAttributes = GoogleHomeDeviceTypes::getAttribute($subDeviceData['type']);
 | 
			
		||||
					if ($deviceAttributes != "") {
 | 
			
		||||
						$attributes += $deviceAttributes;
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				if ($traids < 1) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				$tempDevice = [
 | 
			
		||||
					'id' => (string) $deviceData['device_id'],
 | 
			
		||||
					'type' => $actionType,
 | 
			
		||||
					'traits' => $traids,
 | 
			
		||||
					'attributes' => $attributes,
 | 
			
		||||
					'name' => [
 | 
			
		||||
						'name' => $deviceData['name'],
 | 
			
		||||
					],
 | 
			
		||||
 | 
			
		||||
					'willReportState' => false,
 | 
			
		||||
					'roomHint' => $roomData['name']
 | 
			
		||||
				];
 | 
			
		||||
				if ($tempDevice['attributes'] == null) unset($tempDevice['attributes']);
 | 
			
		||||
 | 
			
		||||
				//traids & Attributes
 | 
			
		||||
				$devices[] = $tempDevice;
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		$response = [
 | 
			
		||||
			'requestId' => $requestId,
 | 
			
		||||
			'payload' => [
 | 
			
		||||
				'agentUserId' => '651351531531',
 | 
			
		||||
				'devices' => array_values($devices),
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		$apiLogManager = new LogManager('../logs/google-home/' . date("Y-m-d") . '.log');
 | 
			
		||||
		$apiLogManager->setLevel(LOGLEVEL);
 | 
			
		||||
		$apiLogManager->write("[API][$requestId] request response\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
		echo json_encode($response);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function query($requestId, $payload)
 | 
			
		||||
	{
 | 
			
		||||
		$devices = [];
 | 
			
		||||
		$num = 0;
 | 
			
		||||
		foreach ($payload['devices'] as $deviceId) {
 | 
			
		||||
 | 
			
		||||
			$tempDevice[$deviceId['id']] = [
 | 
			
		||||
				'online' => false,
 | 
			
		||||
				'status' => 'OFFLINE',
 | 
			
		||||
			];
 | 
			
		||||
 | 
			
		||||
			if ($subDevicesData = SubDeviceManager::getAllSubDevices($deviceId['id'])) {
 | 
			
		||||
				foreach ($subDevicesData as $key => $subDeviceData) {
 | 
			
		||||
					$lastRecord = RecordManager::getLastRecord($subDeviceData['subdevice_id']);
 | 
			
		||||
					if ($lastRecord != false && $lastRecord['execuded'] == 1) {
 | 
			
		||||
						$tempDevice[$deviceId['id']]['online'] = true;
 | 
			
		||||
						$tempDevice[$deviceId['id']]['status'] = "SUCCESS";
 | 
			
		||||
					} else {
 | 
			
		||||
						$executed = 0;
 | 
			
		||||
						$waiting = 0;
 | 
			
		||||
						foreach (RecordManager::getLastRecord($deviceId['id'], 6) as $key => $value) {
 | 
			
		||||
							if ($value['execuded'] == 1) {
 | 
			
		||||
								$executed++;
 | 
			
		||||
							} else {
 | 
			
		||||
								$waiting++;
 | 
			
		||||
							}
 | 
			
		||||
						}
 | 
			
		||||
						if ($waiting < $executed) {
 | 
			
		||||
							$tempDevice[$deviceId['id']]['online'] = true;
 | 
			
		||||
						}
 | 
			
		||||
					}
 | 
			
		||||
 | 
			
		||||
					switch ($subDeviceData['type']) {
 | 
			
		||||
						case 'temp_cont':
 | 
			
		||||
							$tempDevice[$deviceId['id']]['thermostatMode'] = 'off';
 | 
			
		||||
							if ($lastRecord['value'] != 0) {
 | 
			
		||||
								$tempDevice[$deviceId['id']]['thermostatMode'] = 'heat';
 | 
			
		||||
							}
 | 
			
		||||
							$tempDevice[$deviceId['id']]['thermostatTemperatureAmbient'] = $lastRecord['value'];
 | 
			
		||||
							$tempDevice[$deviceId['id']]['thermostatTemperatureSetpoint'] = $lastRecord['value'];
 | 
			
		||||
							break;
 | 
			
		||||
						case 'vol_cont':
 | 
			
		||||
							$tempDevice[$deviceId['id']]['currentVolume'] = $lastRecord['value'];
 | 
			
		||||
							break;
 | 
			
		||||
						case 'media_apps':
 | 
			
		||||
							$tempDevice[$deviceId['id']]['currentApplication'] = "kodi";
 | 
			
		||||
							break;
 | 
			
		||||
						case 'media_input':
 | 
			
		||||
							$tempDevice[$deviceId['id']]['currentInput'] = "pc";
 | 
			
		||||
							break;
 | 
			
		||||
						case 'media_status':
 | 
			
		||||
							$tempDevice[$deviceId['id']]['activityState'] = "ACTIVE";
 | 
			
		||||
							$tempDevice[$deviceId['id']]['playbackState'] = "PLAYING";
 | 
			
		||||
							break;
 | 
			
		||||
						case 'on/off':
 | 
			
		||||
							$tempDevice[$deviceId['id']]['on'] = ($lastRecord['value'] == 1 ? true : false);
 | 
			
		||||
							break;
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
 | 
			
		||||
			// $lastRecord = RecordManager::getLastRecord($deviceId['id']);
 | 
			
		||||
			// //var_dump($lastRecord);
 | 
			
		||||
			// if ($lastRecord['execuded'] == 1) {
 | 
			
		||||
			//  	$online = true;
 | 
			
		||||
			//  	$status = 'SUCCESS';
 | 
			
		||||
			// } else {
 | 
			
		||||
				$executed = 0;
 | 
			
		||||
				$waiting = 0;
 | 
			
		||||
				foreach (RecordManager::getLastRecord($deviceId['id'], 6) as $key => $value) {
 | 
			
		||||
					if ($value['execuded'] == 1) {
 | 
			
		||||
						$executed++;
 | 
			
		||||
					} else {
 | 
			
		||||
						$waiting++;
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				if ($waiting < $executed) {
 | 
			
		||||
					$status = "PENDING";
 | 
			
		||||
					$online = true;
 | 
			
		||||
				}
 | 
			
		||||
			// }
 | 
			
		||||
			$devices = $tempDevice;
 | 
			
		||||
			if (count($devices)> 1){
 | 
			
		||||
				$devices[] = $tempDevice;
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		$response = [
 | 
			
		||||
			'requestId' => $requestId,
 | 
			
		||||
			'payload' => [
 | 
			
		||||
				'devices' => $devices,
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
		$apiLogManager = new LogManager('../logs/google-home/' . date("Y-m-d") . '.log');
 | 
			
		||||
		$apiLogManager->write("[API][$requestId] request response\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
		$apiLogManager->setLevel(LOGLEVEL);
 | 
			
		||||
		echo json_encode($response);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function execute($requestId, $payload)
 | 
			
		||||
	{
 | 
			
		||||
		$commands = [];
 | 
			
		||||
		foreach ($payload['commands'] as $key => $command) {
 | 
			
		||||
			foreach ($command['devices'] as $key2 => $device) {
 | 
			
		||||
				$executionCommand = $command['execution'][0];
 | 
			
		||||
				if (isset($command['execution'][$key])) {
 | 
			
		||||
					$executionCommand = $command['execution'][$key];
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				$deviceType = GoogleHomeDeviceTypes::getType($executionCommand['command']);
 | 
			
		||||
				if ($subDeviceId = SubDeviceManager::getSubDeviceByMasterAndType($device['id'], $deviceType)) {
 | 
			
		||||
					$subDeviceId = $subDeviceId['subdevice_id'];
 | 
			
		||||
					switch ($executionCommand['command']) {
 | 
			
		||||
						case 'action.devices.commands.OnOff':
 | 
			
		||||
							$commands[] = self::executeSwitch($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.ThermostatTemperatureSetpoint':
 | 
			
		||||
							$commands[] = self::executeTermostatValue($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.ThermostatSetMode':
 | 
			
		||||
							$commands[] = self::executeTermostatMode($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.setVolume':
 | 
			
		||||
							$commands[] = self::executeVolume($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.appSelect':
 | 
			
		||||
							$commands[] = self::executeApp($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.SetInput':
 | 
			
		||||
							$commands[] = self::executeInput($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.mediaNext':
 | 
			
		||||
							$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.mediaPrevious':
 | 
			
		||||
							$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.mediaPause':
 | 
			
		||||
							$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.mediaResume':
 | 
			
		||||
							$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
 | 
			
		||||
						case 'action.devices.commands.mediaStop':
 | 
			
		||||
							$commands[] = self::executeMediaCont($subDeviceId, $executionCommand);
 | 
			
		||||
							break;
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		$response = [
 | 
			
		||||
			'requestId' => $requestId,
 | 
			
		||||
			'payload' => [
 | 
			
		||||
				'commands' => $commands,
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		$apiLogManager = new LogManager('../logs/google-home/' . date("Y-m-d") . '.log');
 | 
			
		||||
		$apiLogManager->setLevel(LOGLEVEL);
 | 
			
		||||
		$apiLogManager->write("[API][EXECUTE][$requestId]\n" . json_encode($response, JSON_PRETTY_PRINT), LogRecordTypes::INFO);
 | 
			
		||||
 | 
			
		||||
		echo json_encode($response);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function executeSwitch($subDeviceId, $executionCommand)
 | 
			
		||||
	{
 | 
			
		||||
		$value = 0;
 | 
			
		||||
		$status = 'OFFLINE';
 | 
			
		||||
		$online = false;
 | 
			
		||||
 | 
			
		||||
		if ($executionCommand['params']['on']) $value = 1;
 | 
			
		||||
 | 
			
		||||
		RecordManager::createWithSubId($subDeviceId, $value, 'google');
 | 
			
		||||
 | 
			
		||||
		$executed = 0;
 | 
			
		||||
		$waiting = 0;
 | 
			
		||||
		foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
 | 
			
		||||
			if ($value['execuded'] == 1) {
 | 
			
		||||
				$executed++;
 | 
			
		||||
			} else {
 | 
			
		||||
				$waiting++;
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if ($waiting < $executed) {
 | 
			
		||||
			$status = "PENDING";
 | 
			
		||||
			$online = true;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
 | 
			
		||||
		$commandTemp = [
 | 
			
		||||
			'ids' => [(string) $deviceId],
 | 
			
		||||
			'status' => $status,
 | 
			
		||||
			'states' => [
 | 
			
		||||
				'on' => $executionCommand['params']['on'],
 | 
			
		||||
				'online' => $online,
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
		return $commandTemp;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function executeTermostatValue($subDeviceId, $executionCommand)
 | 
			
		||||
	{
 | 
			
		||||
		$value = 0;
 | 
			
		||||
		$status = 'OFFLINE';
 | 
			
		||||
		$online = false;
 | 
			
		||||
 | 
			
		||||
		if (isset($executionCommand['params']['thermostatTemperatureSetpoint'])) {
 | 
			
		||||
			$value = $executionCommand['params']['thermostatTemperatureSetpoint'];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		RecordManager::createWithSubId($subDeviceId, $value, 'google');
 | 
			
		||||
 | 
			
		||||
		$executed = 0;
 | 
			
		||||
		$waiting = 0;
 | 
			
		||||
		foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $lastValue) {
 | 
			
		||||
			if ($lastValue['execuded'] == 1) {
 | 
			
		||||
				$executed++;
 | 
			
		||||
			} else {
 | 
			
		||||
				$waiting++;
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if ($waiting < $executed) {
 | 
			
		||||
			$status = "PENDING";
 | 
			
		||||
			$online = true;;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
 | 
			
		||||
		$commandTemp = [
 | 
			
		||||
			'ids' => [(string) $deviceId],
 | 
			
		||||
			'status' => $status,
 | 
			
		||||
			'states' => [
 | 
			
		||||
				'thermostatMode' => 'heat',
 | 
			
		||||
				'thermostatTemperatureSetpoint' => $value,
 | 
			
		||||
				'thermostatTemperatureAmbient' => $value,
 | 
			
		||||
				'online' => $online,
 | 
			
		||||
				//ambient z dalšího zenzoru v roomu
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
		return $commandTemp;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function executeTermostatMode($subDeviceId, $executionCommand)
 | 
			
		||||
	{
 | 
			
		||||
		$mode = "off";
 | 
			
		||||
		$value = 0;
 | 
			
		||||
		$status = 'OFFLINE';
 | 
			
		||||
		$online = false;
 | 
			
		||||
 | 
			
		||||
		if (isset($executionCommand['params']['thermostatMode']) && $executionCommand['params']['thermostatMode'] != 'off') {
 | 
			
		||||
			$mode = $executionCommand['params']['thermostatMode'];
 | 
			
		||||
			$value = RecordManager::getLastRecordNotNull($subDeviceId)['value'];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		RecordManager::createWithSubId($subDeviceId, $value, 'google');
 | 
			
		||||
 | 
			
		||||
		$executed = 0;
 | 
			
		||||
		$waiting = 0;
 | 
			
		||||
		foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
 | 
			
		||||
			if ($value['execuded'] == 1) {
 | 
			
		||||
				$executed++;
 | 
			
		||||
			} else {
 | 
			
		||||
				$waiting++;
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if ($waiting < $executed) {
 | 
			
		||||
			$status = "PENDING";
 | 
			
		||||
			$online = true;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
 | 
			
		||||
		$commandTemp = [
 | 
			
		||||
			'ids' => [(string) $deviceId],
 | 
			
		||||
			'status' => $status,
 | 
			
		||||
			'states' => [
 | 
			
		||||
				'thermostatMode' => $mode,
 | 
			
		||||
				'online' => $online,
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		return $commandTemp;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function executeVolume($subDeviceId, $executionCommand)
 | 
			
		||||
	{
 | 
			
		||||
		//echo $executionCommand['params']['volumeLevel'];
 | 
			
		||||
		$status = 'OFFLINE';
 | 
			
		||||
		$online = false;
 | 
			
		||||
 | 
			
		||||
		$currentVolume = RecordManager::getLastRecord($subDeviceId)['value'];
 | 
			
		||||
 | 
			
		||||
		if (isset($executionCommand['params']['volumeLevel'])) {
 | 
			
		||||
			RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['volumeLevel']);
 | 
			
		||||
			$executed = 0;
 | 
			
		||||
			$waiting = 0;
 | 
			
		||||
			foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
 | 
			
		||||
				if ($value['execuded'] == 1) {
 | 
			
		||||
					$executed++;
 | 
			
		||||
				} else {
 | 
			
		||||
					$waiting++;
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
			if ($waiting < $executed) {
 | 
			
		||||
				$status = "PENDING";
 | 
			
		||||
				$online = true;
 | 
			
		||||
				$currentVolume = $executionCommand['params']['volumeLevel'];
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
 | 
			
		||||
		$commandTemp = [
 | 
			
		||||
			'ids' => [(string) $deviceId],
 | 
			
		||||
			'status' => $status,
 | 
			
		||||
			'states' => [
 | 
			
		||||
				'currentVolume' => $currentVolume,
 | 
			
		||||
				'online' => $online,
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		return $commandTemp;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function executeApp($subDeviceId, $executionCommand)
 | 
			
		||||
	{
 | 
			
		||||
		//echo $executionCommand['params']['newApplication'];
 | 
			
		||||
		$status = 'OFFLINE';
 | 
			
		||||
		$online = false;
 | 
			
		||||
 | 
			
		||||
		$currentApplication = RecordManager::getLastRecord($subDeviceId)['value'];
 | 
			
		||||
 | 
			
		||||
		if (isset($executionCommand['params']['newApplication'])) {
 | 
			
		||||
			RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['newApplication']);
 | 
			
		||||
			$executed = 0;
 | 
			
		||||
			$waiting = 0;
 | 
			
		||||
			foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
 | 
			
		||||
				if ($value['execuded'] == 1) {
 | 
			
		||||
					$executed++;
 | 
			
		||||
				} else {
 | 
			
		||||
					$waiting++;
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
			if ($waiting < $executed) {
 | 
			
		||||
				$status = "PENDING";
 | 
			
		||||
				$online = true;
 | 
			
		||||
				$currentApplication = $executionCommand['params']['newApplication'];
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
 | 
			
		||||
		$commandTemp = [
 | 
			
		||||
			'ids' => [(string) $deviceId],
 | 
			
		||||
			'status' => $status,
 | 
			
		||||
			'states' => [
 | 
			
		||||
				'currentApplication' => $currentApplication,
 | 
			
		||||
				'online' => $online,
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		return $commandTemp;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function executeInput($subDeviceId, $executionCommand)
 | 
			
		||||
	{
 | 
			
		||||
		//echo $executionCommand['params']['newInput'];
 | 
			
		||||
		$status = 'OFFLINE';
 | 
			
		||||
		$online = false;
 | 
			
		||||
 | 
			
		||||
		$currentInput = RecordManager::getLastRecord($subDeviceId)['value'];
 | 
			
		||||
 | 
			
		||||
		if (isset($executionCommand['params']['newInput'])) {
 | 
			
		||||
			RecordManager::createWithSubId($subDeviceId, $executionCommand['params']['newInput']);
 | 
			
		||||
			$executed = 0;
 | 
			
		||||
			$waiting = 0;
 | 
			
		||||
			foreach (RecordManager::getLastRecord($subDeviceId, 4) as $key => $value) {
 | 
			
		||||
				if ($value['execuded'] == 1) {
 | 
			
		||||
					$executed++;
 | 
			
		||||
				} else {
 | 
			
		||||
					$waiting++;
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
			if ($waiting < $executed) {
 | 
			
		||||
				$status = "PENDING";
 | 
			
		||||
				$online = true;
 | 
			
		||||
				$currentInput = $executionCommand['params']['newInput'];
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
 | 
			
		||||
		$commandTemp = [
 | 
			
		||||
			'ids' => [(string) $deviceId],
 | 
			
		||||
			'status' => $status,
 | 
			
		||||
			'states' => [
 | 
			
		||||
				'currentInput' => $currentInput,
 | 
			
		||||
				'online' => $online,
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		return $commandTemp;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function executeMediaCont($subDeviceId, $executionCommand)
 | 
			
		||||
	{
 | 
			
		||||
		$status = 'SUCCESS';
 | 
			
		||||
		$online = true;
 | 
			
		||||
 | 
			
		||||
		$deviceId = SubDeviceManager::getSubDeviceMaster($subDeviceId)['device_id'];
 | 
			
		||||
		$commandTemp = [
 | 
			
		||||
			'ids' => [(string) $deviceId],
 | 
			
		||||
			'status' => $status,
 | 
			
		||||
			'states' => [
 | 
			
		||||
				'online' => $online,
 | 
			
		||||
			],
 | 
			
		||||
		];
 | 
			
		||||
 | 
			
		||||
		return $commandTemp;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,13 +1,13 @@
 | 
			
		||||
<?php
 | 
			
		||||
class Partial{
 | 
			
		||||
	var $assignedValues = [];
 | 
			
		||||
	var $partBuffer;
 | 
			
		||||
	var $path;
 | 
			
		||||
	var $debug;
 | 
			
		||||
	private $assignedValues = [];
 | 
			
		||||
	private $partBuffer;
 | 
			
		||||
	private $path;
 | 
			
		||||
	private $debug;
 | 
			
		||||
 | 
			
		||||
	function __construct($path = "", $debug = false) {
 | 
			
		||||
		$this->debug = $debug;
 | 
			
		||||
		if (!empty('app/templates/part/' . $path . '.phtml') && file_exists('app/templates/part/' . $path . '.phtml')) {
 | 
			
		||||
		if (!empty('../app/views/templates/part/' . $path . '.phtml') && file_exists('../app/views/templates/part/' . $path . '.phtml')) {
 | 
			
		||||
			$this->path = $path;
 | 
			
		||||
		} else {
 | 
			
		||||
			echo '<pre>';
 | 
			
		||||
@@ -29,6 +29,6 @@ class Partial{
 | 
			
		||||
			extract($this->assignedValues);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		require('app/templates/part/' . $this->path . '.phtml');
 | 
			
		||||
		require('../app/views/templates/part/' . $this->path . '.phtml');
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										217
									
								
								app/models/Utilities.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										217
									
								
								app/models/Utilities.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,217 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 *
 | 
			
		||||
 */
 | 
			
		||||
class Utilities
 | 
			
		||||
{
 | 
			
		||||
	static function cleanString($text)
 | 
			
		||||
	{
 | 
			
		||||
		$utf8 = array(
 | 
			
		||||
			'/[áàâãªä]/u'   =>   'a',
 | 
			
		||||
			'/[ÁÀÂÃÄ]/u'    =>   'A',
 | 
			
		||||
			'/[ÍÌÎÏ]/u'     =>   'I',
 | 
			
		||||
			'/[íìîï]/u'     =>   'i',
 | 
			
		||||
			'/[ěéèêë]/u'     =>   'e',
 | 
			
		||||
			'/[ĚÉÈÊË]/u'     =>   'E',
 | 
			
		||||
			'/[óòôõºö]/u'   =>   'o',
 | 
			
		||||
			'/[ÓÒÔÕÖ]/u'    =>   'O',
 | 
			
		||||
			'/[úùûü]/u'     =>   'u',
 | 
			
		||||
			'/[ÚÙÛÜ]/u'     =>   'U',
 | 
			
		||||
			'/Š/'     		=>   'S',
 | 
			
		||||
			'/š/'     		=>   's',
 | 
			
		||||
			'/Č/'     		=>   'C',
 | 
			
		||||
			'/č/'     		=>   'c',
 | 
			
		||||
			'/ř/'     		=>   'r',
 | 
			
		||||
			'/Ř/'     		=>   'R',
 | 
			
		||||
			'/Ý/'     		=>   'Y',
 | 
			
		||||
			'/ý/'     		=>   'y',
 | 
			
		||||
			'/ç/'           =>   'c',
 | 
			
		||||
			'/Ç/'           =>   'C',
 | 
			
		||||
			'/ñ/'           =>   'n',
 | 
			
		||||
			'/Ñ/'           =>   'N',
 | 
			
		||||
			'/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
 | 
			
		||||
			'/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
 | 
			
		||||
			'/[“”«»„]/u'    =>   ' ', // Double quote
 | 
			
		||||
			'/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
 | 
			
		||||
		);
 | 
			
		||||
		return preg_replace(array_keys($utf8), array_values($utf8), $text);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function stringInsert($str, $insertstr, $pos)
 | 
			
		||||
	{
 | 
			
		||||
		$str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
 | 
			
		||||
		return $str;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * [generateGraphJson description]
 | 
			
		||||
	 * @param  string $type    [line/bar]
 | 
			
		||||
	 * @param  array  $data    [description]
 | 
			
		||||
	 * @param  array  $options [description]
 | 
			
		||||
	 * @return [type]          [description]
 | 
			
		||||
	 */
 | 
			
		||||
 | 
			
		||||
	static function generateGraphJson(string $type = 'line', array $data = [], array $options = [])
 | 
			
		||||
	{
 | 
			
		||||
		$array = [
 | 
			
		||||
			'type' => $type,
 | 
			
		||||
			'data' => [
 | 
			
		||||
				'datasets' => [
 | 
			
		||||
					[
 | 
			
		||||
						'data' => $data,
 | 
			
		||||
						'borderColor' => "#d4def7",
 | 
			
		||||
						'backgroundColor' => "#d4def7"
 | 
			
		||||
					]
 | 
			
		||||
				]
 | 
			
		||||
			],
 | 
			
		||||
			'options' => [
 | 
			
		||||
				'scales' => [
 | 
			
		||||
					'xAxes' => [
 | 
			
		||||
						[
 | 
			
		||||
							'type' => 'time',
 | 
			
		||||
							'distribution' => 'linear',
 | 
			
		||||
						]
 | 
			
		||||
					],
 | 
			
		||||
					'yAxes' => [
 | 
			
		||||
						[
 | 
			
		||||
							'ticks' => [
 | 
			
		||||
								'min' => $options['min'],
 | 
			
		||||
								'max' => $options['max'],
 | 
			
		||||
								'steps' => $options['scale']
 | 
			
		||||
							]
 | 
			
		||||
						]
 | 
			
		||||
					]
 | 
			
		||||
				],
 | 
			
		||||
				'legend' => [
 | 
			
		||||
					'display' => false
 | 
			
		||||
				],
 | 
			
		||||
				'tooltips' => [
 | 
			
		||||
					'enabled' => true
 | 
			
		||||
				],
 | 
			
		||||
				'hover' => [
 | 
			
		||||
					'mode' => true
 | 
			
		||||
				]
 | 
			
		||||
			]
 | 
			
		||||
		];
 | 
			
		||||
		return json_encode($array, JSON_PRETTY_PRINT);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function ago($datetime)
 | 
			
		||||
	{
 | 
			
		||||
		$interval = date_create('now')->diff($datetime);
 | 
			
		||||
		$suffix = ($interval->invert ? ' ago' : '');
 | 
			
		||||
		if ($v = $interval->y >= 1) return self::pluralize($interval->m, 'month') . $suffix;
 | 
			
		||||
		if ($v = $interval->d >= 1) return self::pluralize($interval->d, 'day') . $suffix;
 | 
			
		||||
		if ($v = $interval->h >= 1) return self::pluralize($interval->h, 'hour') . $suffix;
 | 
			
		||||
		if ($v = $interval->i >= 1) return self::pluralize($interval->i, 'minute') . $suffix;
 | 
			
		||||
		return self::pluralize($interval->s, 'second') . $suffix;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function pluralize($count, $text)
 | 
			
		||||
	{
 | 
			
		||||
		return $count . (($count == 1) ? (" $text") : (" ${text}s"));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function checkOperator($value1, $operator, $value2)
 | 
			
		||||
	{
 | 
			
		||||
		switch ($operator) {
 | 
			
		||||
			case '<': // Less than
 | 
			
		||||
				return $value1 < $value2;
 | 
			
		||||
			case '<=': // Less than or equal to
 | 
			
		||||
				return $value1 <= $value2;
 | 
			
		||||
			case '>': // Greater than
 | 
			
		||||
				return $value1 > $value2;
 | 
			
		||||
			case '>=': // Greater than or equal to
 | 
			
		||||
				return $value1 >= $value2;
 | 
			
		||||
			case '==': // Equal
 | 
			
		||||
				return ($value1 == $value2);
 | 
			
		||||
			case '===': // Identical
 | 
			
		||||
				return $value1 === $value2;
 | 
			
		||||
			case '!==': // Not Identical
 | 
			
		||||
				return $value1 !== $value2;
 | 
			
		||||
			case '!=': // Not equal
 | 
			
		||||
			case '<>': // Not equal
 | 
			
		||||
				return $value1 != $value2;
 | 
			
		||||
			case '||': // Or
 | 
			
		||||
			case 'or': // Or
 | 
			
		||||
				return $value1 || $value2;
 | 
			
		||||
			case '&&': // And
 | 
			
		||||
			case 'and': // And
 | 
			
		||||
				return $value1 && $value2;
 | 
			
		||||
			case 'xor': // Or
 | 
			
		||||
				return $value1 xor $value2;
 | 
			
		||||
			default:
 | 
			
		||||
				return FALSE;
 | 
			
		||||
		} // end switch
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function CallAPI($method, $url, $data = false)
 | 
			
		||||
	{
 | 
			
		||||
		$curl = curl_init();
 | 
			
		||||
 | 
			
		||||
		switch ($method) {
 | 
			
		||||
			case "POST":
 | 
			
		||||
				curl_setopt($curl, CURLOPT_POST, 1);
 | 
			
		||||
 | 
			
		||||
				if ($data)
 | 
			
		||||
					curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
 | 
			
		||||
				break;
 | 
			
		||||
			case "PUT":
 | 
			
		||||
				curl_setopt($curl, CURLOPT_PUT, 1);
 | 
			
		||||
				break;
 | 
			
		||||
			default:
 | 
			
		||||
				if ($data)
 | 
			
		||||
					$url = sprintf("%s?%s", $url, http_build_query($data));
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		// Optional Authentication:
 | 
			
		||||
		curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 | 
			
		||||
		//curl_setopt($curl, CURLOPT_USERPWD, "username:password");
 | 
			
		||||
 | 
			
		||||
		curl_setopt($curl, CURLOPT_URL, $url);
 | 
			
		||||
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 | 
			
		||||
 | 
			
		||||
		$result = curl_exec($curl);
 | 
			
		||||
 | 
			
		||||
		curl_close($curl);
 | 
			
		||||
 | 
			
		||||
		return $result;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Sort Array by keys
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param array $data
 | 
			
		||||
	 * @param [type] $key
 | 
			
		||||
	 * @param string $operator ('asc'/'desc')
 | 
			
		||||
	 * @return void
 | 
			
		||||
	 */
 | 
			
		||||
	static function sortArrayByKey($data = [], $key, $operator = "asc")
 | 
			
		||||
	{
 | 
			
		||||
		if ($operator == "asc") {
 | 
			
		||||
			uasort($data, function ($a, $b) use ($key) {
 | 
			
		||||
				$SortA = $a[$key];
 | 
			
		||||
				$SortB = $b[$key];
 | 
			
		||||
				if ($key == "room_id") {
 | 
			
		||||
					$SortA = RoomManager::getRoomName($SortA);
 | 
			
		||||
					$SortB = RoomManager::getRoomName($SortB);
 | 
			
		||||
				}
 | 
			
		||||
				if ($SortA == $SortB) return 0;
 | 
			
		||||
				return ($SortA < $SortB) ? -1 : 1;
 | 
			
		||||
			});
 | 
			
		||||
		} else {
 | 
			
		||||
			uasort($data, function ($a, $b) use ($key) {
 | 
			
		||||
				$SortA = $a[$key];
 | 
			
		||||
				$SortB = $b[$key];
 | 
			
		||||
				if ($key == "room_id") {
 | 
			
		||||
					$SortA = RoomManager::getRoomName($SortA);
 | 
			
		||||
					$SortB = RoomManager::getRoomName($SortB);
 | 
			
		||||
				}
 | 
			
		||||
				if ($SortA == $SortB) return 0;
 | 
			
		||||
				return ($SortA > $SortB) ? -1 : 1;
 | 
			
		||||
			});
 | 
			
		||||
		}
 | 
			
		||||
		return $data;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										70
									
								
								app/models/managers/AuthManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										70
									
								
								app/models/managers/AuthManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,70 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
class AuthManager {
 | 
			
		||||
	public function getToken($username, $password, $userAgent = null){
 | 
			
		||||
		if ($userAgent == null) {
 | 
			
		||||
			$userAgent = $_SERVER['HTTP_USER_AGENT'];
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$userManager = new UserManager();
 | 
			
		||||
		if ($username != '' || $password != ''){
 | 
			
		||||
			$userLogedIn = $userManager->loginNew($username, $password);
 | 
			
		||||
 | 
			
		||||
			if ($userLogedIn != false){
 | 
			
		||||
				// Create token header as a JSON string
 | 
			
		||||
				$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
 | 
			
		||||
				// Create token payload as a JSON string
 | 
			
		||||
				$payload = json_encode([
 | 
			
		||||
					'user_id' => $userLogedIn,
 | 
			
		||||
					'exp' => date('Y-m-d H:i:s',strtotime("+90 Days")),
 | 
			
		||||
					'iat' => date('Y-m-d H:i:s',time()),
 | 
			
		||||
			  ]);
 | 
			
		||||
				// Encode Header to Base64Url String
 | 
			
		||||
				$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
 | 
			
		||||
				// Encode Payload to Base64Url String
 | 
			
		||||
				$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
 | 
			
		||||
				// Create Signature Hash
 | 
			
		||||
				$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, 'abC123!', true);
 | 
			
		||||
				// Encode Signature to Base64Url String
 | 
			
		||||
				$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
 | 
			
		||||
				// Create JWT
 | 
			
		||||
				$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
				$token = [
 | 
			
		||||
					'user_id' => $userLogedIn,
 | 
			
		||||
					'user_agent' => $userAgent,
 | 
			
		||||
					'token' => $jwt,
 | 
			
		||||
					'expire' => date('Y-m-d H:i:s',strtotime("+90 Days")),
 | 
			
		||||
					'issued' => date('Y-m-d H:i:s',time()),
 | 
			
		||||
				];
 | 
			
		||||
				if (Db::add ('tokens', $token)){
 | 
			
		||||
					return $jwt;
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		return false;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function deleteToken($token){
 | 
			
		||||
		Db::command ('DELETE FROM tokens WHERE token=?', array ($token));
 | 
			
		||||
		return true;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function validateToken($token){
 | 
			
		||||
		list($type, $hash) = explode(' ', $token);
 | 
			
		||||
		$tokens = Db::loadAll('SELECT * FROM tokens WHERE token = ? AND expire >= CURRENT_TIMESTAMP AND blocked = 0;', array($hash));
 | 
			
		||||
		if ($type == 'Bearer' && count($tokens) == 1) {
 | 
			
		||||
			return true;
 | 
			
		||||
		} else if (count($tokens) == 0) {
 | 
			
		||||
			return false;
 | 
			
		||||
		};
 | 
			
		||||
		return false;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getUserId($bearer){
 | 
			
		||||
		$token = explode(' ',  $bearer)[1];
 | 
			
		||||
		$userid = Db::loadOne('SELECT user_id FROM tokens WHERE token = ? AND expire >= CURRENT_TIMESTAMP AND blocked = 0;', array($token))['user_id'];
 | 
			
		||||
		return $userid;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -3,23 +3,25 @@
 | 
			
		||||
class AutomationManager{
 | 
			
		||||
	public static $automation;
 | 
			
		||||
 | 
			
		||||
	public function remove($automationId) {
 | 
			
		||||
	public static function remove($automationId) {
 | 
			
		||||
		return Db::command ('DELETE FROM automation WHERE automation_id=?', array ($automationId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function deactive($automationId) {
 | 
			
		||||
		$automation = Db::loadOne ("SELECT * FROM automation WHERE automation_id=?" , array ($automationId));
 | 
			
		||||
		$flipedValue = ($automation['active'] == 1 ? 0 : 1);
 | 
			
		||||
		return Db::command ('UPDATE automation SET active = ? WHERE automation_id=?', array ($flipedValue,$automationId));
 | 
			
		||||
	public static function deactive($automationId) {
 | 
			
		||||
		$automation = self::getById($automationId,["enabled"]);
 | 
			
		||||
		$flipedValue = ($automation['enabled'] == 1 ? 0 : 1);
 | 
			
		||||
		return Db::command ('UPDATE automation SET enabled = ? WHERE automation_id=?', array ($flipedValue,$automationId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function restart($automationId) {
 | 
			
		||||
	public static function restart($automationId) {
 | 
			
		||||
		return Db::command ('UPDATE automation SET executed = 0 WHERE automation_id=?', array ($automationId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function create ($name, $onDays, $doCode, $ifCode, $automationId = "") {
 | 
			
		||||
	public static function create ($name, $onDays, $doCode, $ifCode, $automationId = "") {
 | 
			
		||||
		$userId = UserManager::getUserData('user_id');
 | 
			
		||||
		$scene = array (
 | 
			
		||||
			'name' => $name,
 | 
			
		||||
			'owner_id' => $userId,
 | 
			
		||||
			'on_days' => $onDays,
 | 
			
		||||
			'if_something' => $ifCode,
 | 
			
		||||
			'do_something' => $doCode,
 | 
			
		||||
@@ -32,19 +34,24 @@ class AutomationManager{
 | 
			
		||||
			}
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			return false;
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getAll(){
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM automation");
 | 
			
		||||
	public static function getAll($collums = ['*']){
 | 
			
		||||
		return Db::loadAll ("SELECT ". implode("," , $collums)." FROM automation");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getById($automationId, $collums = ['*']){
 | 
			
		||||
		return Db::loadOne("SELECT ". implode("," , $collums)." FROM automation WHERE automation_id = ?", [$automationId]);
 | 
			
		||||
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function executeAll(){
 | 
			
		||||
	public static function executeAll(){
 | 
			
		||||
		global $logManager;
 | 
			
		||||
 | 
			
		||||
		$automations = Db::loadAll ("SELECT * FROM automation");
 | 
			
		||||
		/*$automations = Db::loadAll ("SELECT * FROM automation");
 | 
			
		||||
		$dayNameNow = strtolower (date('D', time()));
 | 
			
		||||
 | 
			
		||||
		foreach ($automations as $automation) {
 | 
			
		||||
@@ -77,9 +84,21 @@ class AutomationManager{
 | 
			
		||||
						}
 | 
			
		||||
 | 
			
		||||
					} else if ($onValue['type'] == 'outHome') {
 | 
			
		||||
 | 
			
		||||
						//TODO: Add Ovner to automation
 | 
			
		||||
						$userHomeStatus = UserManager::getUserData('at_home', $onValue['value']);
 | 
			
		||||
						if ($userHomeStatus == 'false' && $automation['executed'] == 0) {
 | 
			
		||||
							$run = true;
 | 
			
		||||
						} else if ($userHomeStatus == 'true' &&  $automation['executed'] == 1) {
 | 
			
		||||
							$restart = true;
 | 
			
		||||
						}
 | 
			
		||||
					} else if ($onValue['type'] == 'inHome') {
 | 
			
		||||
 | 
			
		||||
						//TODO: Add Ovner to automation
 | 
			
		||||
						$userHomeStatus = UserManager::getUserData('at_home', $onValue['value']);
 | 
			
		||||
						if ($userHomeStatus == 'true' && $automation['executed'] == 0) {
 | 
			
		||||
							$run = true;
 | 
			
		||||
						} else if ($userHomeStatus == 'false' &&  $automation['executed'] == 1) {
 | 
			
		||||
							$restart = true;
 | 
			
		||||
						}
 | 
			
		||||
					} else if ($onValue['type'] == 'noOneHome') {
 | 
			
		||||
						$users = UserManager::getUsers();
 | 
			
		||||
						$membersHome = 0;
 | 
			
		||||
@@ -106,6 +125,18 @@ class AutomationManager{
 | 
			
		||||
						} else if ($membersHome > 0 && $automation['executed'] == 0){
 | 
			
		||||
							$run = true;
 | 
			
		||||
						}
 | 
			
		||||
					} else if ($onValue['type'] == 'atDeviceValue') {
 | 
			
		||||
 | 
			
		||||
						$subDeviceId = SubDeviceManager::getSubDeviceByMaster($onValue['value']['deviceID'], $onValue['value']['type'])["subdevice_id"];
 | 
			
		||||
						$lastValue = RecordManager::getLastRecord($subDeviceId);
 | 
			
		||||
 | 
			
		||||
						if ($lastValue['value'] == $onValue['value']['value'] && $automation['executed'] == 0) {
 | 
			
		||||
							$run = true;
 | 
			
		||||
 | 
			
		||||
						} else if ($lastValue['value'] != $onValue['value']['value'] && $automation['executed'] == 1){
 | 
			
		||||
							$restart = true;
 | 
			
		||||
 | 
			
		||||
						}
 | 
			
		||||
					}
 | 
			
		||||
 | 
			
		||||
					//finalization
 | 
			
		||||
@@ -120,18 +151,23 @@ class AutomationManager{
 | 
			
		||||
						$subscribers = NotificationManager::getSubscription();
 | 
			
		||||
						$i = 0;
 | 
			
		||||
 | 
			
		||||
						$notificationMng = new NotificationManager;
 | 
			
		||||
						$notificationData = [
 | 
			
		||||
							'title' => 'Automatization',
 | 
			
		||||
							'body' => 'Automatization '.$automation['name']." was just executed",
 | 
			
		||||
							'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
 | 
			
		||||
						];
 | 
			
		||||
 | 
			
		||||
						if ($notificationData != []) {
 | 
			
		||||
							$subscribers = $notificationMng::getSubscription();
 | 
			
		||||
							foreach ($subscribers as $key => $subscriber) {
 | 
			
		||||
							$logManager->write("[NOTIFICATION] SENDING NOTIFICATION TO" . $subscriber['id'] . " was executed" . $i);
 | 
			
		||||
							$title = 'Automatization '.$automation['name']." was just executed";
 | 
			
		||||
							$notification = new Notification(SERVERKEY);
 | 
			
		||||
							$notification->to($subscriber['token']);
 | 
			
		||||
							$notification->notification($title, ''  , '', '');
 | 
			
		||||
							$notification->send();
 | 
			
		||||
							$notification = null;
 | 
			
		||||
								$logManager->write("[NOTIFICATION/AUTOOMATION] SENDING TO" . $subscriber['id'] . " ");
 | 
			
		||||
								$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
 | 
			
		||||
							}
 | 
			
		||||
						}
 | 
			
		||||
 | 
			
		||||
						$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was executed");
 | 
			
		||||
						Db::edit('automation', array('executed' => 1), 'WHERE automation_id = ?', array($automation['automation_id']));
 | 
			
		||||
						Db::edit('automation', array('executed' => 1, 'execution_time' => date("Y-m-d H:i:s")), 'WHERE automation_id = ?', array($automation['automation_id']));
 | 
			
		||||
					} else if ($restart) {
 | 
			
		||||
						$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was restarted");
 | 
			
		||||
						Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
 | 
			
		||||
@@ -139,6 +175,6 @@ class AutomationManager{
 | 
			
		||||
					Db::edit('automation', array('locked' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		}*/
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										129
									
								
								app/models/managers/ChartManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										129
									
								
								app/models/managers/ChartManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,129 @@
 | 
			
		||||
<?php
 | 
			
		||||
class ChartScale{
 | 
			
		||||
	const HOUR = 'info';
 | 
			
		||||
	const DAY = 'warning';
 | 
			
		||||
	const MONTH = 'warning';
 | 
			
		||||
	const YEAR = 'error';
 | 
			
		||||
}
 | 
			
		||||
class ChartManager{
 | 
			
		||||
	function generateChart($data, $min = 0, $max = 100) {
 | 
			
		||||
 | 
			
		||||
		echo '<br>Aktuální Hodnota: '.$data[0]['value'];
 | 
			
		||||
		echo "<style>
 | 
			
		||||
		.sloupec {
 | 
			
		||||
			border-top: solid 2px red;
 | 
			
		||||
		}
 | 
			
		||||
		</style>";
 | 
			
		||||
		echo '<div class=graph>';
 | 
			
		||||
		echo '<div class="posuv " graf-max="'.$max.'" graf-min='.$min.'>';
 | 
			
		||||
		for ($valuesRow = 0; $valuesRow < count($data); $valuesRow++) {
 | 
			
		||||
			$row = $data[$valuesRow];
 | 
			
		||||
 | 
			
		||||
			echo '<div class="sloupec " name="sloupec" value="' . $row['value'] . '" data-toggle="tooltip" title=""></div>';
 | 
			
		||||
		}
 | 
			
		||||
		echo '</div>';
 | 
			
		||||
		echo '</div>';
 | 
			
		||||
		echo '<script src="./include/js/chartDrwer.js"></script>';
 | 
			
		||||
		echo 'Poslední Update: ';
 | 
			
		||||
 | 
			
		||||
		echo '<style>
 | 
			
		||||
		.graph {
 | 
			
		||||
			width: 100%;
 | 
			
		||||
			overflow: hidden;
 | 
			
		||||
 | 
			
		||||
			margin-top: auto;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
		.posuv {
 | 
			
		||||
			display: flex;
 | 
			
		||||
			height: 200px;
 | 
			
		||||
			background-image: url(./img/graph.png);
 | 
			
		||||
			padding: 20px;
 | 
			
		||||
			background-repeat: repeat;
 | 
			
		||||
			border-bottom: 1px solid black;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		.sloupec {
 | 
			
		||||
			border-top: solid 2px blue;
 | 
			
		||||
			background-color: grey;
 | 
			
		||||
			float: left;
 | 
			
		||||
			margin: auto 0 0;
 | 
			
		||||
			display: inline-block;
 | 
			
		||||
			width: 1%;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		</style>
 | 
			
		||||
		<script>
 | 
			
		||||
		var posuvList = document.getElementsByClassName("posuv");
 | 
			
		||||
		var maxHeight = posuvList[0].clientHeight;
 | 
			
		||||
		for (i = 0; i < posuvList.length; i++) {
 | 
			
		||||
			var maxPx = 0;
 | 
			
		||||
			var grafMax = Number(posuvList[i].getAttribute("graf-max")); //100%
 | 
			
		||||
			var grafMin = Number(posuvList[i].getAttribute("graf-min")); //0%
 | 
			
		||||
			if (grafMin == 0 && grafMax == 100) {
 | 
			
		||||
				var onePercent = 1;
 | 
			
		||||
			} else {
 | 
			
		||||
				var stepsBetWene = grafMax;
 | 
			
		||||
				if (grafMin !== 0) {
 | 
			
		||||
					if (grafMin < 0) {
 | 
			
		||||
						stepsBetWene = grafMax + Math.abs(grafMin);
 | 
			
		||||
					}
 | 
			
		||||
					if (grafMin > 0) {
 | 
			
		||||
						stepsBetWene = grafMax - grafMin;
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
				var onePercent = stepsBetWene / 100;
 | 
			
		||||
			}
 | 
			
		||||
			var sloupceList = posuvList[i].querySelectorAll(".sloupec");
 | 
			
		||||
			for (ai = 0; ai < sloupceList.length; ai++) {
 | 
			
		||||
				var onePxPercent = maxHeight / 100;
 | 
			
		||||
				var heightInPercent =
 | 
			
		||||
				Math.abs(sloupceList[ai].getAttribute("value")) / onePercent;
 | 
			
		||||
				var outputPx = onePxPercent * heightInPercent;
 | 
			
		||||
 | 
			
		||||
				sloupceList[ai].style.height = outputPx + "px";
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		</script>';
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function generateChartData(int $subDeviceId, string $periode, string $groupBy) {
 | 
			
		||||
		$chartData = [];
 | 
			
		||||
 | 
			
		||||
		$subDevice = SubDeviceManager::getSubDevice($subDeviceId);
 | 
			
		||||
		$records = RecordManager::getAllRecordForGraph($subDeviceId, $periode, $groupBy);
 | 
			
		||||
 | 
			
		||||
		$array = array_column($records, 'value');
 | 
			
		||||
		$arrayTime = array_column($records, 'time');
 | 
			
		||||
		$output = [];
 | 
			
		||||
 | 
			
		||||
		foreach ($array as $key => $value) {
 | 
			
		||||
			$output[$key]['y'] = $value;
 | 
			
		||||
			if ($subDevice['type'] == 'light'){
 | 
			
		||||
				if ($value > 810){
 | 
			
		||||
					$output[$key]['y'] = 1;
 | 
			
		||||
				} else {
 | 
			
		||||
					$output[$key]['y'] = 0;
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
 | 
			
		||||
			$timeStamp = new DateTime($arrayTime[$key]);
 | 
			
		||||
			$output[$key]['t'] = $timeStamp->format("Y-m-d") . 'T' . $timeStamp->format("H:i:s") . 'Z';
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$data = json_encode($output);
 | 
			
		||||
		$data = $output;
 | 
			
		||||
		$arrayTimeStamps = array_column($records, 'time');
 | 
			
		||||
		foreach ($arrayTimeStamps as $key => $value) {
 | 
			
		||||
			$arrayTimeStamps[$key] = (new DateTime($value))->format(TIMEFORMAT);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$chartData['graphRange'] = RANGES[$subDevice['type']];
 | 
			
		||||
		$chartData['graphType'] = RANGES[$subDevice['type']]['graph'];
 | 
			
		||||
		$chartData['graphData'] = $data;
 | 
			
		||||
 | 
			
		||||
		return $chartData;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
@@ -3,19 +3,19 @@ class DashboardManager{
 | 
			
		||||
	public static $devices;
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
	function getAllDashboards ($userId) {
 | 
			
		||||
	static function getAllDashboards ($userId) {
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM dashboard WHERE user_id=?", array($userId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function getAllSubDevices ($userId) {
 | 
			
		||||
	static function getAllSubDevices ($userId) {
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM subdevices WHERE subdevice_id IN (SELECT subdevice_id FROM dashboard WHERE user_id=?)", array($userId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function getSubDevice ($userId, $subDeviceId) {
 | 
			
		||||
	static function getSubDevice ($userId, $subDeviceId) {
 | 
			
		||||
		return Db::loadOne ("SELECT * FROM subdevices WHERE subdevice_id = (SELECT subdevice_id FROM dashboard WHERE user_id=? AND subdevice_id = ? )", array($userId, $subDeviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function Add ($subDeviceId) {
 | 
			
		||||
	static function Add ($subDeviceId) {
 | 
			
		||||
		if (self::getSubDevice(UserManager::getUserData('user_id'), $subDeviceId) == null){
 | 
			
		||||
 | 
			
		||||
			// to do: pokud existuje nepridej
 | 
			
		||||
@@ -34,7 +34,7 @@ class DashboardManager{
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function Remove ($subDeviceId){
 | 
			
		||||
	static function Remove ($subDeviceId){
 | 
			
		||||
		$userId = UserManager::getUserData('user_id');
 | 
			
		||||
		Db::command ('DELETE FROM dashboard WHERE subdevice_id=? AND user_id = ?', array ($subDeviceId, $userId));
 | 
			
		||||
	}
 | 
			
		||||
@@ -2,31 +2,51 @@
 | 
			
		||||
class DeviceManager{
 | 
			
		||||
	public static $devices;
 | 
			
		||||
 | 
			
		||||
	function getAllDevices () {
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM devices WHERE approved != ?", Array(2));
 | 
			
		||||
	static function getAllDevices () {
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM devices
 | 
			
		||||
		WHERE approved != ?", Array(2));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function getAllDevicesInRoom ($roomId = "") {
 | 
			
		||||
	static function setHeartbeat($deviceId){
 | 
			
		||||
		self::edit($deviceId, ['heartbeat' => date("Y-m-d H:i:s", time())]);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getAllDevicesInRoom ($roomId = "") {
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM devices WHERE room_id = ? AND approved != ?", Array($roomId, 2));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function getOtherDevices(){
 | 
			
		||||
	static function getOtherDevices(){
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM devices WHERE room_id IS NULL ");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function getDeviceByToken($deviceToken) {
 | 
			
		||||
	static function getDeviceByToken($deviceToken) {
 | 
			
		||||
		return Db::loadOne("SELECT * FROM devices WHERE token = ?", array($deviceToken));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function getDeviceById($deviceId) {
 | 
			
		||||
	static function getDeviceByMac($deviceMac) {
 | 
			
		||||
		return Db::loadOne("SELECT * FROM devices WHERE mac = ?", array($deviceMac));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getDeviceById($deviceId) {
 | 
			
		||||
		return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function create ($name, $token) {
 | 
			
		||||
	static function getAllDevicesSorted ($sort, $sortType = "ASC") {
 | 
			
		||||
		return Db::loadAll ("SELECT devices.* FROM devices
 | 
			
		||||
			LEFT JOIN rooms ON (devices.room_id = rooms.room_id)
 | 
			
		||||
		WHERE devices.approved != ? ORDER BY $sort $sortType", Array(2));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function create ($name, $token, $type = "") {
 | 
			
		||||
		$defaultRoom = RoomManager::getDefaultRoomId();
 | 
			
		||||
		$device = array (
 | 
			
		||||
			'name' => $name,
 | 
			
		||||
			'token' => $token,
 | 
			
		||||
			'room_id' => $defaultRoom,
 | 
			
		||||
		);
 | 
			
		||||
		if (!empty($type)) {
 | 
			
		||||
			$device['type'] = $type;
 | 
			
		||||
		}
 | 
			
		||||
		try {
 | 
			
		||||
			Db::add ('devices', $device);
 | 
			
		||||
			return Db::loadOne("SELECT device_id FROM devices WHERE token = ?", array($token))['device_id'];
 | 
			
		||||
@@ -36,7 +56,7 @@ class DeviceManager{
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function edit ($deviceId, $values = []) {
 | 
			
		||||
	public static function edit ($deviceId, $values = []) {
 | 
			
		||||
		try {
 | 
			
		||||
			Db::edit ('devices', $values, 'WHERE device_id = ?', array($deviceId));
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
@@ -45,12 +65,21 @@ class DeviceManager{
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function editByToken ($token, $values = []) {
 | 
			
		||||
		try {
 | 
			
		||||
			Db::edit ('devices', $values, 'WHERE token = ?', array($token));
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	* [assignRoom Přiřazení zařízení do třídy]
 | 
			
		||||
	* @param  [type] $roomId   [číslo místnosti do kter se má zařízení přiřadit]
 | 
			
		||||
	* @param  [type] $deviceId [Číslo zařízení které chcete přiřadit do místnosti]
 | 
			
		||||
	*/
 | 
			
		||||
	public function assignRoom ($roomId, $deviceId) {
 | 
			
		||||
	public static function assignRoom ($roomId, $deviceId) {
 | 
			
		||||
		$device = array (
 | 
			
		||||
			'room_id' => $roomId,
 | 
			
		||||
		);
 | 
			
		||||
@@ -66,15 +95,15 @@ class DeviceManager{
 | 
			
		||||
	* [delete Smazání zařízení]
 | 
			
		||||
	* @param  [type] $deviceId [Id zařízení ke smazání]
 | 
			
		||||
	*/
 | 
			
		||||
	public function delete ($deviceId) {
 | 
			
		||||
	public static function delete ($deviceId) {
 | 
			
		||||
		Db::command ('DELETE FROM devices WHERE device_id=?', array ($deviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function registeret ($deviceToken) {
 | 
			
		||||
	public static function registeret ($deviceToken) {
 | 
			
		||||
		return (count(Db::loadAll ("SELECT * FROM devices WHERE token=?", array($deviceToken))) == 1 ? true : false);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function approved ($deviceToken) {
 | 
			
		||||
	public static function approved ($deviceToken) {
 | 
			
		||||
		return (count(Db::loadAll ("SELECT * FROM devices WHERE token=? AND approved = ?", array($deviceToken, 1))) == 1 ? true : false);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										11
									
								
								app/models/managers/EmailManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										11
									
								
								app/models/managers/EmailManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,11 @@
 | 
			
		||||
<?php
 | 
			
		||||
class EmailManager {
 | 
			
		||||
	public function SendTo ($pro, $predmet, $zprava) {
 | 
			
		||||
			$email = "From: EnergyCounter@steelants.cz";
 | 
			
		||||
			$email .= "\nMIME-Version: 1.0\n";
 | 
			
		||||
			$email .= "Content-Type: text/html; charset=\"utf-8\"\n";
 | 
			
		||||
			if (!mb_send_mail ($pro, $predmet, $zprava, $email)) {
 | 
			
		||||
				throw new PDOException("!Email se nepodařilo odeslat!");
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										44
									
								
								app/models/managers/FallbackManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										44
									
								
								app/models/managers/FallbackManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,44 @@
 | 
			
		||||
<?php
 | 
			
		||||
/**
 | 
			
		||||
*
 | 
			
		||||
*/
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
class FallbackManager
 | 
			
		||||
{
 | 
			
		||||
	public $deviceDefinitions = "";
 | 
			
		||||
 | 
			
		||||
	function __construct($deviceDefinition)
 | 
			
		||||
	{
 | 
			
		||||
		$this->deviceDefinitions = $deviceDefinition;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function check(){
 | 
			
		||||
		//TODO: FIX IT
 | 
			
		||||
		$allDevicesData = DeviceManager::getAllDevices();
 | 
			
		||||
		foreach ($allDevicesData as $deviceKey => $deviceValue) {
 | 
			
		||||
			$allSubDevicesData = SubDeviceManager::getAllSubDevices($deviceValue['device_id']);
 | 
			
		||||
			foreach ($allSubDevicesData as $subDeviceKey => $subDeviceValue) {
 | 
			
		||||
				if (!isset($this->deviceDefinitions[$subDeviceValue['type']]["fallBack"])) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				if (!isset($this->deviceDefinitions[$subDeviceValue['type']]["fallBackTime"])) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				$lastRecord = RecordManager::getLastRecord($subDeviceValue['subdevice_id']);
 | 
			
		||||
				if ($lastRecord["value"] == $this->deviceDefinitions[$subDeviceValue['type']]["fallBack"]) {
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				$minutes = (time() - strtotime($lastRecord['time'])) / 60;
 | 
			
		||||
 | 
			
		||||
				if ( $minutes > $this->deviceDefinitions[$subDeviceValue['type']]["fallBackTime"]){
 | 
			
		||||
					RecordManager::create($deviceValue['device_id'], $subDeviceValue['type'], $this->deviceDefinitions[$subDeviceValue['type']]["fallBack"]);
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -17,13 +17,14 @@ class LanguageManager
 | 
			
		||||
 | 
			
		||||
	function load()
 | 
			
		||||
	{
 | 
			
		||||
		$file = './app/lang/en.php';
 | 
			
		||||
		$file = '../lang/en.php';
 | 
			
		||||
		if (!file_exists($file)){
 | 
			
		||||
			echo 'ERROR: en.php not found';
 | 
			
		||||
			die();
 | 
			
		||||
			//TODO add lng EXEPTIONS
 | 
			
		||||
		}
 | 
			
		||||
		$arrayFirst = include($file);
 | 
			
		||||
		$file = './app/lang/' . $this->lngCode . '.php';
 | 
			
		||||
		$file = '../lang/' . $this->lngCode . '.php';
 | 
			
		||||
		$arraySecond = [];
 | 
			
		||||
		if (file_exists($file)){
 | 
			
		||||
			$arraySecond = include($file);
 | 
			
		||||
							
								
								
									
										78
									
								
								app/models/managers/LogMaintainer.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										78
									
								
								app/models/managers/LogMaintainer.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,78 @@
 | 
			
		||||
<?php
 | 
			
		||||
class LogMaintainer
 | 
			
		||||
{
 | 
			
		||||
	private function cleaningDir ($dir, $seconds) {
 | 
			
		||||
		$todayFileName = date ("Y-m-d").'.log';
 | 
			
		||||
		$logFiles = scandir ($dir);
 | 
			
		||||
		foreach ($logFiles as $key => $file) {
 | 
			
		||||
			if (in_array ($file,array (".", "..", ".gitkeep", $todayFileName)))
 | 
			
		||||
			{
 | 
			
		||||
				continue;
 | 
			
		||||
			}
 | 
			
		||||
			if (!is_dir($dir . $file)) {
 | 
			
		||||
				if (strtotime(str_replace(".log", "", $file)) < (strtotime("now") - $seconds)) {
 | 
			
		||||
					unlink ($dir . $file);
 | 
			
		||||
				}
 | 
			
		||||
			} else {
 | 
			
		||||
				$this->cleaningDir ($dir . $file . "/", $seconds);
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function purge ($days) {
 | 
			
		||||
		$seconds = $days * 86400;
 | 
			
		||||
		$this->cleaningDir ('../logs/', $seconds);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getStats(){
 | 
			
		||||
		$stats = array(
 | 
			
		||||
			'ERROR' => 0,
 | 
			
		||||
			'WARNING' => 0,
 | 
			
		||||
			'EXEPTION' => 0,
 | 
			
		||||
			'INFO' => 0,
 | 
			
		||||
		);
 | 
			
		||||
 | 
			
		||||
		$result = array();
 | 
			
		||||
		$result = self::logFinder ('../logs/', $result);
 | 
			
		||||
 | 
			
		||||
		foreach ($result as $path => $files) {
 | 
			
		||||
			foreach ($files as $file) {
 | 
			
		||||
		
 | 
			
		||||
				# code...
 | 
			
		||||
				$matches = array();
 | 
			
		||||
 | 
			
		||||
				$re = '/\[(?:warning|error|info)\]/';
 | 
			
		||||
				$str = file_get_contents($path . $file);
 | 
			
		||||
				preg_match_all($re, $str, $matches);
 | 
			
		||||
				if (count($matches[0]) == 0) continue;
 | 
			
		||||
				
 | 
			
		||||
				foreach ($matches[0] as $match) {
 | 
			
		||||
					switch($match){
 | 
			
		||||
						case '[error]': $stats['ERROR']++; break;
 | 
			
		||||
						case '[warning]': $stats['WARNING']++; break;
 | 
			
		||||
						case '[exeption]': $stats['EXEPTION']++; break;
 | 
			
		||||
						default: $stats['INFO']++;  break;
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		return $stats;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	private static function logFinder ($dir, $result) {
 | 
			
		||||
		$logFiles = scandir ($dir);
 | 
			
		||||
		foreach ($logFiles as $key => $file) {
 | 
			
		||||
			if (in_array ($file,array (".", "..", ".gitkeep")))
 | 
			
		||||
			{
 | 
			
		||||
				continue;
 | 
			
		||||
			}
 | 
			
		||||
			if (!is_dir($dir . $file)) {
 | 
			
		||||
				$result[$dir][] = $file;
 | 
			
		||||
			} else {
 | 
			
		||||
				$result = self::logFinder ($dir . $file . "/", $result);
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		return $result;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										42
									
								
								app/models/managers/LogManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								app/models/managers/LogManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,42 @@
 | 
			
		||||
<?php
 | 
			
		||||
/**
 | 
			
		||||
*
 | 
			
		||||
*/
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
class LogManager
 | 
			
		||||
{
 | 
			
		||||
	private $logFile;
 | 
			
		||||
	private $logLevel = 1;
 | 
			
		||||
 | 
			
		||||
	public function __construct($fileName = "")
 | 
			
		||||
	{
 | 
			
		||||
		if ($fileName == ""){
 | 
			
		||||
			$fileName = '../logs/'. date("Y-m-d").'.log';
 | 
			
		||||
		}
 | 
			
		||||
		if(!is_dir("../logs/"))
 | 
			
		||||
		{
 | 
			
		||||
			mkdir("../logs/");
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$this->logFile = fopen($fileName, "a") or die("Unable to open file!");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function setLevel($type = LogRecordTypess::WARNING){
 | 
			
		||||
		$this->logLevel = $type['level'];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function write($value, $type = LogRecordTypess::ERROR){
 | 
			
		||||
		if ($type['level'] <= $this->logLevel) {
 | 
			
		||||
			$record = "[".date("H:m:s")."][".$type['identifier']."]" . $value . "\n";
 | 
			
		||||
			fwrite($this->logFile, $record);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function __destruct(){
 | 
			
		||||
		if (isset($this->logFile) && $this->logFile != "Unable to open file!") {
 | 
			
		||||
			fclose($this->logFile);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										18
									
								
								app/models/managers/NetworkManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								app/models/managers/NetworkManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,18 @@
 | 
			
		||||
<?php
 | 
			
		||||
/**
 | 
			
		||||
 *
 | 
			
		||||
 */
 | 
			
		||||
class NetvorkManager
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
	function __construct()
 | 
			
		||||
	{
 | 
			
		||||
		// code...
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function validateIp($ip = '0.0.0.0'){
 | 
			
		||||
		if (!filter_var($ip, FILTER_VALIDATE_IP)){
 | 
			
		||||
			return false;
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -2,9 +2,11 @@
 | 
			
		||||
/**
 | 
			
		||||
* Notification Manager
 | 
			
		||||
*/
 | 
			
		||||
//TODO: Working timestamp to $title
 | 
			
		||||
class NotificationManager
 | 
			
		||||
{
 | 
			
		||||
	function addSubscriber($userID = '', $token = ''){
 | 
			
		||||
	public static function addSubscriber($userID, $token){
 | 
			
		||||
		if (!empty($userID) && !empty($token)) {
 | 
			
		||||
			$notificationSubscriber = $subDeviceId = Db::loadOne('SELECT id FROM notifications WHERE token = ?;', array($token));
 | 
			
		||||
			if ($notificationSubscriber == ''){
 | 
			
		||||
				$notification = array (
 | 
			
		||||
@@ -14,12 +16,13 @@ class NotificationManager
 | 
			
		||||
				Db::add ('notifications', $notification);
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
	function getSubscription(){
 | 
			
		||||
		return Db::loadAll('SELECT * FROM notifications;', array());
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function sendSimpleNotification(string $serverKey, string $to, array $data){
 | 
			
		||||
	public static function getSubscription () {
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM notifications");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function sendSimpleNotification(string $serverKey, string $to, array $data, bool $timeStamp = false){
 | 
			
		||||
		$dataTemplate = [
 | 
			
		||||
			'title' => '',
 | 
			
		||||
			'body' => '',
 | 
			
		||||
@@ -30,9 +33,13 @@ class NotificationManager
 | 
			
		||||
			return;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if ($timeStamp) {
 | 
			
		||||
			$data['title'] = $data['title'] . date();
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$notification = new Notification($serverKey);
 | 
			
		||||
		$notification->to($to);
 | 
			
		||||
		$notification->notification($data['title'], $data['body'], $data['icon'], '');
 | 
			
		||||
		$notification->notification($data['title'], date("h:i") . " - " . $data['body'], $data['icon'], '');
 | 
			
		||||
		$answer = $notification->send();
 | 
			
		||||
		$notification = null;
 | 
			
		||||
 | 
			
		||||
@@ -64,8 +71,12 @@ class Notification
 | 
			
		||||
		$this->jsonPayload["to"] = $to;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function notification($title = '', $body = '', $icon = '', $action = '')
 | 
			
		||||
	function notification($title = '', $body = '', $icon = '', $action = '', bool $timeStamp = false)
 | 
			
		||||
	{
 | 
			
		||||
		if ($timeStamp) {
 | 
			
		||||
			$data['title'] = $data['title'] . date();
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		$this->jsonPayload["data"]["notification"]["title"] = $title;
 | 
			
		||||
		$this->jsonPayload["data"]["notification"]["body"] = $body;
 | 
			
		||||
		$this->jsonPayload["data"]["notification"]["icon"] = $icon;
 | 
			
		||||
@@ -2,16 +2,55 @@
 | 
			
		||||
class RecordManager{
 | 
			
		||||
	public static $records;
 | 
			
		||||
 | 
			
		||||
	public function create ($deviceId, $type, $value) {
 | 
			
		||||
		$subDeviceId = Db::loadOne('SELECT * FROM subdevices WHERE device_id = ? AND type = ?;', array($deviceId, $type))['subdevice_id'];
 | 
			
		||||
		if ($subDeviceId == '') {
 | 
			
		||||
			return false;
 | 
			
		||||
		};
 | 
			
		||||
	public static function createWithSubId ($subDeviceId, $value, $origin = false) {
 | 
			
		||||
		try {
 | 
			
		||||
			$record = [
 | 
			
		||||
				'execuded' => 1,
 | 
			
		||||
			];
 | 
			
		||||
 | 
			
		||||
			Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
 | 
			
		||||
			$record = array (
 | 
			
		||||
				'subdevice_id' => $subDeviceId,
 | 
			
		||||
				'value' => $value,
 | 
			
		||||
			);
 | 
			
		||||
 | 
			
		||||
			if ($origin != false)
 | 
			
		||||
				$record['Origin'] = $origin;
 | 
			
		||||
 | 
			
		||||
			return Db::add ('records', $record);
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function create ($deviceId, $type, $value, $origin = false) {
 | 
			
		||||
		$subDeviceId = Db::loadOne('SELECT * FROM subdevices WHERE device_id = ? AND type = ?;', array($deviceId, $type))['subdevice_id'];
 | 
			
		||||
		if ($subDeviceId == '') {
 | 
			
		||||
			return false;
 | 
			
		||||
		};
 | 
			
		||||
 | 
			
		||||
		//Ochrana proti duplicitním hodnotám zapisují se jen změny
 | 
			
		||||
		$lastRecord = self::getLastRecord($subDeviceId, 1);
 | 
			
		||||
 | 
			
		||||
		if (isset($lastRecord['value']) && $lastRecord['value'] == $value){
 | 
			
		||||
			return false;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		try {
 | 
			
		||||
			$record = [
 | 
			
		||||
				'execuded' => 1,
 | 
			
		||||
			];
 | 
			
		||||
			Db::edit ('records', $record, 'WHERE subdevice_id = ?', array ($subDeviceId));
 | 
			
		||||
 | 
			
		||||
			$record = array (
 | 
			
		||||
				'subdevice_id' => $subDeviceId,
 | 
			
		||||
				'value' => $value,
 | 
			
		||||
			);
 | 
			
		||||
 | 
			
		||||
			if ($origin != false)
 | 
			
		||||
				$record['Origin'] = $origin;
 | 
			
		||||
 | 
			
		||||
			return Db::add ('records', $record);
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
@@ -42,17 +81,22 @@ class RecordManager{
 | 
			
		||||
		return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC LIMIT ?;', array($subDeviceId, 999, $num));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getLastRecordNotNull($subDeviceId) {
 | 
			
		||||
		return Db::loadOne('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC;', array($subDeviceId, 0));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getAllRecord($subDeviceId, $timeFrom, $timeTo) {
 | 
			
		||||
		return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND time >= ? AND time <= ? AND value != ? ORDER BY time;', array($subDeviceId, $timeFrom, $timeTo, 999));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	//TODO: Zeptat se @Patrik jestli je secure pak používat periodu přímo do SQL a pak pře url SQL Injection
 | 
			
		||||
	public static function getAllRecordForGraph($subDeviceId, $period = "day", $groupBy = "hour") {
 | 
			
		||||
		$periodLocal = '- 1' . strtoupper($period);
 | 
			
		||||
		$dateTime = new DateTime();
 | 
			
		||||
		$dateTime = $dateTime->modify($periodLocal);
 | 
			
		||||
		$dateTime = $dateTime->format('Y-m-d');
 | 
			
		||||
		$dateTime = $dateTime->format('Y-m-d H:i:s');
 | 
			
		||||
		$groupBy = strtoupper($groupBy).'(time)';
 | 
			
		||||
		$sql = 'SELECT value, time FROM records
 | 
			
		||||
		$sql = 'SELECT value, time, execuded, origin FROM records
 | 
			
		||||
		WHERE
 | 
			
		||||
		subdevice_id = ?
 | 
			
		||||
		AND
 | 
			
		||||
@@ -60,21 +104,25 @@ class RecordManager{
 | 
			
		||||
		AND
 | 
			
		||||
		time > ?
 | 
			
		||||
		GROUP BY '.$groupBy.'
 | 
			
		||||
		ORDER BY time ASC';
 | 
			
		||||
		ORDER BY time Desc';
 | 
			
		||||
		//TODO: Prasárna Opravit
 | 
			
		||||
		return Db::loadAll($sql, array($subDeviceId, $dateTime));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function clean ($day) {
 | 
			
		||||
		if (isset($day)) {
 | 
			
		||||
			Db::command ('DELETE FROM records WHERE time < ADDDATE(NOW(), INTERVAL -? DAY);', array($day));
 | 
			
		||||
			Db::command ('DELETE FROM records WHERE `time` < ADDDATE(NOW(), INTERVAL ? DAY);', array($day));
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
	//TODO: zkontrolovat jestli neco nezbilo po smazaní
 | 
			
		||||
	public static function cleanSubdeviceRecords ($subDeviceId) {
 | 
			
		||||
		Db::command ('DELETE FROM records WHERE subdevice_id = ?);', array($subDeviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function setHistory($subDeviceId){
 | 
			
		||||
		$history = SubDeviceManager::getSubDevice($subDeviceId)['history'];
 | 
			
		||||
		if ($history > 0) self::clean(-abs($history));
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
							
								
								
									
										44
									
								
								app/models/managers/RoomManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										44
									
								
								app/models/managers/RoomManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,44 @@
 | 
			
		||||
<?php
 | 
			
		||||
class RoomManager{
 | 
			
		||||
	public static $rooms;
 | 
			
		||||
 | 
			
		||||
	static function getDefaultRoomId() {
 | 
			
		||||
		$defaultRoom = Db::loadOne("SELECT `room_id` FROM `rooms` WHERE `default` = 1");
 | 
			
		||||
		return $defaultRoom['room_id'];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getAllRooms () {
 | 
			
		||||
		//TODO: ignore Widgets withoud data
 | 
			
		||||
		$allRoom = Db::loadAll ("SELECT rooms.*, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id");
 | 
			
		||||
		return $allRoom;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getRoomsDefault () {
 | 
			
		||||
		//TODO: ignore Widgets withoud data
 | 
			
		||||
		$allRoom = Db::loadAll ("SELECT rooms.room_id, rooms.name, COUNT(devices.device_id) as device_count FROM rooms LEFT JOIN devices ON (devices.room_id=rooms.room_id) GROUP BY rooms.room_id;");
 | 
			
		||||
		return $allRoom;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getRoomName ($room_id) {
 | 
			
		||||
		//TODO: ignore Widgets withoud data
 | 
			
		||||
		$allRoom = Db::loadAlone ("SELECT name FROM rooms WHERE room_id=?", array ($room_id));
 | 
			
		||||
		return $allRoom;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function create ($name) {
 | 
			
		||||
		$room = array (
 | 
			
		||||
			'name' => $name,
 | 
			
		||||
		);
 | 
			
		||||
		try {
 | 
			
		||||
			Db::add ('rooms', $room);
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function delete ($roomId) {
 | 
			
		||||
		Db::command ('DELETE FROM rooms WHERE room_id=?', array ($roomId));
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
@@ -2,7 +2,7 @@
 | 
			
		||||
class SceneManager{
 | 
			
		||||
	public static $scenes;
 | 
			
		||||
 | 
			
		||||
	public function create ($icon, $name, $doCode) {
 | 
			
		||||
	public static function create ($icon, $name, $doCode) {
 | 
			
		||||
		$scene = array (
 | 
			
		||||
			'icon' => $icon,
 | 
			
		||||
			'name' => $name,
 | 
			
		||||
@@ -16,15 +16,15 @@ class SceneManager{
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getAllScenes () {
 | 
			
		||||
	public static function getAllScenes () {
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM scenes");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getScene ($sceneId) {
 | 
			
		||||
	public static function getScene ($sceneId) {
 | 
			
		||||
		return Db::loadOne("SELECT * FROM scenes WHERE scene_id = ?", array($sceneId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function execScene ($sceneId) {
 | 
			
		||||
	public static function execScene ($sceneId) {
 | 
			
		||||
		$sceneData = SceneManager::getScene($sceneId);
 | 
			
		||||
		$sceneDoJson = $sceneData['do_something'];
 | 
			
		||||
		$sceneDoArray = json_decode($sceneDoJson);
 | 
			
		||||
@@ -34,7 +34,7 @@ class SceneManager{
 | 
			
		||||
		return true;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function delete($sceneId){
 | 
			
		||||
	public static function delete($sceneId){
 | 
			
		||||
		Db::command ('DELETE FROM scenes WHERE scene_id=?', array ($sceneId));
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										47
									
								
								app/models/managers/SettingsManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										47
									
								
								app/models/managers/SettingsManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,47 @@
 | 
			
		||||
<?php
 | 
			
		||||
class SettingsManager{
 | 
			
		||||
	static function getAllValues () {
 | 
			
		||||
		return Db::loadAll ("SELECT * FROM settings");
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getByName($settingName, $type = '') {
 | 
			
		||||
		if ($type != '') return Db::loadOne("SELECT * FROM settings WHERE name = ? AND type = ?", array($settingName, $type));
 | 
			
		||||
		return Db::loadOne("SELECT * FROM settings WHERE name = ?", array($settingName));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getSettingGroup($type) {
 | 
			
		||||
		return Db::loadAll("SELECT * FROM settings WHERE type=?", array($type));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function create ($name, $value, $type = '') {
 | 
			
		||||
		//if (!self::getByName($name)){
 | 
			
		||||
			$setting = array (
 | 
			
		||||
				'name' => $name,
 | 
			
		||||
				'value' => $value,
 | 
			
		||||
				'type' => $type,
 | 
			
		||||
			);
 | 
			
		||||
			try {
 | 
			
		||||
				Db::add ('settings', $setting);
 | 
			
		||||
			} catch(PDOException $error) {
 | 
			
		||||
				echo $error->getMessage();
 | 
			
		||||
				die();
 | 
			
		||||
			}
 | 
			
		||||
		//}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function update ($name, $value, $type = '') {
 | 
			
		||||
		if (!self::getByName($name)){
 | 
			
		||||
			self::create($name, $value, $type);
 | 
			
		||||
		} else {
 | 
			
		||||
			try {
 | 
			
		||||
				Db::edit ('settings', [
 | 
			
		||||
					'value' => $value
 | 
			
		||||
				], 'WHERE name = ?', array($name));
 | 
			
		||||
			} catch(PDOException $error) {
 | 
			
		||||
				echo $error->getMessage();
 | 
			
		||||
				die();
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
							
								
								
									
										117
									
								
								app/models/managers/SubDeviceManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										117
									
								
								app/models/managers/SubDeviceManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,117 @@
 | 
			
		||||
<?php
 | 
			
		||||
class SubDeviceManager
 | 
			
		||||
{
 | 
			
		||||
	public static $devices;
 | 
			
		||||
 | 
			
		||||
	public static function getAllSubDevices($deviceId = null)
 | 
			
		||||
	{
 | 
			
		||||
		if ($deviceId == null) {
 | 
			
		||||
			return Db::loadAll("SELECT * FROM subdevices");
 | 
			
		||||
		}
 | 
			
		||||
		return Db::loadAll("SELECT * FROM subdevices WHERE device_id = ?", array($deviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getSubDeviceMaster($subDeviceId)
 | 
			
		||||
	{
 | 
			
		||||
		return Db::loadOne("SELECT * FROM devices WHERE device_id = (SELECT device_id FROM subdevices WHERE subdevice_id = ?)", array($subDeviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getSubDeviceByMaster($deviceId, $subDeviceType = null)
 | 
			
		||||
	{
 | 
			
		||||
		if ($subDeviceType == null) {
 | 
			
		||||
			return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
 | 
			
		||||
		} else {
 | 
			
		||||
			return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ? AND type = ?;", array($deviceId, $subDeviceType));
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getSubDeviceByMasterAndType($deviceId, $subDeviceType = '')
 | 
			
		||||
	{
 | 
			
		||||
		if ($subDeviceType == '') {
 | 
			
		||||
			return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ?;", array($deviceId));
 | 
			
		||||
		} else {
 | 
			
		||||
			return Db::loadOne("SELECT * FROM subdevices WHERE device_id = ? AND type = ?;", array($deviceId, $subDeviceType));
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getSubDevice($subDeviceId)
 | 
			
		||||
	{
 | 
			
		||||
		return Db::loadOne("SELECT * FROM subdevices WHERE subdevice_id = ?;", array($subDeviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getSubDevicesTypeForMater($deviceId)
 | 
			
		||||
	{
 | 
			
		||||
		$parsedTypes = [];
 | 
			
		||||
		$types = Db::loadAll("SELECT type FROM subdevices WHERE device_id = ?;", array($deviceId));
 | 
			
		||||
		foreach ($types as $orderNum => $type) {
 | 
			
		||||
			$parsedTypes[$orderNum] = $type['type'];
 | 
			
		||||
		}
 | 
			
		||||
		return $parsedTypes;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	//check if dubdevice exist
 | 
			
		||||
	//Add History to be set in Creation
 | 
			
		||||
	public static function create($deviceId, $type, $unit)
 | 
			
		||||
	{
 | 
			
		||||
		$record = array(
 | 
			
		||||
			'device_id' => $deviceId,
 | 
			
		||||
			'type' => $type,
 | 
			
		||||
			'unit' => $unit,
 | 
			
		||||
		);
 | 
			
		||||
		try {
 | 
			
		||||
			Db::add('subdevices', $record);
 | 
			
		||||
		} catch (PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function editSubDevicesByDevice ($deviceId, $subDeviceParameters) {
 | 
			
		||||
		DB::edit('subdevices', $subDeviceParameters, 'WHERE device_id=?', array ($deviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function remove($subDeviceId)
 | 
			
		||||
	{
 | 
			
		||||
		RecordManager::cleanSubdeviceRecords($subDeviceId);
 | 
			
		||||
		return Db::loadAll("DELETE FROM subdevices WHERE subdevice_id = ?", array($subDeviceId));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getSubdevicesByRoomIds($roomIds = NULL)
 | 
			
		||||
	{
 | 
			
		||||
		if (empty($roomIds)) return NULL;
 | 
			
		||||
 | 
			
		||||
		//TODO: @Patrik Check line 89
 | 
			
		||||
		$rows = Db::loadAll("
 | 
			
		||||
			SELECT d.room_id, d.sleep_time, sd.subdevice_id, sd.device_id, d.icon, d.name, sd.type, sd.unit, r.value, r.time FROM subdevices sd
 | 
			
		||||
			JOIN devices d ON sd.device_id = d.device_id
 | 
			
		||||
			JOIN records r ON r.subdevice_id = sd.subdevice_id
 | 
			
		||||
			WHERE d.room_id IN (" . str_repeat("?,", count($roomIds) - 1) . "?)
 | 
			
		||||
			/*AND value != '999'*/
 | 
			
		||||
			AND r.record_id IN (
 | 
			
		||||
				SELECT MAX(record_id)
 | 
			
		||||
				FROM records
 | 
			
		||||
				GROUP BY subdevice_id
 | 
			
		||||
			  )
 | 
			
		||||
			GROUP BY subdevice_id
 | 
			
		||||
			ORDER BY d.name DESC
 | 
			
		||||
		", $roomIds);
 | 
			
		||||
 | 
			
		||||
		$ret = [];
 | 
			
		||||
		foreach ($rows as $row) {
 | 
			
		||||
			$ret[$row['room_id']][] = $row;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		return $ret;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getSubdeviceDetailById($subDeviceId){
 | 
			
		||||
		if (empty($subDeviceId)) return NULL;
 | 
			
		||||
 | 
			
		||||
		$rows = Db::loadOne("SELECT d.room_id, d.sleep_time, sd.subdevice_id, sd.type, sd.device_id FROM subdevices sd
 | 
			
		||||
		JOIN devices d ON sd.device_id = d.device_id
 | 
			
		||||
		WHERE sd.subdevice_id = ? ", [$subDeviceId]);
 | 
			
		||||
 | 
			
		||||
		return $rows;
 | 
			
		||||
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,9 +1,9 @@
 | 
			
		||||
<?php
 | 
			
		||||
class UserManager
 | 
			
		||||
{
 | 
			
		||||
	public function getUsers () {
 | 
			
		||||
	public static function getUsers ($filtr = ['*']) {
 | 
			
		||||
		try {
 | 
			
		||||
			$allUsers = Db::loadAll ("SELECT user_id, username, at_home, ota FROM users");
 | 
			
		||||
			$allUsers = Db::loadAll ("SELECT " . implode(",", $filtr) . " FROM users");
 | 
			
		||||
			return $allUsers;
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
@@ -11,7 +11,7 @@ class UserManager
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getUser ($userName) {
 | 
			
		||||
	public static function getUser ($userName) {
 | 
			
		||||
		try {
 | 
			
		||||
			$user = Db::loadOne ("SELECT * FROM users WHERE username = ?", [$userName]);
 | 
			
		||||
			return $user;
 | 
			
		||||
@@ -21,38 +21,73 @@ class UserManager
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function login ($username, $password, $rememberMe) {
 | 
			
		||||
	public static function getUserId ($userId) {
 | 
			
		||||
		try {
 | 
			
		||||
			if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($username))) {
 | 
			
		||||
			$user = Db::loadOne ("SELECT * FROM users WHERE user_id = ?", [$userId]);
 | 
			
		||||
			return $user;
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getAvatarUrl($userId = null){
 | 
			
		||||
		if ($userId == null) {
 | 
			
		||||
			$email = self::getUserData('email');
 | 
			
		||||
		}
 | 
			
		||||
		else if ($userId != null){
 | 
			
		||||
			$email = self::getUserData('email',$userId);
 | 
			
		||||
		}
 | 
			
		||||
		return 'https://secure.gravatar.com/avatar/' . md5( strtolower( trim( $email ) ) );
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function login ($username, $password, $rememberMe) {
 | 
			
		||||
		try {
 | 
			
		||||
			if ($user = Db::loadOne ('SELECT * FROM users WHERE (LOWER(username)=LOWER(?) OR LOWER(email)=LOWER(?))', array ($username, $username))) {
 | 
			
		||||
				if ($user['password'] == UserManager::getHashPassword($password)) {
 | 
			
		||||
					if (isset($rememberMe) && $rememberMe == 'true') {
 | 
			
		||||
						setcookie ("rememberMe", $this->setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), BASEDIR, $_SERVER['HTTP_HOST'], 1);
 | 
			
		||||
						setcookie ("rememberMe", self::setEncryptedCookie($user['username']), time () + (30 * 24 * 60 * 60 * 1000), BASEDIR, $_SERVER['HTTP_HOST'], 1);
 | 
			
		||||
					}
 | 
			
		||||
					$_SESSION['user']['id'] = $user['user_id'];
 | 
			
		||||
					$page = "";
 | 
			
		||||
					if ($user["startPage"] == 1) {
 | 
			
		||||
						$page = "dashboard";
 | 
			
		||||
					}
 | 
			
		||||
					unset($_POST['login']);
 | 
			
		||||
					return $page;
 | 
			
		||||
					return "";
 | 
			
		||||
				} else {
 | 
			
		||||
					throw new PDOException("Heslo není správné!");
 | 
			
		||||
				}
 | 
			
		||||
			} else {
 | 
			
		||||
				throw new PDOException("Uživatel s tím to jménem neexistuje!");
 | 
			
		||||
			}
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			$_SESSION['msg'] = $error->getMessage();
 | 
			
		||||
			unset($_POST);
 | 
			
		||||
			header('Location: ' . BASEURL . 'login');
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function loginNew ($username, $password) {
 | 
			
		||||
		try {
 | 
			
		||||
			if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?) OR LOWER(email)=LOWER(?)', array ($username, $username))) {
 | 
			
		||||
				if ($user['password'] == UserManager::getHashPassword($password)) {
 | 
			
		||||
					return $user['user_id'];
 | 
			
		||||
				} else {
 | 
			
		||||
					return false;
 | 
			
		||||
				}
 | 
			
		||||
			} else {
 | 
			
		||||
				return false;
 | 
			
		||||
			}
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
			echo $error->getMessage();
 | 
			
		||||
			die();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function isLogin () {
 | 
			
		||||
	public static function isLogin () {
 | 
			
		||||
		if (isset ($_SESSION['user']) && isset($_SESSION['user']['id'])) {
 | 
			
		||||
			return true;
 | 
			
		||||
		} else {
 | 
			
		||||
			if (isset ($_COOKIE['rememberMe'])){
 | 
			
		||||
				if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array ($this->getDecryptedCookie($_COOKIE['rememberMe'])))) {
 | 
			
		||||
				if ($user = Db::loadOne ('SELECT * FROM users WHERE LOWER(username)=LOWER(?)', array (self::getDecryptedCookie($_COOKIE['rememberMe'])))) {
 | 
			
		||||
					$_SESSION['user']['id'] = $user['user_id'];
 | 
			
		||||
					return true;
 | 
			
		||||
				}
 | 
			
		||||
@@ -61,16 +96,14 @@ class UserManager
 | 
			
		||||
		return false;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function logout () {
 | 
			
		||||
	public static function logout () {
 | 
			
		||||
		unset($_SESSION['user']);
 | 
			
		||||
		session_destroy();
 | 
			
		||||
		if (isset($_COOKIE['rememberMe'])){
 | 
			
		||||
		unset($_COOKIE['rememberMe']);
 | 
			
		||||
			setcookie("rememberMe", 'false', time(), BASEDIR, $_SERVER['HTTP_HOST']);
 | 
			
		||||
		}
 | 
			
		||||
		setcookie("rememberMe", 'false', 0 - time(), BASEDIR, $_SERVER['HTTP_HOST']);
 | 
			
		||||
		session_destroy();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function setEncryptedCookie($value){
 | 
			
		||||
	public static function setEncryptedCookie($value){
 | 
			
		||||
		$first_key = base64_decode(FIRSTKEY);
 | 
			
		||||
		$second_key = base64_decode(SECONDKEY);
 | 
			
		||||
 | 
			
		||||
@@ -83,7 +116,7 @@ class UserManager
 | 
			
		||||
		return $newvalue;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getDecryptedCookie($value){
 | 
			
		||||
	public static function getDecryptedCookie($value){
 | 
			
		||||
		$first_key = base64_decode(FIRSTKEY);
 | 
			
		||||
		$second_key = base64_decode(SECONDKEY);
 | 
			
		||||
 | 
			
		||||
@@ -102,28 +135,32 @@ class UserManager
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getUserData ($type, $userId = '') {
 | 
			
		||||
		if (isset($_SESSION['user']['id'])) {
 | 
			
		||||
		if ($userId == '') {
 | 
			
		||||
			$userId = $_SESSION['user']['id'];
 | 
			
		||||
		} else {
 | 
			
		||||
			return "";
 | 
			
		||||
		}
 | 
			
		||||
		$user = Db::loadOne ('SELECT ' . $type . ' FROM users WHERE user_id=?', array ($userId));
 | 
			
		||||
		return $user[$type];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function setUserData ($type, $value) {
 | 
			
		||||
	public static function setUserData ($type, $value) {
 | 
			
		||||
		if (isset ($_SESSION['user']['id'])) {
 | 
			
		||||
			Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $_SESSION['user']['id']));
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function getHashPassword ($password) {
 | 
			
		||||
	public static function setUserDataAdmin ($type, $value, $id) {
 | 
			
		||||
		if ($id) {
 | 
			
		||||
			Db::command ('UPDATE users SET ' . $type . '=? WHERE user_id=?', array ($value, $id));
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function getHashPassword ($password) {
 | 
			
		||||
		$salt = "s0mRIdlKvI";
 | 
			
		||||
		$hashPassword = hash('sha512', ($password . $salt));
 | 
			
		||||
		return $hashPassword;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function atHome($userId, $atHome){
 | 
			
		||||
	public static function atHome($userId, $atHome){
 | 
			
		||||
		try {
 | 
			
		||||
			Db::edit ('users', ['at_home' => $atHome], 'WHERE user_id = ?', array($userId));
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
@@ -132,7 +169,7 @@ class UserManager
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function changePassword($oldPassword, $newPassword, $newPassword2){
 | 
			
		||||
	public static function changePassword($oldPassword, $newPassword, $newPassword2){
 | 
			
		||||
		if ($newPassword == $newPassword2) {
 | 
			
		||||
			//Password Criteria
 | 
			
		||||
			$oldPasswordSaved = self::getUserData('password');
 | 
			
		||||
@@ -146,8 +183,9 @@ class UserManager
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function createUser($userName, $password){
 | 
			
		||||
		$userId = Db::loadOne('SELECT * FROM users WHERE username = ?;', array($userName))['user_id'];
 | 
			
		||||
	public static function createUser ($userName, $password, $email) {
 | 
			
		||||
		$email = strtolower ($email);
 | 
			
		||||
		$userId = Db::loadOne ('SELECT * FROM users WHERE LOWER (username) = LOWER (?) OR LOWER (email) = LOWER (?);', array ($userName, $email))['user_id'];
 | 
			
		||||
		if ($userId != null) {
 | 
			
		||||
			return false;
 | 
			
		||||
		};
 | 
			
		||||
@@ -155,6 +193,7 @@ class UserManager
 | 
			
		||||
			$user = [
 | 
			
		||||
				'username' => $userName,
 | 
			
		||||
				'password' => self::getHashPassword($password),
 | 
			
		||||
				'email' => $email,
 | 
			
		||||
			];
 | 
			
		||||
			return Db::add ('users', $user);
 | 
			
		||||
		} catch(PDOException $error) {
 | 
			
		||||
@@ -163,8 +202,8 @@ class UserManager
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public function	haveOtaEnabled($userName){
 | 
			
		||||
		$ota = $this->getUser($userName)['ota'];
 | 
			
		||||
	public static function	haveOtaEnabled($userName){
 | 
			
		||||
		$ota = self::getUser($userName)['ota'];
 | 
			
		||||
 | 
			
		||||
		if ($ota != ''){
 | 
			
		||||
			return ($ota != '' ? $ota : false);
 | 
			
		||||
@@ -172,5 +211,15 @@ class UserManager
 | 
			
		||||
			return false;
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function setOta($otaCode, $otaSecret){
 | 
			
		||||
		$ga = new PHPGangsta_GoogleAuthenticator();
 | 
			
		||||
		$checkResult = $ga->verifyCode($otaSecret, $otaCode, 2);    // 2 = 2*30sec clock tolerance
 | 
			
		||||
		if ($checkResult) {
 | 
			
		||||
			self::setUserData('ota', $otaSecret);
 | 
			
		||||
			return true;
 | 
			
		||||
		}
 | 
			
		||||
		return false;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
?>
 | 
			
		||||
							
								
								
									
										19
									
								
								app/models/managers/VirtualDeviceManager.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								app/models/managers/VirtualDeviceManager.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,19 @@
 | 
			
		||||
<?php
 | 
			
		||||
class VirtualDeviceManager
 | 
			
		||||
{
 | 
			
		||||
	public function fetchEnabled($deviceId = null, $subDeviceId = null){
 | 
			
		||||
		$sleepTime = DeviceManager::getDeviceById($deviceId)['sleep_time'];
 | 
			
		||||
 | 
			
		||||
		$LastRecordTime = new DateTime(RecordManager::getLastRecord($subDeviceId, 1)['time']);
 | 
			
		||||
		$interval = $LastRecordTime->diff(new DateTime());
 | 
			
		||||
		$hours   = $interval->format('%h');
 | 
			
		||||
		$minutes = $interval->format('%i');
 | 
			
		||||
		$lastSeen = ($hours * 60 + $minutes);
 | 
			
		||||
 | 
			
		||||
		if ($lastSeen > $sleepTime || $sleepTime == 0) {
 | 
			
		||||
			return true;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		return false;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										185
									
								
								app/models/types/GoogleHomeDeviceTypes.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										185
									
								
								app/models/types/GoogleHomeDeviceTypes.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,185 @@
 | 
			
		||||
<?php
 | 
			
		||||
class GoogleHomeDeviceTypes {
 | 
			
		||||
	/*const AirConditioningUnit	   = 'action.devices.types.AC_UNIT';
 | 
			
		||||
	const AirFreshener 			   = 'action.devices.types.AIRFRESHENER';
 | 
			
		||||
	const AirPurifier             = 'action.devices.types.AIRPURIFIER';
 | 
			
		||||
	const Awning 					   = 'action.devices.types.AWNING';
 | 
			
		||||
	const Bathtub 					   = 'action.devices.types.BATHTUB';
 | 
			
		||||
	const Bed 					 	   = 'action.devices.types.BED';
 | 
			
		||||
	const Blender				 	   = 'action.devices.types.BLENDER';
 | 
			
		||||
	const Blinds					   = 'action.devices.types.BLINDS';
 | 
			
		||||
	const Boiler					   = 'action.devices.types.BOILER';
 | 
			
		||||
	const Camera					   = 'action.devices.types.CAMERA';
 | 
			
		||||
	const CarbonMonoxideDetector	= 'action.devices.types.CARBON_MONOXIDE_DETECTOR';
 | 
			
		||||
	const Charger						= 'action.devices.types.CHARGER';
 | 
			
		||||
	const Closet						= 'action.devices.types.CLOSET';
 | 
			
		||||
	const CoffeeMaker					= 'action.devices.types.COFFEE_MAKER';
 | 
			
		||||
	const Cooktop						= 'action.devices.types.COOKTOP';
 | 
			
		||||
	const Curtain						= 'action.devices.types.CURTAIN';
 | 
			
		||||
	const Dehumidifier				= 'action.devices.types.DEHUMIDIFIER';
 | 
			
		||||
	const Dehydrator					= 'action.devices.types.DEHYDRATOR';
 | 
			
		||||
	const Dishwasher					= 'action.devices.types.DISHWASHER';
 | 
			
		||||
	const Door							= 'action.devices.types.DOOR';
 | 
			
		||||
	const Drawer						= 'action.devices.types.DRAWER';
 | 
			
		||||
	const Dryer							= 'action.devices.types.DRYER';
 | 
			
		||||
	const Fan							= 'action.devices.types.FAN';
 | 
			
		||||
	const Faucet						= 'action.devices.types.FAUCET';
 | 
			
		||||
	const Fireplace					= 'action.devices.types.FIREPLACE';
 | 
			
		||||
	const Fryer                   = 'action.devices.types.FRYER';
 | 
			
		||||
	const GarageDoor              = 'action.devices.types.GARAGE';
 | 
			
		||||
	const Gate							= 'action.devices.types.GATE';
 | 
			
		||||
	const Grill							= 'action.devices.types.GRILL';
 | 
			
		||||
	const Heater						= 'action.devices.types.HEATER';
 | 
			
		||||
	const Hood							= 'action.devices.types.HOOD';
 | 
			
		||||
	const Humidifier					= 'action.devices.types.HUMIDIFIER';
 | 
			
		||||
	const Kettle						= 'action.devices.types.KETTLE';
 | 
			
		||||
	const Light							= 'action.devices.types.LIGHT';
 | 
			
		||||
	const Lock							= 'action.devices.types.LOCK';
 | 
			
		||||
	const MediaRemote					= 'action.devices.types.REMOTECONTROL';
 | 
			
		||||
	const Mop							= 'action.devices.types.MOP';
 | 
			
		||||
	const Mower							= 'action.devices.types.MOWER';
 | 
			
		||||
	const Microwave					= 'action.devices.types.MICROWAVE';
 | 
			
		||||
	const Multicooker					= 'action.devices.types.MULTICOOKER';
 | 
			
		||||
	const Network						= 'action.devices.types.NETWORK';
 | 
			
		||||
 | 
			
		||||
	const Oven							= 'action.devices.types.OVEN';
 | 
			
		||||
	const Pergola						= 'action.devices.types.PERGOLA';
 | 
			
		||||
	const PetFeeder					= 'action.devices.types.PETFEEDER';
 | 
			
		||||
	const PressureCooker				= 'action.devices.types.PRESSURECOOKER';
 | 
			
		||||
	const Radiator						= 'action.devices.types.RADIATOR';
 | 
			
		||||
	const Refrigerator				= 'action.devices.types.REFRIGERATOR';
 | 
			
		||||
	const Router						= 'action.devices.types.ROUTER';
 | 
			
		||||
	const Scene							= 'action.devices.types.SCENE';
 | 
			
		||||
	const Sensor						= 'action.devices.types.SENSOR';
 | 
			
		||||
	const SecuritySystem				= 'action.devices.types.SECURITYSYSTEM';
 | 
			
		||||
	const SettopBox					= 'action.devices.types.SETTOP';
 | 
			
		||||
	const Shutter						= 'action.devices.types.SHUTTER';
 | 
			
		||||
	const Shower						= 'action.devices.types.SHOWER';
 | 
			
		||||
	const SmokeDetector				= 'action.devices.types.SMOKE_DETECTOR';
 | 
			
		||||
	const SousVide						= 'action.devices.types.SOUSVIDE';
 | 
			
		||||
	const Sprinkler					= 'action.devices.types.SPRINKLER';
 | 
			
		||||
	const StandMixer					= 'action.devices.types.STANDMIXER';
 | 
			
		||||
	const Switch						= 'action.devices.types.SWITCH';
 | 
			
		||||
	const Television					= 'action.devices.types.TV';
 | 
			
		||||
	const Thermostat					= 'action.devices.types.THERMOSTAT';
 | 
			
		||||
	const Vacuum						= 'action.devices.types.VACUUM';
 | 
			
		||||
	const Valve							= 'action.devices.types.VALVE';
 | 
			
		||||
	const Washer						= 'action.devices.types.WASHER';
 | 
			
		||||
	const WaterHeater					= 'action.devices.types.WATERHEATER';
 | 
			
		||||
	const WaterPurifier				= 'action.devices.types.WATERPURIFIER';
 | 
			
		||||
	const WaterSoftener				= 'action.devices.types.WATERSOFTENER';
 | 
			
		||||
	const Window						= 'action.devices.types.WINDOW';
 | 
			
		||||
	const YogurtMaker					= 'action.devices.types.YOGURTMAKER';*/
 | 
			
		||||
 | 
			
		||||
	private static $actionWordBook = [
 | 
			
		||||
		'control-light' 			=> 'action.devices.types.LIGHT',
 | 
			
		||||
		'control-socket' 			=> 'action.devices.types.OUTLET',
 | 
			
		||||
		'control-temp'				=> 'action.devices.types.THERMOSTAT',
 | 
			
		||||
		'control-media'				=> 'action.devices.types.REMOTECONTROL',
 | 
			
		||||
	];
 | 
			
		||||
 | 
			
		||||
	private static $traidWordBook = [
 | 
			
		||||
		'on/off' 					=> 'action.devices.traits.OnOff',
 | 
			
		||||
		'temp_cont' 				=> 'action.devices.traits.TemperatureSetting',
 | 
			
		||||
		'vol_cont'					=> 'action.devices.traits.Volume',
 | 
			
		||||
		'media_cont'            => 'action.devices.traits.TransportControl',
 | 
			
		||||
		'media_status'          => 'action.devices.traits.MediaState',
 | 
			
		||||
		'media_apps'            => 'action.devices.traits.AppSelector',
 | 
			
		||||
		'media_input'           => 'action.devices.traits.InputSelector',
 | 
			
		||||
	];
 | 
			
		||||
 | 
			
		||||
	private static $commandWordBook = [
 | 
			
		||||
		'action.devices.commands.OnOff' => 'on/off',
 | 
			
		||||
		'action.devices.commands.ThermostatTemperatureSetpoint' => 'temp_cont',
 | 
			
		||||
		'action.devices.commands.ThermostatSetMode' => 'temp_cont',
 | 
			
		||||
		'action.devices.commands.setVolume' => 'vol_cont',
 | 
			
		||||
		'action.devices.commands.mediaNext' => 'media_status',
 | 
			
		||||
		'action.devices.commands.mediaPause' => 'media_status',
 | 
			
		||||
		'action.devices.commands.mediaPrevious' => 'media_status',
 | 
			
		||||
		'action.devices.commands.mediaResume' => 'media_status',
 | 
			
		||||
		'action.devices.commands.mediaStop' => 'media_status',
 | 
			
		||||
		'action.devices.commands.appSelect' => 'media_apps',
 | 
			
		||||
		'action.devices.commands.SetInput' => 'media_input',
 | 
			
		||||
	];
 | 
			
		||||
 | 
			
		||||
	private static $attributeWordBook = [
 | 
			
		||||
		'on/off' => [
 | 
			
		||||
			'commandOnlyOnOff' => false,
 | 
			
		||||
		],
 | 
			
		||||
		'temp_cont' 				=> [
 | 
			
		||||
			'availableThermostatModes' => 'off,heat',
 | 
			
		||||
			'thermostatTemperatureUnit' => 'C',
 | 
			
		||||
		],
 | 
			
		||||
		'vol_cont' 				=> [
 | 
			
		||||
			'volumeCanMuteAndUnmute' => false,
 | 
			
		||||
			'volumeDefaultPercentage' => 6,
 | 
			
		||||
			'volumeMaxLevel' => 100,
 | 
			
		||||
			'levelStepSize' => 2,
 | 
			
		||||
			'commandOnlyVolume' => false,
 | 
			
		||||
		],
 | 
			
		||||
		'media_cont'=> [
 | 
			
		||||
			'transportControlSupportedCommands' => [
 | 
			
		||||
				"NEXT",
 | 
			
		||||
				"PREVIOUS",
 | 
			
		||||
				"PAUSE",
 | 
			
		||||
				"STOP",
 | 
			
		||||
				"RESUME",
 | 
			
		||||
				"CAPTION_CONTROL"
 | 
			
		||||
			],
 | 
			
		||||
		],
 | 
			
		||||
		'media_status'=> [
 | 
			
		||||
			'supportActivityState' => true,
 | 
			
		||||
			'supportPlaybackState' => true,
 | 
			
		||||
		],
 | 
			
		||||
		'media_apps' => [
 | 
			
		||||
			"availableApplications" => [
 | 
			
		||||
				[
 | 
			
		||||
					"key" => "kodi",
 | 
			
		||||
					"names" => [
 | 
			
		||||
						"name_synonym" => [
 | 
			
		||||
							"Kodi",
 | 
			
		||||
						],
 | 
			
		||||
						"lang" => "en",
 | 
			
		||||
					],
 | 
			
		||||
				],
 | 
			
		||||
			],
 | 
			
		||||
		],
 | 
			
		||||
		'media_input' => [
 | 
			
		||||
			"availableInputs" => [
 | 
			
		||||
				[
 | 
			
		||||
					"key" => "pc",
 | 
			
		||||
					"names" => [
 | 
			
		||||
						"name_synonym"  => [
 | 
			
		||||
							"PC",
 | 
			
		||||
						],
 | 
			
		||||
						"lang"  => "en",
 | 
			
		||||
					],
 | 
			
		||||
				],
 | 
			
		||||
			]
 | 
			
		||||
		],
 | 
			
		||||
	];
 | 
			
		||||
 | 
			
		||||
	static function getAction($deviceType){
 | 
			
		||||
		if (!isset(self::$actionWordBook[$deviceType])) return;
 | 
			
		||||
		return self::$actionWordBook[$deviceType];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getTraid($subDeviceType){
 | 
			
		||||
		if (!isset(self::$traidWordBook[$subDeviceType])) return;
 | 
			
		||||
		return self::$traidWordBook[$subDeviceType];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getType($subDeviceCommand){
 | 
			
		||||
		if (!isset(self::$commandWordBook[$subDeviceCommand])) return;
 | 
			
		||||
		return self::$commandWordBook[$subDeviceCommand];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getAttribute($subDeviceType){
 | 
			
		||||
		if (!isset(self::$attributeWordBook[$subDeviceType])) return;
 | 
			
		||||
		return self::$attributeWordBook[$subDeviceType];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static function getQueryJson($deviceType, $type){
 | 
			
		||||
		return self::$wordBook[$type];
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										19
									
								
								app/models/types/LogRecordTypes.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								app/models/types/LogRecordTypes.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,19 @@
 | 
			
		||||
<?php
 | 
			
		||||
class LogRecordTypes{
 | 
			
		||||
	const ERROR = [
 | 
			
		||||
		'level' => 0,
 | 
			
		||||
		'identifier' => 'error',
 | 
			
		||||
	];
 | 
			
		||||
	const WARNING = [
 | 
			
		||||
		'level' => 1,
 | 
			
		||||
		'identifier' =>'warning',
 | 
			
		||||
	];
 | 
			
		||||
	const EXEPTION = [
 | 
			
		||||
		'level' => 2,
 | 
			
		||||
		'identifier' => 'exeption',
 | 
			
		||||
	];
 | 
			
		||||
	const INFO = [
 | 
			
		||||
		'level' => 3,
 | 
			
		||||
		'identifier' => 'info',
 | 
			
		||||
	];
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										45
									
								
								app/models/types/WidgetTypes.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										45
									
								
								app/models/types/WidgetTypes.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,45 @@
 | 
			
		||||
<?php
 | 
			
		||||
 | 
			
		||||
class WidgetTypes {
 | 
			
		||||
	const VALUE 	= 0;
 | 
			
		||||
	const ICON 		= 1;
 | 
			
		||||
	const BUTTON 	= 2;
 | 
			
		||||
	const SWITH  	= 3;
 | 
			
		||||
	const RANGE 	= 4;
 | 
			
		||||
	const CUSTOM	= 5;
 | 
			
		||||
 | 
			
		||||
	private $types = [
 | 
			
		||||
		self::VALUE => [
 | 
			
		||||
			'name' => 'value',
 | 
			
		||||
			'active' => false
 | 
			
		||||
		],
 | 
			
		||||
		self::ICON => [
 | 
			
		||||
			'name' => 'icon',
 | 
			
		||||
			'active' => false
 | 
			
		||||
		],
 | 
			
		||||
		self::BUTTON => [
 | 
			
		||||
			'name' => 'button',
 | 
			
		||||
			'active' => true
 | 
			
		||||
		],
 | 
			
		||||
		self::SWITH => [
 | 
			
		||||
			'name' => 'switch',
 | 
			
		||||
			'active' => true
 | 
			
		||||
		],
 | 
			
		||||
		self::RANGE => [
 | 
			
		||||
			'name' => 'range',
 | 
			
		||||
			'active' => true
 | 
			
		||||
		],
 | 
			
		||||
		self::CUSTOM => [
 | 
			
		||||
			'name' => 'custom',
 | 
			
		||||
			'active' => true
 | 
			
		||||
		],
 | 
			
		||||
	];
 | 
			
		||||
 | 
			
		||||
	public static function getName($type){
 | 
			
		||||
		return self::$types[$type];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	public static function isActive($type){
 | 
			
		||||
		return isset(self::$types[$type]) && self::$types[$type]['active'];
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										52
									
								
								app/plugins/!AirQuality.php
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										52
									
								
								app/plugins/!AirQuality.php
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,52 @@
 | 
			
		||||
<?php
 | 
			
		||||
class AirQuality extends VirtualDeviceManager
 | 
			
		||||
{
 | 
			
		||||
	private $city_sluig = "prague";
 | 
			
		||||
	private $app_id = "53ccbc353bb0bd0b05515169a593b96c38d57c48";
 | 
			
		||||
	private $api_uri = 'http://api.waqi.info/feed/%s/?token=%s'; // Your redirect uri
 | 
			
		||||
	private $virtual_device_name = "Air Quality";
 | 
			
		||||
	private $subdevice_type = "air-quality";
 | 
			
		||||
 | 
			
		||||
	function make()
 | 
			
		||||
	{
 | 
			
		||||
		try {
 | 
			
		||||
			if (DeviceManager::registeret($this->virtual_device_name)) {
 | 
			
		||||
				$deviceId = DeviceManager::getDeviceByToken($this->virtual_device_name)['device_id'];
 | 
			
		||||
				if (!$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, $this->subdevice_type)) {
 | 
			
		||||
					SubDeviceManager::create($deviceId, $this->subdevice_type, '');
 | 
			
		||||
					sleep(1);
 | 
			
		||||
					$subDevice = SubDeviceManager::getSubDeviceByMaster($deviceId, strtolower($this->subdevice_type));
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				//if (!$this->fetchEnabled($deviceId,$subDevice['subdevice_id'])) die();
 | 
			
		||||
 | 
			
		||||
				$finalUrl = sprintf($this->api_uri, $this->city_sluig, $this->app_id);
 | 
			
		||||
				$json = json_decode(Utilities::CallAPI('GET', $finalUrl, ''), true);
 | 
			
		||||
				RecordManager::create($deviceId, $this->subdevice_type, $json['data']['aqi'], 'plugin');
 | 
			
		||||
			} else {
 | 
			
		||||
				DeviceManager::create($this->virtual_device_name, $this->virtual_device_name, 'senzore-virtual');
 | 
			
		||||
				DeviceManager::approved($this->virtual_device_name);
 | 
			
		||||
			}
 | 
			
		||||
			return 'sucessful';
 | 
			
		||||
		} catch(Exception $e) {
 | 
			
		||||
			return 'exception: ' . $e->getMessage();
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function translate($value){
 | 
			
		||||
		if ($value < 50) {
 | 
			
		||||
			return 'Good';
 | 
			
		||||
		}  else if  ($value > 51 && $value < 100) {
 | 
			
		||||
			return 'Moderate';
 | 
			
		||||
		} else if ($value > 101 && $value < 150) {
 | 
			
		||||
			return 'Normal';
 | 
			
		||||
		} else if ($value > 151 && $value < 200) {
 | 
			
		||||
			return 'Unhealthy';
 | 
			
		||||
		} else if ($value > 201 && $value < 300) {
 | 
			
		||||
			return 'Very Unhealthy';
 | 
			
		||||
		} else if ($value > 301 ) {
 | 
			
		||||
			return 'Hazardous';
 | 
			
		||||
		}
 | 
			
		||||
		return '';
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user