Compare commits
307 Commits
Author | SHA1 | Date | |
---|---|---|---|
c608b34de4 | |||
cceba2d62d | |||
|
e38421ca2f | ||
27e9ef9f27 | |||
35293ac1b9 | |||
7e5176d5f3 | |||
eb48d616a8 | |||
498a71fc71 | |||
dfa0b6505d | |||
f8c1421bdd | |||
1d6c509982 | |||
9575f69b35 | |||
a0f7b51ba1 | |||
aafd9622a6 | |||
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 |
@@ -1,31 +1,15 @@
|
||||
# https://editorconfig.org/
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
tab_width = 4
|
||||
|
||||
[*.{php,phpt,inc}]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 2
|
||||
indent_style = tab
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_style = tab
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
max_line_length = 80
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[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
|
||||
[*.{yml,yaml}]
|
||||
indent_size = 2
|
||||
|
49
.env.bak
Normal file
@@ -0,0 +1,49 @@
|
||||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_KEY=base64:xVtSpoWE/jaVTqvkBLSMsqTmkLc6GXTZ/1Hu5t2tIww=
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://example-app.test
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_LEVEL=debug
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=mysql
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=simple_home
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=toor
|
||||
|
||||
BROADCAST_DRIVER=log
|
||||
CACHE_DRIVER=file
|
||||
QUEUE_CONNECTION=sync
|
||||
SESSION_DRIVER=file
|
||||
SESSION_LIFETIME=120
|
||||
|
||||
MEMCACHED_HOST=memcached
|
||||
|
||||
REDIS_HOST=redis
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=mailhog
|
||||
MAIL_PORT=1025
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_ENCRYPTION=null
|
||||
MAIL_FROM_ADDRESS=null
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
AWS_DEFAULT_REGION=us-east-1
|
||||
AWS_BUCKET=
|
||||
|
||||
PUSHER_APP_ID=
|
||||
PUSHER_APP_KEY=
|
||||
PUSHER_APP_SECRET=
|
||||
PUSHER_APP_CLUSTER=mt1
|
||||
|
||||
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
|
||||
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
|
49
.env.example
Normal file
@@ -0,0 +1,49 @@
|
||||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_KEY=base64:xVtSpoWE/jaVTqvkBLSMsqTmkLc6GXTZ/1Hu5t2tIww=
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://example-app.test
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_LEVEL=debug
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=mysql
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=simple_home
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=toor
|
||||
|
||||
BROADCAST_DRIVER=log
|
||||
CACHE_DRIVER=file
|
||||
QUEUE_CONNECTION=sync
|
||||
SESSION_DRIVER=file
|
||||
SESSION_LIFETIME=120
|
||||
|
||||
MEMCACHED_HOST=memcached
|
||||
|
||||
REDIS_HOST=redis
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=mailhog
|
||||
MAIL_PORT=1025
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_ENCRYPTION=null
|
||||
MAIL_FROM_ADDRESS=null
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
AWS_DEFAULT_REGION=us-east-1
|
||||
AWS_BUCKET=
|
||||
|
||||
PUSHER_APP_ID=
|
||||
PUSHER_APP_KEY=
|
||||
PUSHER_APP_SECRET=
|
||||
PUSHER_APP_CLUSTER=mt1
|
||||
|
||||
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
|
||||
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
|
49
.env.example.bak
Normal file
@@ -0,0 +1,49 @@
|
||||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_KEY=
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://localhost
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_LEVEL=debug
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=mysql
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=example_app
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
|
||||
BROADCAST_DRIVER=log
|
||||
CACHE_DRIVER=file
|
||||
QUEUE_CONNECTION=sync
|
||||
SESSION_DRIVER=file
|
||||
SESSION_LIFETIME=120
|
||||
|
||||
MEMCACHED_HOST=memcached
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=mailhog
|
||||
MAIL_PORT=1025
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_ENCRYPTION=null
|
||||
MAIL_FROM_ADDRESS=null
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
AWS_ACCESS_KEY_ID=
|
||||
AWS_SECRET_ACCESS_KEY=
|
||||
AWS_DEFAULT_REGION=us-east-1
|
||||
AWS_BUCKET=
|
||||
|
||||
PUSHER_APP_ID=
|
||||
PUSHER_APP_KEY=
|
||||
PUSHER_APP_SECRET=
|
||||
PUSHER_APP_CLUSTER=mt1
|
||||
|
||||
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
|
||||
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
|
@@ -1,6 +0,0 @@
|
||||
.git
|
||||
_FIRMWARE
|
||||
_INSTALATION
|
||||
_README_IMG
|
||||
README.md
|
||||
.todo
|
5
.gitattributes
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
* text=auto
|
||||
*.css linguist-vendored
|
||||
*.scss linguist-vendored
|
||||
*.js linguist-vendored
|
||||
CHANGELOG.md export-ignore
|
30
.gitignore
vendored
@@ -1,11 +1,19 @@
|
||||
.ftpconfig
|
||||
.ftpconfig2
|
||||
config.php
|
||||
_nemazat/index.html
|
||||
_nemazat/css/main.css.map
|
||||
_nemazat/css/main.css
|
||||
_nemazat/css/font-awesome.min.css
|
||||
app/logs/*.log
|
||||
.vscode/
|
||||
.vscode/sftp.json
|
||||
app/updater/*.bin
|
||||
/node_modules
|
||||
/public/hot
|
||||
/public/storage
|
||||
/storage/*.key
|
||||
/vendor
|
||||
.env
|
||||
.env.backup
|
||||
.phpunit.result.cache
|
||||
docker-compose.override.yml
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
.idea/
|
||||
|
||||
|
||||
|
||||
|
||||
.vscode
|
||||
|
18
.htaccess
@@ -1,18 +0,0 @@
|
||||
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]
|
||||
|
||||
RewriteCond %{HTTPS} off
|
||||
RewriteCond %{REQUEST_FILENAME} !api.php
|
||||
RewriteCond %{REQUEST_FILENAME} !apiFront.php
|
||||
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
|
||||
|
||||
AddType application/x-httpd-php .php .phtml
|
13
.styleci.yml
Normal file
@@ -0,0 +1,13 @@
|
||||
php:
|
||||
preset: laravel
|
||||
disabled:
|
||||
- no_unused_imports
|
||||
finder:
|
||||
not-name:
|
||||
- index.php
|
||||
- server.php
|
||||
js:
|
||||
finder:
|
||||
not-name:
|
||||
- webpack.mix.js
|
||||
css: true
|
13
.todo
@@ -1,13 +0,0 @@
|
||||
//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
|
21
LICENSE
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 JonatanRek
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
34
README.md
@@ -135,3 +135,37 @@ 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
|
||||
|
||||
## 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
|
||||
```
|
||||
|
@@ -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"
|
@@ -1,88 +0,0 @@
|
||||
//Includes
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
//USER CONFIGURATION
|
||||
const char* WIFI_SSID = "";
|
||||
const char* WIFI_PASS = "";
|
||||
const char* HW_TOKEN = "";
|
||||
const char* SERVER_ADRESS = "";
|
||||
|
||||
StaticJsonDocument<250> jsonBuffer;
|
||||
String requestJson = "";
|
||||
ADC_MODE(ADC_VCC);
|
||||
|
||||
//Pins
|
||||
#define SENZORPIN 12 //12
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
WiFi.begin(WIFI_SSID, WIFI_PASS);
|
||||
checkConnection();
|
||||
Serial.print("TEST");
|
||||
jsonBuffer = {};
|
||||
jsonBuffer["token"] = HW_TOKEN;
|
||||
jsonBuffer["values"]["door"]["value"] = 0;
|
||||
|
||||
int batteryVoltage = (ESP.getVcc() + 600) / 1000;
|
||||
jsonBuffer["values"]["battery"]["value"] = batteryVoltage;
|
||||
|
||||
serializeJson(jsonBuffer, requestJson);
|
||||
sendHttpRequest(requestJson);
|
||||
|
||||
delay(500);
|
||||
ESP.deepSleep(0);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
||||
|
||||
void setStaticIp(String ipAddress, String subnet, String gateway){
|
||||
//Set static ip
|
||||
IPAddress staticIpAddress;
|
||||
IPAddress subnetIpAddress;
|
||||
IPAddress gatewayIpAddress;
|
||||
|
||||
if (
|
||||
staticIpAddress.fromString(ipAddress) &&
|
||||
subnetIpAddress.fromString(subnet) &&
|
||||
gatewayIpAddress.fromString(gateway) &&
|
||||
WiFi.localIP() != staticIpAddress
|
||||
) {
|
||||
WiFi.config(staticIpAddress, subnetIpAddress, gatewayIpAddress);
|
||||
Serial.print("STATIC IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
}
|
||||
}
|
||||
|
||||
String sendHttpRequest (String requestJson) {
|
||||
HTTPClient http;
|
||||
http.setReuse(true);
|
||||
http.begin(SERVER_ADRESS);
|
||||
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();
|
||||
|
||||
if (httpCode == -1) {
|
||||
ESP.restart();
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
bool checkConnection() {
|
||||
int count = 0;
|
||||
while ( count < 30 ) {
|
||||
delay(500);
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
return true;
|
||||
}
|
||||
count++;
|
||||
}
|
||||
return false;
|
||||
}
|
Before Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 28 KiB |
Before Width: | Height: | Size: 16 KiB |
@@ -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,153 +0,0 @@
|
||||
//Includes
|
||||
#include <DHT.h>
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
//Variables
|
||||
const char* ssid = "Smart-Home";
|
||||
const char* pasw = "S1pjg3684dcCPTUQ";
|
||||
const char* hwId = "45235sadad";
|
||||
const char* url = "http://dev.steelants.cz/vasek/home/api.php";
|
||||
int unsuccessfulRounds = 0;
|
||||
|
||||
//Pins
|
||||
#define pinDHT 4
|
||||
#define LIGHTPIN 13
|
||||
|
||||
//Inicializations
|
||||
DHT DHTs(pinDHT, DHT11);
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
while (!Serial) continue;
|
||||
delay(10);
|
||||
Serial.println('\n');
|
||||
//Show start up Configuration
|
||||
Serial.println("HW: " + String(hwId));
|
||||
Serial.print("IP address:\t");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("MAC address:\t");
|
||||
Serial.println(WiFi.macAddress());
|
||||
pinMode(LIGHTPIN, INPUT);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
//Start Conection to wifi
|
||||
WiFi.begin(ssid, pasw);
|
||||
checkConnection();
|
||||
|
||||
//HTTP CLIENT
|
||||
HTTPClient http;
|
||||
http.begin(url); //Begun HTTP Request
|
||||
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
|
||||
|
||||
DHTs.begin();
|
||||
|
||||
//JsonDocsDefinition
|
||||
StaticJsonDocument<265> doc;
|
||||
doc["token"] = hwId;
|
||||
|
||||
//Read and Handle DHT values
|
||||
float tem = DHTs.readTemperature();
|
||||
float hum = DHTs.readHumidity();
|
||||
Serial.println("TEMP" + String(tem) + ";HUMI" + String(hum));
|
||||
if (isnan(tem) || isnan(hum)) {
|
||||
Serial.println("Unable to read DHT");
|
||||
} else {
|
||||
doc["values"]["temp"]["value"] = tem;
|
||||
doc["values"]["temp"]["unit"] = "C";
|
||||
doc["values"]["humi"]["value"] = hum;
|
||||
doc["values"]["humi"]["unit"] = "%";
|
||||
}
|
||||
|
||||
//Handle Photo Rezistor Values
|
||||
doc["values"]["light"]["value"] = (String)!digitalRead(LIGHTPIN);
|
||||
doc["values"]["light"]["unit"] = "";
|
||||
|
||||
/*More Senzores to come*/
|
||||
String jsonPayload = "";
|
||||
serializeJson(doc, jsonPayload);
|
||||
Serial.print("JSON: ");
|
||||
Serial.println(jsonPayload);
|
||||
|
||||
int httpCode = http.POST(jsonPayload); //Get Http response code
|
||||
String httpPayload = http.getString(); //Get the response payload
|
||||
Serial.println("HTTP CODE: " + String(httpCode) + ""); //Print HTTP return code
|
||||
Serial.println("HTTP BODY: " + String(httpPayload) + ""); //Print request response payload
|
||||
|
||||
DeserializationError error = deserializeJson(doc, httpPayload); //Get deserialization Error if exists
|
||||
|
||||
//configuration setup
|
||||
int sleepTime = doc["device"]["sleepTime"];
|
||||
String hostName = doc["device"]["hostname"];
|
||||
String ipAddress = doc["device"]["ipAddress"];
|
||||
String gateway = doc["device"]["gateway"];
|
||||
String subnet = doc["device"]["subnet"];
|
||||
String state = doc["state"];
|
||||
|
||||
if (state != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + (String)unsuccessfulRounds + "FROM 5");
|
||||
} else if (state == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
|
||||
//Set static ip
|
||||
setStaticIp(ipAddress, gateway, subnet);
|
||||
WiFi.hostname(hostName); //Set HostName
|
||||
|
||||
http.end(); //Close connection
|
||||
WiFi.disconnect(); //Disconect from WIFI
|
||||
Serial.println("DISCONECTED FROM WIFI");
|
||||
|
||||
if(unsuccessfulRounds == 5) { //after 5 unsucessful request restart ESP
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
sleep(sleepTime);
|
||||
}
|
||||
|
||||
//checking if connection is working
|
||||
bool checkConnection() {
|
||||
int count = 0;
|
||||
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 setStaticIp(String IpAddress, String subnet, String gateway){
|
||||
//Set static ip
|
||||
IPAddress staticIpAddress;
|
||||
IPAddress subnetIpAddress;
|
||||
IPAddress gatewayIpAddress;
|
||||
|
||||
if (
|
||||
staticIpAddress.fromString(IpAddress) &&
|
||||
subnetIpAddress.fromString(subnet) &&
|
||||
gatewayIpAddress.fromString(gateway) &&
|
||||
WiFi.localIP() != staticIpAddress
|
||||
) {
|
||||
WiFi.config(staticIpAddress, subnetIpAddress, gatewayIpAddress);
|
||||
Serial.print("STATIC IP address:\t");
|
||||
Serial.println(WiFi.localIP());
|
||||
}
|
||||
}
|
||||
void sleep(int sleepTime) {
|
||||
if (sleepTime > 0) { //if deep sleepTime > 0 use deep sleep
|
||||
Serial.println("GOING TO SLEEP FOR " + String(sleepTime));
|
||||
ESP.deepSleep((sleepTime * 60) * 1000000, RF_DEFAULT);
|
||||
} else {
|
||||
delay(5000);
|
||||
}
|
||||
}
|
@@ -1,387 +0,0 @@
|
||||
//Includes
|
||||
#include <DHT.h>
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WebServer.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#define ARDUINOJSON_DECODE_UNICODE 1
|
||||
#include <ArduinoJson.h>
|
||||
#include <EEPROM.h>
|
||||
#include "ESP8266httpUpdate.h"
|
||||
|
||||
//Variables
|
||||
const char* ssidServer = "";
|
||||
const char* paswServer = "";
|
||||
String ssid = "";
|
||||
String pasw = "";
|
||||
String apiToken = "";
|
||||
const int httpsPort = 443;
|
||||
const char* host = "http://dev.steelants.cz";
|
||||
const char* url = "/vasek/home/api.php";
|
||||
|
||||
const char* fingerprint = "";
|
||||
const char* host2 = "dev.steelants.cz";
|
||||
const char* url2 = "/vasek/home/update.php";
|
||||
|
||||
String content;
|
||||
String Logs;
|
||||
bool conf = false;
|
||||
bool buttonActive = false;
|
||||
int state = 0;
|
||||
String requestJson = "";
|
||||
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
|
||||
|
||||
ESP8266WebServer server(80);
|
||||
StaticJsonDocument<265> jsonContent;
|
||||
DeserializationError error;
|
||||
|
||||
//Pins
|
||||
#define DHTPIN 2
|
||||
//#define LIGHTPIN 13
|
||||
|
||||
//Inicializations
|
||||
DHT DHTs(DHTPIN, DHT11);
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
EEPROM.begin(100);
|
||||
while (!Serial) continue;
|
||||
delay(10);
|
||||
//read saved data
|
||||
ssid = ReadEeprom(1, 33);
|
||||
pasw = ReadEeprom(33, 65);
|
||||
apiToken = ReadEeprom(65, 97);
|
||||
#if defined(LIGHTPIN)
|
||||
//set pins
|
||||
pinMode(LIGHTPIN, INPUT);
|
||||
#endif
|
||||
//wifi
|
||||
if (ssid != "") {
|
||||
WiFi.disconnect();
|
||||
WiFi.softAPdisconnect(true);
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, pasw);
|
||||
conf = wifiVerify(20);
|
||||
if (conf) {
|
||||
configTime(3 * 3600, 0, "pool.ntp.org");
|
||||
WiFiClientSecure client;
|
||||
Serial.print("connecting to ");
|
||||
Serial.println(host2);
|
||||
client.setInsecure();
|
||||
if (!client.connect(host2, httpsPort)) {
|
||||
addLog("connection failed");
|
||||
Serial.println("connection failed");
|
||||
return;
|
||||
}
|
||||
|
||||
if (client.verify(fingerprint, host2)) {
|
||||
Serial.println("certificate matches");
|
||||
} else {
|
||||
addLog("certificate doesn't match");
|
||||
Serial.println("certificate doesn't match");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.print("Starting OTA from: ");
|
||||
Serial.println(url2
|
||||
|
||||
);
|
||||
|
||||
auto ret = ESPhttpUpdate.update(client, host2, 80, url2);
|
||||
delay(500);
|
||||
switch(ret) {
|
||||
case HTTP_UPDATE_FAILED:
|
||||
addLog("HTTP_UPDATE_FAILD Error (" + (String)ESPhttpUpdate.getLastError() + ") : " + (String)ESPhttpUpdate.getLastErrorString().c_str());
|
||||
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
Serial.println("HTTP_UPDATE_OK");
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
}
|
||||
delay(500);
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
jsonContent["settings"]["network"]["ip"] = WiFi.localIP().toString();
|
||||
jsonContent["settings"]["network"]["mac"] = WiFi.macAddress();
|
||||
jsonContent["settings"]["firmware_hash"] = ESP.getSketchMD5();
|
||||
sendDataToWeb();
|
||||
return;
|
||||
}
|
||||
}
|
||||
setupAP();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (conf) {
|
||||
LogErrors();
|
||||
if (unsuccessfulRounds >= 5) {
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
DHTs.begin();
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
requestJson = "";
|
||||
|
||||
//Read and Handle DHT values
|
||||
float tem = DHTs.readTemperature();
|
||||
float hum = DHTs.readHumidity();
|
||||
Serial.println("TEMP" + String(tem) + ";HUMI" + String(hum));
|
||||
if (isnan(tem) || isnan(hum)) {
|
||||
Serial.println("Unable to read DHT");
|
||||
} else {
|
||||
jsonContent["values"]["temp"]["value"] = (String)tem;
|
||||
jsonContent["values"]["temp"]["unit"] = "C";
|
||||
jsonContent["values"]["humi"]["value"] = (String)hum;
|
||||
jsonContent["values"]["humi"]["unit"] = "%";
|
||||
}
|
||||
#if defined(LIGHTPIN)
|
||||
//Handle Photo Rezistor Values
|
||||
jsonContent["values"]["light"]["value"] = (String)!digitalRead(LIGHTPIN);
|
||||
jsonContent["values"]["light"]["unit"] = "";
|
||||
#endif
|
||||
sendDataToWeb();
|
||||
loadDataFromWeb();
|
||||
} else {
|
||||
server.handleClient();
|
||||
}
|
||||
}
|
||||
|
||||
bool wifiVerify(int t) {
|
||||
int c = 0;
|
||||
Serial.println("Waiting for Wifi");
|
||||
while (c < t) {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
c = t;
|
||||
return true;
|
||||
}
|
||||
delay(500);
|
||||
Serial.print(WiFi.status());
|
||||
c++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void loadDataFromWeb() {
|
||||
if (error.code() != DeserializationError::Ok) {
|
||||
addLog(error.c_str());
|
||||
Serial.println(error.c_str());
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
error = DeserializationError::Ok;
|
||||
return;
|
||||
}
|
||||
|
||||
//configuration setup
|
||||
int sleepTime = jsonContent["device"]["sleepTime"];
|
||||
String hostName = jsonContent["device"]["hostname"];
|
||||
String requestState = jsonContent["state"];
|
||||
String command = jsonContent["command"];
|
||||
|
||||
if (command == "reset"){
|
||||
command = "";
|
||||
ESP.reset();
|
||||
} else if (command == "config") {
|
||||
command = "";
|
||||
CleanEeprom();
|
||||
EEPROM.commit();
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
if (requestState != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
} else if (requestState == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
|
||||
WiFi.hostname(hostName);
|
||||
sleep(sleepTime);
|
||||
}
|
||||
|
||||
void sendDataToWeb() {
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
error = deserializeJson(jsonContent, sendHttpRequest());
|
||||
}
|
||||
|
||||
void sleep(int sleepTime) {
|
||||
if (sleepTime > 0) { //if deep sleepTime > 0 use deep sleep
|
||||
Serial.println("GOING TO SLEEP FOR " + String(sleepTime));
|
||||
ESP.deepSleep((sleepTime * 60) * 1000000, RF_DEFAULT);
|
||||
} else {
|
||||
delay(5000);
|
||||
}
|
||||
}
|
||||
|
||||
String sendHttpRequest () {
|
||||
HTTPClient http;
|
||||
http.setReuse(true);
|
||||
Serial.println("HTTP url: " + String(host) + String(url) + ""); //Print HTTP return code
|
||||
http.begin(String(host) + String(url));
|
||||
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
|
||||
Serial.println("HTTP request: " + String(requestJson) + ""); //Print HTTP return code
|
||||
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
|
||||
|
||||
if (httpCode == -1) {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return "";
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
void LogErrors() {
|
||||
jsonContent = {};
|
||||
error = deserializeJson(jsonContent, "{\"logs\":[" + Logs + "]}");
|
||||
jsonContent["token"] = apiToken;
|
||||
requestJson = "";
|
||||
Logs = "";
|
||||
sendDataToWeb();
|
||||
}
|
||||
|
||||
void addLog(String logText) {
|
||||
if (Logs == "") {
|
||||
Logs = "\"" + logText + "\"";
|
||||
} else {
|
||||
Logs += ",\"" + logText + "\"";
|
||||
}
|
||||
}
|
||||
|
||||
void CleanEeprom() {
|
||||
for (int i = 1; i < 100; ++i) {
|
||||
EEPROM.write(i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void WriteEeprom (String data, int start = 1) {
|
||||
for (int i = 0; i < data.length(); ++i)
|
||||
{
|
||||
EEPROM.write(start + i, data[i]);
|
||||
}
|
||||
EEPROM.commit();
|
||||
}
|
||||
|
||||
String ReadEeprom(int min, int max) {
|
||||
String localString;
|
||||
for (int i = min; i < max; ++i) {
|
||||
localString += char(EEPROM.read(i));
|
||||
}
|
||||
return localString;
|
||||
}
|
||||
|
||||
void createWeb()
|
||||
{
|
||||
server.on("/", []() {
|
||||
if (server.args() == 3) {
|
||||
ssid = server.arg("wifi-ssid");
|
||||
pasw = server.arg("wifi-pasw");
|
||||
apiToken = server.arg("apiToken");
|
||||
if (ssid != "" && pasw != "" && apiToken != "") {
|
||||
CleanEeprom();
|
||||
WriteEeprom(ssid);
|
||||
WriteEeprom(pasw, 33);
|
||||
WriteEeprom(apiToken, 65);
|
||||
server.send(200, "application/json", "Restarting esp");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
}
|
||||
}
|
||||
content = "<!DOCTYPE HTML><body>";
|
||||
content += "<head><style>";
|
||||
content += "html,body {height: 100%;}";
|
||||
content += "html {display: table;margin: auto;}";
|
||||
content += "body {display: table-cell;vertical-align: middle;}";
|
||||
content += "input {width: 100%;box-sizing: border-box}";
|
||||
content += "</style></head>";
|
||||
content += "<h2>WIFI Configuration</h2>";
|
||||
content += "<h4><b>" + (String)ssidServer + "</b></h4>";
|
||||
content += "<a href='#'>Refresh</a>";
|
||||
content += "<div class=\"wifi-list\">";
|
||||
int n = WiFi.scanNetworks();
|
||||
if (n == 0)
|
||||
content += "<label>No networks found...</label>";
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
content += "<a href=\"#\" onclick=\"fillSSID(this.innerHTML)\">" + WiFi.SSID(i) + "</a><br>";
|
||||
}
|
||||
}
|
||||
content += "</div>";
|
||||
content += "<form method='get' action=''><div class='wifi-form'>";
|
||||
content += "<label>SSID: </label><input name='wifi-ssid' id='wifi-ssid' length=32 type='text'><br>";
|
||||
content += "<label>Heslo: </label><input name='wifi-pasw' length=32 type='password'><br>";
|
||||
content += "<label>Api token: </label><input name='apiToken' length=32 type='password'><br>";
|
||||
content += "<input type='submit' value='Connect'>";
|
||||
content += "</div></form>";
|
||||
content += "<script>";
|
||||
content += "function fillSSID(value) {\r\n";
|
||||
content += "document.getElementById(\"wifi-ssid\").value = value;\r\n";
|
||||
content += "}";
|
||||
content += "</script>";
|
||||
content += "</body>";
|
||||
server.send(200, "text/html", content);
|
||||
});
|
||||
}
|
||||
|
||||
void setupAP(void) {
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.disconnect();
|
||||
WiFi.softAPdisconnect(true);
|
||||
delay(100);
|
||||
int n = WiFi.scanNetworks();
|
||||
Serial.println("scan done");
|
||||
if (n == 0)
|
||||
Serial.println("no networks found");
|
||||
else
|
||||
{
|
||||
Serial.print(n);
|
||||
Serial.println(" networks found");
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
// Print SSID and RSSI for each network found
|
||||
Serial.print(i + 1);
|
||||
Serial.print(": ");
|
||||
Serial.print(WiFi.SSID(i));
|
||||
Serial.print(" (");
|
||||
Serial.print(WiFi.RSSI(i));
|
||||
Serial.print(")");
|
||||
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
|
||||
delay(10);
|
||||
}
|
||||
}
|
||||
delay(100);
|
||||
WiFi.softAP(ssidServer, paswServer);
|
||||
Serial.println("softap");
|
||||
Serial.println("");
|
||||
Serial.println("WiFi connected");
|
||||
Serial.print("Local IP: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("SoftAP IP: ");
|
||||
Serial.println(WiFi.softAPIP());
|
||||
createWeb();
|
||||
// Start the server
|
||||
server.begin();
|
||||
Serial.println("Server started");
|
||||
Serial.println("over");
|
||||
}
|
Before Width: | Height: | Size: 21 KiB |
@@ -1,206 +0,0 @@
|
||||
//Includes
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <EEPROM.h>
|
||||
|
||||
//Variables
|
||||
const char* ssid = "ssid";
|
||||
const char* pasw = "pasw";
|
||||
const char* hwId = "hwId";
|
||||
const char* server = "http://dev.steelants.cz/vasek/home/api.php";
|
||||
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
|
||||
StaticJsonDocument<250> jsonContent;
|
||||
bool buttonActive = false;
|
||||
int interuptCount = 0;
|
||||
int realState = 0;
|
||||
int state = 0;
|
||||
String requestJson = "";
|
||||
|
||||
//Pins
|
||||
#define RELAY 4 //12
|
||||
#define SWITCH 5 //0
|
||||
|
||||
void ICACHE_RAM_ATTR handleInterrupt ();
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
EEPROM.begin(1);
|
||||
while (!Serial) continue;
|
||||
delay(10);
|
||||
Serial.println('\n');
|
||||
Serial.println("HW: " + String(hwId));
|
||||
|
||||
pinMode(SWITCH, INPUT);
|
||||
pinMode(RELAY, OUTPUT);
|
||||
state = EEPROM.read(0);
|
||||
digitalWrite(RELAY, state);
|
||||
realState = state;
|
||||
|
||||
attachInterrupt(digitalPinToInterrupt(SWITCH), handleInterrupt, CHANGE);
|
||||
|
||||
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
WiFi.begin(ssid, pasw);
|
||||
checkConnection();
|
||||
|
||||
Serial.println('\n');
|
||||
Serial.println("Connection established!");
|
||||
Serial.print("IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("MAC address:");
|
||||
Serial.println(WiFi.macAddress());
|
||||
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
jsonContent["values"]["on/off"]["value"] = (String)realState;
|
||||
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if(unsuccessfulRounds >= 5) {
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
requestJson = "";
|
||||
if (buttonActive){
|
||||
int realStateLocal = digitalRead(SWITCH);
|
||||
jsonContent["values"]["on/off"]["value"] = (String)realStateLocal;
|
||||
digitalWrite(RELAY, realStateLocal);
|
||||
realState = realStateLocal;
|
||||
EEPROM.write(0, realState);
|
||||
EEPROM.commit();
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
|
||||
//HTTP CLIENT
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
buttonActive = false;
|
||||
}
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
requestJson = "";
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
|
||||
//HTTP CLIENT
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
|
||||
if (error) {
|
||||
Serial.println(error.c_str());
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return;
|
||||
}
|
||||
//configuration setup
|
||||
String hostName = jsonContent["device"]["hostname"];
|
||||
String ipAddress = jsonContent["device"]["ipAddress"];
|
||||
String gateway = jsonContent["device"]["gateway"];
|
||||
String subnet = jsonContent["device"]["subnet"];
|
||||
String requestState = jsonContent["state"];
|
||||
JsonObject object = jsonContent.as<JsonObject>();
|
||||
if (!object["value"].isNull()) {
|
||||
state = (int)jsonContent["value"];
|
||||
}
|
||||
|
||||
if (requestState != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
} else if (requestState == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
|
||||
//Set static ip
|
||||
setStaticIp(ipAddress, gateway, subnet);
|
||||
WiFi.hostname(hostName);
|
||||
Serial.println("state: " + (String)state + ", realState: " + (String)realState);
|
||||
if (state != realState){
|
||||
if (state == 1 && realState == 0) {
|
||||
Serial.println("ON state: " + (String)state + ", realState: " + (String)realState);
|
||||
digitalWrite(RELAY, HIGH); // Turn the LED on by making the voltage LOW
|
||||
realState = 1;
|
||||
} else {
|
||||
Serial.println("OFF");
|
||||
digitalWrite(RELAY, LOW); // Turn the LED on by making the voltage LOW
|
||||
realState = 0;
|
||||
}
|
||||
EEPROM.write(0, realState);
|
||||
EEPROM.commit();
|
||||
}
|
||||
}
|
||||
|
||||
void handleInterrupt() {
|
||||
interuptCount++;
|
||||
buttonActive = true;
|
||||
}
|
||||
|
||||
String sendHttpRequest (String requestJson) {
|
||||
HTTPClient http;
|
||||
http.setReuse(true);
|
||||
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
|
||||
|
||||
if (httpCode == -1) {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return "";
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
bool checkConnection() {
|
||||
int count = 0;
|
||||
Serial.print("Waiting for Wi-Fi connection");
|
||||
while ( count < 30 ) {
|
||||
if (buttonActive){
|
||||
int realStateLocal = digitalRead(SWITCH);
|
||||
digitalWrite(RELAY, realStateLocal);
|
||||
realState = realStateLocal;
|
||||
EEPROM.write(0, realState);
|
||||
EEPROM.commit();
|
||||
buttonActive = false;
|
||||
}
|
||||
delay(250);
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.println();
|
||||
Serial.println("Connected!");
|
||||
return (true);
|
||||
}
|
||||
Serial.print(".");
|
||||
count++;
|
||||
}
|
||||
Serial.println("Timed out.");
|
||||
return false;
|
||||
}
|
||||
|
||||
void setStaticIp(String ipAddress, String subnet, String gateway){
|
||||
//Set static ip
|
||||
IPAddress staticIpAddress;
|
||||
IPAddress subnetIpAddress;
|
||||
IPAddress gatewayIpAddress;
|
||||
|
||||
if (
|
||||
staticIpAddress.fromString(ipAddress) &&
|
||||
subnetIpAddress.fromString(subnet) &&
|
||||
gatewayIpAddress.fromString(gateway) &&
|
||||
WiFi.localIP() != staticIpAddress
|
||||
) {
|
||||
WiFi.config(staticIpAddress, subnetIpAddress, gatewayIpAddress);
|
||||
Serial.print("STATIC IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
}
|
||||
}
|
@@ -1,360 +0,0 @@
|
||||
//Includes
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WebServer.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#define ARDUINOJSON_DECODE_UNICODE 1
|
||||
#include <ArduinoJson.h>
|
||||
#include <EEPROM.h>
|
||||
#include "ESP8266httpUpdate.h"
|
||||
|
||||
//Variables
|
||||
const char* ssidServer = "";
|
||||
const char* paswServer = "";
|
||||
String ssid = "";
|
||||
String pasw = "";
|
||||
String apiToken = "";
|
||||
const int httpsPort = 443;
|
||||
const char* host = "http://dev.steelants.cz";
|
||||
const char* url = "/vasek/home/api.php";
|
||||
|
||||
const char* fingerprint = "";
|
||||
const char* host2 = "dev.steelants.cz";
|
||||
const char* url2 = "/vasek/home/update.php";
|
||||
|
||||
String content;
|
||||
bool conf = false;
|
||||
bool buttonActive = false;
|
||||
int state = 0;
|
||||
String requestJson = "";
|
||||
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
|
||||
|
||||
ESP8266WebServer server(80);
|
||||
StaticJsonDocument<250> jsonContent;
|
||||
DeserializationError error;
|
||||
|
||||
//Pins
|
||||
#define RELAY 4 //12
|
||||
#define SWITCH 5 //0
|
||||
|
||||
void ICACHE_RAM_ATTR handleInterrupt ();
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
EEPROM.begin(100);
|
||||
while (!Serial) continue;
|
||||
delay(10);
|
||||
//read saved data
|
||||
ssid = ReadEeprom(1, 33);
|
||||
pasw = ReadEeprom(33, 65);
|
||||
apiToken = ReadEeprom(65, 97);
|
||||
//set pins
|
||||
pinMode(SWITCH, INPUT);
|
||||
pinMode(RELAY, OUTPUT);
|
||||
state = EEPROM.read(0);
|
||||
digitalWrite(RELAY, state);
|
||||
attachInterrupt(digitalPinToInterrupt(SWITCH), handleInterrupt, CHANGE);
|
||||
//wifi
|
||||
if (ssid != "") {
|
||||
WiFi.disconnect();
|
||||
WiFi.softAPdisconnect(true);
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, pasw);
|
||||
conf = wifiVerify(20);
|
||||
if (conf) {
|
||||
configTime(3 * 3600, 0, "pool.ntp.org");
|
||||
WiFiClientSecure client;
|
||||
Serial.print("connecting to ");
|
||||
Serial.println(host2);
|
||||
client.setInsecure();
|
||||
if (!client.connect(host2, httpsPort)) {
|
||||
Serial.println("connection failed");
|
||||
return;
|
||||
}
|
||||
|
||||
if (client.verify(fingerprint, host2)) {
|
||||
Serial.println("certificate matches");
|
||||
} else {
|
||||
Serial.println("certificate doesn't match");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.print("Starting OTA from: ");
|
||||
Serial.println(url2
|
||||
|
||||
);
|
||||
|
||||
auto ret = ESPhttpUpdate.update(client, host2, 80, url2);
|
||||
delay(500);
|
||||
switch(ret) {
|
||||
case HTTP_UPDATE_FAILED:
|
||||
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
Serial.println("HTTP_UPDATE_OK");
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
}
|
||||
delay(500);
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
jsonContent["values"]["on/off"]["value"] = (String)state;
|
||||
jsonContent["settings"]["network"]["ip"] = WiFi.localIP().toString();
|
||||
jsonContent["settings"]["network"]["mac"] = WiFi.macAddress();
|
||||
jsonContent["settings"]["firmware_hash"] = ESP.getSketchMD5();
|
||||
sendDataToWeb();
|
||||
return;
|
||||
}
|
||||
}
|
||||
setupAP();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (conf) {
|
||||
if (unsuccessfulRounds >= 5) {
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
if (buttonActive) {
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
requestJson = "";
|
||||
jsonContent["values"]["on/off"]["value"] = (String)state;
|
||||
digitalWrite(RELAY, state);
|
||||
EEPROM.write(0, state);
|
||||
EEPROM.commit();
|
||||
sendDataToWeb();
|
||||
buttonActive = false;
|
||||
delay(500);
|
||||
} else {
|
||||
loadDataFromWeb();
|
||||
}
|
||||
} else {
|
||||
server.handleClient();
|
||||
}
|
||||
}
|
||||
|
||||
void handleInterrupt() {
|
||||
buttonActive = true;
|
||||
state = !state;
|
||||
digitalWrite(RELAY, state);
|
||||
}
|
||||
|
||||
bool wifiVerify(int t) {
|
||||
int c = 0;
|
||||
Serial.println("Waiting for Wifi to connect to Shelly1");
|
||||
while (c < t) {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
c = t;
|
||||
return true;
|
||||
}
|
||||
delay(500);
|
||||
Serial.print(WiFi.status());
|
||||
c++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void loadDataFromWeb() {
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
requestJson = "";
|
||||
sendDataToWeb();
|
||||
|
||||
if (error.code() != DeserializationError::Ok) {
|
||||
Serial.println(error.c_str());
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
error = DeserializationError::Ok;
|
||||
return;
|
||||
}
|
||||
|
||||
//configuration setup
|
||||
String hostName = jsonContent["device"]["hostname"];
|
||||
String requestState = jsonContent["state"];
|
||||
String command = jsonContent["command"];
|
||||
if (!buttonActive) {
|
||||
state = (int)jsonContent["value"];
|
||||
Serial.println("state: " + (String)state);
|
||||
digitalWrite(RELAY, state);
|
||||
EEPROM.write(0, state);
|
||||
EEPROM.commit();
|
||||
delay(500);
|
||||
}
|
||||
|
||||
if (command == "reset"){
|
||||
ESP.reset();
|
||||
} else if (command == "config") {
|
||||
CleanEeprom();
|
||||
EEPROM.commit();
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
if (requestState != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
} else if (requestState == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
|
||||
WiFi.hostname(hostName);
|
||||
}
|
||||
|
||||
void sendDataToWeb() {
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
error = deserializeJson(jsonContent, sendHttpRequest());
|
||||
}
|
||||
|
||||
String sendHttpRequest () {
|
||||
HTTPClient http;
|
||||
http.setReuse(true);
|
||||
Serial.println("HTTP url: " + String(host) + String(url) + ""); //Print HTTP return code
|
||||
http.begin(String(host) + String(url));
|
||||
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
|
||||
Serial.println("HTTP request: " + String(requestJson) + ""); //Print HTTP return code
|
||||
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
|
||||
|
||||
if (httpCode == -1) {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return "";
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
void CleanEeprom() {
|
||||
for (int i = 1; i < 100; ++i) {
|
||||
EEPROM.write(i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void WriteEeprom (String data, int start = 1) {
|
||||
for (int i = 0; i < data.length(); ++i)
|
||||
{
|
||||
EEPROM.write(start + i, data[i]);
|
||||
}
|
||||
EEPROM.commit();
|
||||
}
|
||||
|
||||
String ReadEeprom(int min, int max) {
|
||||
String localString;
|
||||
for (int i = min; i < max; ++i) {
|
||||
localString += char(EEPROM.read(i));
|
||||
}
|
||||
return localString;
|
||||
}
|
||||
|
||||
void createWeb()
|
||||
{
|
||||
server.on("/", []() {
|
||||
if (server.args() == 3) {
|
||||
ssid = server.arg("wifi-ssid");
|
||||
pasw = server.arg("wifi-pasw");
|
||||
apiToken = server.arg("apiToken");
|
||||
if (ssid != "" && pasw != "" && apiToken != "") {
|
||||
CleanEeprom();
|
||||
WriteEeprom(ssid);
|
||||
WriteEeprom(pasw, 33);
|
||||
WriteEeprom(apiToken, 65);
|
||||
server.send(200, "application/json", "Restarting esp");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
}
|
||||
}
|
||||
content = "<!DOCTYPE HTML><body>";
|
||||
content += "<head><style>";
|
||||
content += "html,body {height: 100%;}";
|
||||
content += "html {display: table;margin: auto;}";
|
||||
content += "body {display: table-cell;vertical-align: middle;}";
|
||||
content += "input {width: 100%;box-sizing: border-box}";
|
||||
content += "</style></head>";
|
||||
content += "<h2>WIFI Configuration</h2>";
|
||||
content += "<a href='#'>Refresh</a>";
|
||||
content += "<div class=\"wifi-list\">";
|
||||
int n = WiFi.scanNetworks();
|
||||
if (n == 0)
|
||||
content += "<label>No networks found...</label>";
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
content += "<a href=\"#\" onclick=\"fillSSID(this.innerHTML)\">" + WiFi.SSID(i) + "</a><br>";
|
||||
}
|
||||
}
|
||||
content += "</div>";
|
||||
content += "<form method='get' action=''><div class='wifi-form'>";
|
||||
content += "<label>SSID: </label><input name='wifi-ssid' id='wifi-ssid' length=32 type='text'><br>";
|
||||
content += "<label>Heslo: </label><input name='wifi-pasw' length=32 type='password'><br>";
|
||||
content += "<label>Api token: </label><input name='apiToken' length=32 type='password'><br>";
|
||||
content += "<input type='submit' value='Connect'>";
|
||||
content += "</div></form>";
|
||||
content += "<script>";
|
||||
content += "function fillSSID(value) {\r\n";
|
||||
content += "document.getElementById(\"wifi-ssid\").value = value;\r\n";
|
||||
content += "}";
|
||||
content += "</script>";
|
||||
content += "</body>";
|
||||
server.send(200, "text/html", content);
|
||||
});
|
||||
}
|
||||
|
||||
void setupAP(void) {
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.disconnect();
|
||||
WiFi.softAPdisconnect(true);
|
||||
delay(100);
|
||||
int n = WiFi.scanNetworks();
|
||||
Serial.println("scan done");
|
||||
if (n == 0)
|
||||
Serial.println("no networks found");
|
||||
else
|
||||
{
|
||||
Serial.print(n);
|
||||
Serial.println(" networks found");
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
// Print SSID and RSSI for each network found
|
||||
Serial.print(i + 1);
|
||||
Serial.print(": ");
|
||||
Serial.print(WiFi.SSID(i));
|
||||
Serial.print(" (");
|
||||
Serial.print(WiFi.RSSI(i));
|
||||
Serial.print(")");
|
||||
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
|
||||
delay(10);
|
||||
}
|
||||
}
|
||||
delay(100);
|
||||
WiFi.softAP(ssidServer, paswServer);
|
||||
Serial.println("softap");
|
||||
Serial.println("");
|
||||
Serial.println("WiFi connected");
|
||||
Serial.print("Local IP: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("SoftAP IP: ");
|
||||
Serial.println(WiFi.softAPIP());
|
||||
createWeb();
|
||||
// Start the server
|
||||
server.begin();
|
||||
Serial.println("Server started");
|
||||
Serial.println("over");
|
||||
}
|
Before Width: | Height: | Size: 19 KiB |
@@ -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,221 +0,0 @@
|
||||
//Includes
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <EEPROM.h>
|
||||
|
||||
//Variables
|
||||
const char* ssid = "Smart-Home";
|
||||
const char* pasw = "S1pjg3684dcCPTUQ";
|
||||
const char* hwId = "452r5s8dad";
|
||||
const char* server = "http://dev.steelants.cz/vasek/home/api.php";
|
||||
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
|
||||
StaticJsonDocument<250> jsonContent;
|
||||
bool buttonActive = false;
|
||||
int interuptCount = 0;
|
||||
int realState = 1;
|
||||
int state = 0;
|
||||
String requestJson = "";
|
||||
|
||||
//Pins
|
||||
#define SONOFF 12 //12
|
||||
#define SONOFF_LED 13
|
||||
#define SONOFF_BUT 0 //0
|
||||
|
||||
void ICACHE_RAM_ATTR handleInterrupt ();
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
EEPROM.begin(1);
|
||||
while (!Serial) continue;
|
||||
delay(10);
|
||||
Serial.println('\n');
|
||||
Serial.println("HW: " + String(hwId));
|
||||
|
||||
pinMode(SONOFF_LED, OUTPUT);
|
||||
pinMode(SONOFF_BUT, INPUT_PULLUP);
|
||||
pinMode(SONOFF, OUTPUT);
|
||||
state = EEPROM.read(0);
|
||||
digitalWrite(SONOFF, state);
|
||||
realState = state;
|
||||
|
||||
attachInterrupt(digitalPinToInterrupt(SONOFF_BUT), handleInterrupt, FALLING);
|
||||
|
||||
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
WiFi.begin(ssid, pasw);
|
||||
checkConnection();
|
||||
|
||||
Serial.println('\n');
|
||||
Serial.println("Connection established!");
|
||||
Serial.print("IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("MAC address:");
|
||||
Serial.println(WiFi.macAddress());
|
||||
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
jsonContent["values"]["on/off"]["value"] = (String)realState;
|
||||
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if(unsuccessfulRounds >= 5) {
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
requestJson = "";
|
||||
if (buttonActive == true){
|
||||
jsonContent["values"]["on/off"]["value"] = (String)!realState;
|
||||
if (!realState == 1) {
|
||||
digitalWrite(SONOFF, HIGH);
|
||||
realState = 1;
|
||||
} else if (!realState == 0){
|
||||
digitalWrite(SONOFF, LOW);
|
||||
realState = 0;
|
||||
}
|
||||
EEPROM.write(0, 0);
|
||||
EEPROM.commit();
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
|
||||
//HTTP CLIENT
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
buttonActive = false;
|
||||
}
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
|
||||
requestJson = "";
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
|
||||
//HTTP CLIENT
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
|
||||
if (error) {
|
||||
Serial.println(error.c_str());
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return;
|
||||
}
|
||||
//configuration setup
|
||||
String hostName = jsonContent["device"]["hostname"];
|
||||
String ipAddress = jsonContent["device"]["ipAddress"];
|
||||
String gateway = jsonContent["device"]["gateway"];
|
||||
String subnet = jsonContent["device"]["subnet"];
|
||||
String requestState = jsonContent["state"];
|
||||
JsonObject object = jsonContent.as<JsonObject>();
|
||||
if (!object["value"].isNull()) {
|
||||
state = (int)jsonContent["value"];
|
||||
}
|
||||
|
||||
if (requestState != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
} else if (requestState == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
|
||||
//Set static ip
|
||||
setStaticIp(ipAddress, gateway, subnet);
|
||||
WiFi.hostname(hostName);
|
||||
Serial.println("state: " + (String)state + ", realState: " + (String)realState);
|
||||
if (state != realState){
|
||||
if (state == 1 && realState == 0) {
|
||||
Serial.println("ON state: " + (String)state + ", realState: " + (String)realState);
|
||||
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
|
||||
realState = 1;
|
||||
} else if (state == 0 && realState == 1) {
|
||||
Serial.println("OFF");
|
||||
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
|
||||
realState = 0;
|
||||
}
|
||||
EEPROM.write(0, realState);
|
||||
EEPROM.commit();
|
||||
}
|
||||
}
|
||||
|
||||
void handleInterrupt() {
|
||||
interuptCount++;
|
||||
buttonActive = true;
|
||||
}
|
||||
|
||||
String sendHttpRequest (String requestJson) {
|
||||
HTTPClient http;
|
||||
http.setReuse(true);
|
||||
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
|
||||
|
||||
if (httpCode == -1) {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return "";
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
bool checkConnection() {
|
||||
int count = 0;
|
||||
Serial.print("Waiting for Wi-Fi connection");
|
||||
while ( count < 30 ) {
|
||||
if (buttonActive == true){
|
||||
if (!realState == 1) {
|
||||
digitalWrite(SONOFF, HIGH);
|
||||
realState = 1;
|
||||
} else if (!realState == 0){
|
||||
digitalWrite(SONOFF, LOW);
|
||||
realState = 0;
|
||||
}
|
||||
EEPROM.write(0, realState);
|
||||
EEPROM.commit();
|
||||
buttonActive = false;
|
||||
}
|
||||
digitalWrite(SONOFF_LED, HIGH);
|
||||
delay(125);
|
||||
digitalWrite(SONOFF_LED, LOW);
|
||||
delay(125);
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.println();
|
||||
Serial.println("Connected!");
|
||||
digitalWrite(SONOFF_LED, HIGH);
|
||||
return (true);
|
||||
}
|
||||
Serial.print(".");
|
||||
count++;
|
||||
}
|
||||
Serial.println("Timed out.");
|
||||
return false;
|
||||
}
|
||||
|
||||
void setStaticIp(String ipAddress, String subnet, String gateway){
|
||||
//Set static ip
|
||||
IPAddress staticIpAddress;
|
||||
IPAddress subnetIpAddress;
|
||||
IPAddress gatewayIpAddress;
|
||||
|
||||
if (
|
||||
staticIpAddress.fromString(ipAddress) &&
|
||||
subnetIpAddress.fromString(subnet) &&
|
||||
gatewayIpAddress.fromString(gateway) &&
|
||||
WiFi.localIP() != staticIpAddress
|
||||
) {
|
||||
WiFi.config(staticIpAddress, subnetIpAddress, gatewayIpAddress);
|
||||
Serial.print("STATIC IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
}
|
||||
}
|
@@ -1,373 +0,0 @@
|
||||
//Includes
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WebServer.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#define ARDUINOJSON_DECODE_UNICODE 1
|
||||
#include <ArduinoJson.h>
|
||||
#include <EEPROM.h>
|
||||
#include "ESP8266httpUpdate.h"
|
||||
|
||||
//Variables
|
||||
const char* ssidServer = "";
|
||||
const char* paswServer = "";
|
||||
String ssid = "";
|
||||
String pasw = "";
|
||||
String apiToken = "";
|
||||
const int httpsPort = 443;
|
||||
const char* host = "http://dev.steelants.cz";
|
||||
const char* url = "/vasek/home/api.php";
|
||||
|
||||
const char* fingerprint = "";
|
||||
const char* host2 = "dev.steelants.cz";
|
||||
const char* url2 = "/vasek/home/update.php";
|
||||
|
||||
String content;
|
||||
bool conf = false;
|
||||
bool buttonActive = false;
|
||||
int state = 0;
|
||||
String requestJson = "";
|
||||
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
|
||||
|
||||
ESP8266WebServer server(80);
|
||||
StaticJsonDocument<250> jsonContent;
|
||||
DeserializationError error;
|
||||
|
||||
//Pins
|
||||
#define SONOFF 12
|
||||
#define SONOFF_LED 13
|
||||
#define SONOFF_BUT 0 //0
|
||||
|
||||
void ICACHE_RAM_ATTR handleInterrupt ();
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
EEPROM.begin(100);
|
||||
while (!Serial) continue;
|
||||
delay(10);
|
||||
|
||||
//read saved data
|
||||
ssid = ReadEeprom(1, 33);
|
||||
pasw = ReadEeprom(33, 65);
|
||||
apiToken = ReadEeprom(65, 97);
|
||||
|
||||
//set pins
|
||||
pinMode(SONOFF_LED, OUTPUT);
|
||||
pinMode(SONOFF_BUT, INPUT_PULLUP);
|
||||
pinMode(SONOFF, OUTPUT);
|
||||
state = EEPROM.read(0);
|
||||
digitalWrite(SONOFF, state);
|
||||
|
||||
attachInterrupt(digitalPinToInterrupt(SONOFF_BUT), handleInterrupt, FALLING);
|
||||
|
||||
//wifi
|
||||
if (ssid != "") {
|
||||
WiFi.disconnect();
|
||||
WiFi.softAPdisconnect(true);
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, pasw);
|
||||
conf = wifiVerify(20);
|
||||
if (conf) {
|
||||
configTime(3 * 3600, 0, "pool.ntp.org");
|
||||
WiFiClientSecure client;
|
||||
Serial.print("connecting to ");
|
||||
Serial.println(host2);
|
||||
client.setInsecure();
|
||||
if (!client.connect(host2, httpsPort)) {
|
||||
Serial.println("connection failed");
|
||||
return;
|
||||
}
|
||||
|
||||
if (client.verify(fingerprint, host2)) {
|
||||
Serial.println("certificate matches");
|
||||
} else {
|
||||
Serial.println("certificate doesn't match");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.print("Starting OTA from: ");
|
||||
Serial.println(url2
|
||||
|
||||
);
|
||||
|
||||
auto ret = ESPhttpUpdate.update(client, host2, 80, url2);
|
||||
delay(500);
|
||||
switch(ret) {
|
||||
case HTTP_UPDATE_FAILED:
|
||||
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
Serial.println("HTTP_UPDATE_OK");
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
}
|
||||
delay(500);
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
jsonContent["values"]["on/off"]["value"] = (String)state;
|
||||
jsonContent["settings"]["network"]["ip"] = WiFi.localIP().toString();
|
||||
jsonContent["settings"]["network"]["mac"] = WiFi.macAddress();
|
||||
jsonContent["settings"]["firmware_hash"] = ESP.getSketchMD5();
|
||||
sendDataToWeb();
|
||||
return;
|
||||
}
|
||||
}
|
||||
setupAP();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (conf) {
|
||||
if (unsuccessfulRounds >= 5) {
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
requestJson = "";
|
||||
if (buttonActive) {
|
||||
jsonContent["values"]["on/off"]["value"] = (String)state;
|
||||
digitalWrite(SONOFF, state);
|
||||
EEPROM.write(0, state);
|
||||
EEPROM.commit();
|
||||
sendDataToWeb();
|
||||
buttonActive = false;
|
||||
delay(500);
|
||||
} else {
|
||||
sendDataToWeb();
|
||||
loadDataFromWeb();
|
||||
}
|
||||
} else {
|
||||
server.handleClient();
|
||||
}
|
||||
}
|
||||
|
||||
void handleInterrupt() {
|
||||
buttonActive = true;
|
||||
state = !state;
|
||||
digitalWrite(SONOFF, state);
|
||||
}
|
||||
|
||||
bool wifiVerify(int t) {
|
||||
int c = 0;
|
||||
Serial.println("Waiting for Wifi to connect to Shelly1");
|
||||
while (c < t) {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
c = t;
|
||||
Serial.println();
|
||||
Serial.println("Connected!");
|
||||
digitalWrite(SONOFF_LED, HIGH);
|
||||
return true;
|
||||
}
|
||||
if (buttonActive == true){
|
||||
digitalWrite(SONOFF, state);
|
||||
EEPROM.write(0, state);
|
||||
EEPROM.commit();
|
||||
buttonActive = false;
|
||||
}
|
||||
digitalWrite(SONOFF_LED, HIGH);
|
||||
delay(125);
|
||||
digitalWrite(SONOFF_LED, LOW);
|
||||
delay(375);
|
||||
Serial.print(WiFi.status());
|
||||
c++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void loadDataFromWeb() {
|
||||
if (error.code() != DeserializationError::Ok) {
|
||||
Serial.println(error.c_str());
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
error = DeserializationError::Ok;
|
||||
return;
|
||||
}
|
||||
|
||||
//configuration setup
|
||||
String hostName = jsonContent["device"]["hostname"];
|
||||
String requestState = jsonContent["state"];
|
||||
String command = jsonContent["command"];
|
||||
if (!buttonActive) {
|
||||
state = (int)jsonContent["value"];
|
||||
Serial.println("state: " + (String)state);
|
||||
digitalWrite(SONOFF, state);
|
||||
EEPROM.write(0, state);
|
||||
EEPROM.commit();
|
||||
delay(500);
|
||||
}
|
||||
|
||||
if (command == "reset"){
|
||||
ESP.reset();
|
||||
} else if (command == "config") {
|
||||
CleanEeprom();
|
||||
EEPROM.commit();
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
if (requestState != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
} else if (requestState == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
WiFi.hostname(hostName);
|
||||
}
|
||||
|
||||
void sendDataToWeb() {
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
error = deserializeJson(jsonContent, sendHttpRequest());
|
||||
}
|
||||
|
||||
String sendHttpRequest () {
|
||||
HTTPClient http;
|
||||
http.setReuse(true);
|
||||
Serial.println("HTTP url: " + String(host) + String(url) + ""); //Print HTTP return code
|
||||
http.begin(String(host) + String(url));
|
||||
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
|
||||
Serial.println("HTTP request: " + String(requestJson) + ""); //Print HTTP return code
|
||||
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
|
||||
|
||||
if (httpCode == -1) {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return "";
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
void CleanEeprom() {
|
||||
for (int i = 1; i < 100; ++i) {
|
||||
EEPROM.write(i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void WriteEeprom (String data, int start = 1) {
|
||||
for (int i = 0; i < data.length(); ++i)
|
||||
{
|
||||
EEPROM.write(start + i, data[i]);
|
||||
}
|
||||
EEPROM.commit();
|
||||
}
|
||||
|
||||
String ReadEeprom(int min, int max) {
|
||||
String localString;
|
||||
for (int i = min; i < max; ++i) {
|
||||
localString += char(EEPROM.read(i));
|
||||
}
|
||||
return localString;
|
||||
}
|
||||
|
||||
void createWeb()
|
||||
{
|
||||
server.on("/", []() {
|
||||
if (server.args() == 3) {
|
||||
ssid = server.arg("wifi-ssid");
|
||||
pasw = server.arg("wifi-pasw");
|
||||
apiToken = server.arg("apiToken");
|
||||
if (ssid != "" && pasw != "" && apiToken != "") {
|
||||
CleanEeprom();
|
||||
WriteEeprom(ssid);
|
||||
WriteEeprom(pasw, 33);
|
||||
WriteEeprom(apiToken, 65);
|
||||
server.send(200, "application/json", "Restarting esp");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
}
|
||||
}
|
||||
content = "<!DOCTYPE HTML><body>";
|
||||
content += "<head><style>";
|
||||
content += "html,body {height: 100%;}";
|
||||
content += "html {display: table;margin: auto;}";
|
||||
content += "body {display: table-cell;vertical-align: middle;}";
|
||||
content += "input {width: 100%;box-sizing: border-box}";
|
||||
content += "</style></head>";
|
||||
content += "<h2>WIFI Configuration</h2>";
|
||||
content += "<h4><b>" + (String)ssidServer + "</b></h4>";
|
||||
content += "<a href='#'>Refresh</a>";
|
||||
content += "<div class=\"wifi-list\">";
|
||||
int n = WiFi.scanNetworks();
|
||||
if (n == 0)
|
||||
content += "<label>No networks found...</label>";
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
content += "<a href=\"#\" onclick=\"fillSSID(this.innerHTML)\">" + WiFi.SSID(i) + "</a><br>";
|
||||
}
|
||||
}
|
||||
content += "</div>";
|
||||
content += "<form method='get' action=''><div class='wifi-form'>";
|
||||
content += "<label>SSID: </label><input name='wifi-ssid' id='wifi-ssid' length=32 type='text'><br>";
|
||||
content += "<label>Heslo: </label><input name='wifi-pasw' length=32 type='password'><br>";
|
||||
content += "<label>Api token: </label><input name='apiToken' length=32 type='password'><br>";
|
||||
content += "<input type='submit' value='Connect'>";
|
||||
content += "</div></form>";
|
||||
content += "<script>";
|
||||
content += "function fillSSID(value) {\r\n";
|
||||
content += "document.getElementById(\"wifi-ssid\").value = value;\r\n";
|
||||
content += "}";
|
||||
content += "</script>";
|
||||
content += "</body>";
|
||||
server.send(200, "text/html", content);
|
||||
});
|
||||
}
|
||||
|
||||
void setupAP(void) {
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.disconnect();
|
||||
WiFi.softAPdisconnect(true);
|
||||
delay(100);
|
||||
int n = WiFi.scanNetworks();
|
||||
Serial.println("scan done");
|
||||
if (n == 0)
|
||||
Serial.println("no networks found");
|
||||
else
|
||||
{
|
||||
Serial.print(n);
|
||||
Serial.println(" networks found");
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
// Print SSID and RSSI for each network found
|
||||
Serial.print(i + 1);
|
||||
Serial.print(": ");
|
||||
Serial.print(WiFi.SSID(i));
|
||||
Serial.print(" (");
|
||||
Serial.print(WiFi.RSSI(i));
|
||||
Serial.print(")");
|
||||
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
|
||||
delay(10);
|
||||
}
|
||||
}
|
||||
delay(100);
|
||||
WiFi.softAP(ssidServer, paswServer);
|
||||
Serial.println("softap");
|
||||
Serial.println("");
|
||||
Serial.println("WiFi connected");
|
||||
Serial.print("Local IP: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("SoftAP IP: ");
|
||||
Serial.println(WiFi.softAPIP());
|
||||
createWeb();
|
||||
// Start the server
|
||||
server.begin();
|
||||
Serial.println("Server started");
|
||||
Serial.println("over");
|
||||
}
|
@@ -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;
|
||||
}
|
@@ -1,150 +0,0 @@
|
||||
//Includes
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
//Variables
|
||||
const char* ssid = "";
|
||||
const char* pasw = "";
|
||||
const char* hwId = "";
|
||||
const char* server = "http://dev.steelants.cz/vasek/home/api.php";
|
||||
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
|
||||
int lastState = 0;
|
||||
|
||||
//Pins
|
||||
#define SONOFF 12
|
||||
#define SONOFF_LED 13
|
||||
#define SONOFF_BUT 0
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
while (!Serial) continue;
|
||||
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);
|
||||
checkConnection();
|
||||
|
||||
Serial.println('\n');
|
||||
Serial.println("Connection established!");
|
||||
Serial.print("IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("MAC address:");
|
||||
Serial.println(WiFi.macAddress());
|
||||
}
|
||||
|
||||
void loop() {
|
||||
StaticJsonDocument<250> 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);
|
||||
|
||||
//HTTP CLIENT
|
||||
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
|
||||
|
||||
DeserializationError error = deserializeJson(jsonContent, payload);
|
||||
|
||||
//configuration setup
|
||||
String hostName = jsonContent["device"]["hostname"];
|
||||
String ipAddress = jsonContent["device"]["ipAddress"];
|
||||
String gateway = jsonContent["device"]["gateway"];
|
||||
String subnet = jsonContent["device"]["subnet"];
|
||||
String requestState = jsonContent["state"];
|
||||
int state = jsonContent["value"];
|
||||
|
||||
if (requestState != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
} else if (requestState == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
|
||||
//Set static ip
|
||||
setStaticIp(ipAddress, gateway, subnet);
|
||||
WiFi.hostname(hostName);
|
||||
|
||||
if(unsuccessfulRounds == 5) {
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
bool checkConnection() {
|
||||
int count = 0;
|
||||
Serial.print("Waiting for Wi-Fi connection");
|
||||
while ( count < 30 ) {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.println();
|
||||
Serial.println("Connected!");
|
||||
return (true);
|
||||
}
|
||||
digitalWrite(SONOFF, HIGH);
|
||||
delay(250);
|
||||
digitalWrite(SONOFF, HIGH);
|
||||
delay(250);
|
||||
Serial.print(".");
|
||||
count++;
|
||||
}
|
||||
Serial.println("Timed out.");
|
||||
return false;
|
||||
}
|
||||
|
||||
void setStaticIp(String ipAddress, String subnet, String gateway){
|
||||
//Set static ip
|
||||
IPAddress staticIpAddress;
|
||||
IPAddress subnetIpAddress;
|
||||
IPAddress gatewayIpAddress;
|
||||
|
||||
if (
|
||||
staticIpAddress.fromString(ipAddress) &&
|
||||
subnetIpAddress.fromString(subnet) &&
|
||||
gatewayIpAddress.fromString(gateway) &&
|
||||
WiFi.localIP() != staticIpAddress
|
||||
) {
|
||||
WiFi.config(staticIpAddress, subnetIpAddress, gatewayIpAddress);
|
||||
Serial.print("STATIC IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
}
|
||||
}
|
@@ -1,221 +0,0 @@
|
||||
//Includes
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <EEPROM.h>
|
||||
|
||||
//Variables
|
||||
const char* ssid = "ssid";
|
||||
const char* pasw = "pasw";
|
||||
const char* hwId = "hwId";
|
||||
const char* server = "http://dev.steelants.cz/vasek/home/api.php";
|
||||
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
|
||||
StaticJsonDocument<250> jsonContent;
|
||||
bool buttonActive = false;
|
||||
int interuptCount = 0;
|
||||
int realState = 1;
|
||||
int state = 0;
|
||||
String requestJson = "";
|
||||
|
||||
//Pins
|
||||
#define SONOFF 12 //12
|
||||
#define SONOFF_LED 13
|
||||
#define SONOFF_BUT 0 //0
|
||||
|
||||
void ICACHE_RAM_ATTR handleInterrupt ();
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
EEPROM.begin(1);
|
||||
while (!Serial) continue;
|
||||
delay(10);
|
||||
Serial.println('\n');
|
||||
Serial.println("HW: " + String(hwId));
|
||||
|
||||
pinMode(SONOFF_LED, OUTPUT);
|
||||
pinMode(SONOFF_BUT, INPUT_PULLUP);
|
||||
pinMode(SONOFF, OUTPUT);
|
||||
state = EEPROM.read(0);
|
||||
digitalWrite(SONOFF, state);
|
||||
realState = state;
|
||||
|
||||
attachInterrupt(digitalPinToInterrupt(SONOFF_BUT), handleInterrupt, FALLING);
|
||||
|
||||
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
WiFi.begin(ssid, pasw);
|
||||
checkConnection();
|
||||
|
||||
Serial.println('\n');
|
||||
Serial.println("Connection established!");
|
||||
Serial.print("IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("MAC address:");
|
||||
Serial.println(WiFi.macAddress());
|
||||
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
jsonContent["values"]["on/off"]["value"] = (String)realState;
|
||||
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if(unsuccessfulRounds >= 5) {
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
requestJson = "";
|
||||
if (buttonActive){
|
||||
jsonContent["values"]["on/off"]["value"] = (String)!realState;
|
||||
if (!realState == 1) {
|
||||
digitalWrite(SONOFF, HIGH);
|
||||
realState = 1;
|
||||
} else if (!realState == 0){
|
||||
digitalWrite(SONOFF, LOW);
|
||||
realState = 0;
|
||||
}
|
||||
EEPROM.write(0, 0);
|
||||
EEPROM.commit();
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
|
||||
//HTTP CLIENT
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
buttonActive = false;
|
||||
}
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = hwId;
|
||||
|
||||
requestJson = "";
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
|
||||
//HTTP CLIENT
|
||||
DeserializationError error = deserializeJson(jsonContent, sendHttpRequest(requestJson));
|
||||
|
||||
if (error) {
|
||||
Serial.println(error.c_str());
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return;
|
||||
}
|
||||
//configuration setup
|
||||
String hostName = jsonContent["device"]["hostname"];
|
||||
String ipAddress = jsonContent["device"]["ipAddress"];
|
||||
String gateway = jsonContent["device"]["gateway"];
|
||||
String subnet = jsonContent["device"]["subnet"];
|
||||
String requestState = jsonContent["state"];
|
||||
JsonObject object = jsonContent.as<JsonObject>();
|
||||
if (!object["value"].isNull()) {
|
||||
state = (int)jsonContent["value"];
|
||||
}
|
||||
|
||||
if (requestState != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
} else if (requestState == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
|
||||
//Set static ip
|
||||
setStaticIp(ipAddress, gateway, subnet);
|
||||
WiFi.hostname(hostName);
|
||||
Serial.println("state: " + (String)state + ", realState: " + (String)realState);
|
||||
if (state != realState){
|
||||
if (state == 1 && realState == 0) {
|
||||
Serial.println("ON state: " + (String)state + ", realState: " + (String)realState);
|
||||
digitalWrite(SONOFF, HIGH); // Turn the LED on by making the voltage LOW
|
||||
realState = 1;
|
||||
} else {
|
||||
Serial.println("OFF");
|
||||
digitalWrite(SONOFF, LOW); // Turn the LED on by making the voltage LOW
|
||||
realState = 0;
|
||||
}
|
||||
EEPROM.write(0, realState);
|
||||
EEPROM.commit();
|
||||
}
|
||||
}
|
||||
|
||||
void handleInterrupt() {
|
||||
interuptCount++;
|
||||
buttonActive = true;
|
||||
}
|
||||
|
||||
String sendHttpRequest (String requestJson) {
|
||||
HTTPClient http;
|
||||
http.setReuse(true);
|
||||
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
|
||||
|
||||
if (httpCode == -1) {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return "";
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
bool checkConnection() {
|
||||
int count = 0;
|
||||
Serial.print("Waiting for Wi-Fi connection");
|
||||
while ( count < 30 ) {
|
||||
if (buttonActive){
|
||||
if (!realState == 1) {
|
||||
digitalWrite(SONOFF, HIGH);
|
||||
realState = 1;
|
||||
} else if (!realState == 0){
|
||||
digitalWrite(SONOFF, LOW);
|
||||
realState = 0;
|
||||
}
|
||||
EEPROM.write(0, realState);
|
||||
EEPROM.commit();
|
||||
buttonActive = false;
|
||||
}
|
||||
digitalWrite(SONOFF_LED, HIGH);
|
||||
delay(125);
|
||||
digitalWrite(SONOFF_LED, LOW);
|
||||
delay(125);
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.println();
|
||||
Serial.println("Connected!");
|
||||
digitalWrite(SONOFF_LED, LOW);
|
||||
return (true);
|
||||
}
|
||||
Serial.print(".");
|
||||
count++;
|
||||
}
|
||||
Serial.println("Timed out.");
|
||||
return false;
|
||||
}
|
||||
|
||||
void setStaticIp(String ipAddress, String subnet, String gateway){
|
||||
//Set static ip
|
||||
IPAddress staticIpAddress;
|
||||
IPAddress subnetIpAddress;
|
||||
IPAddress gatewayIpAddress;
|
||||
|
||||
if (
|
||||
staticIpAddress.fromString(ipAddress) &&
|
||||
subnetIpAddress.fromString(subnet) &&
|
||||
gatewayIpAddress.fromString(gateway) &&
|
||||
WiFi.localIP() != staticIpAddress
|
||||
) {
|
||||
WiFi.config(staticIpAddress, subnetIpAddress, gatewayIpAddress);
|
||||
Serial.print("STATIC IP address:");
|
||||
Serial.println(WiFi.localIP());
|
||||
}
|
||||
}
|
@@ -1,375 +0,0 @@
|
||||
//Includes
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266WebServer.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#define ARDUINOJSON_DECODE_UNICODE 1
|
||||
#include <ArduinoJson.h>
|
||||
#include <EEPROM.h>
|
||||
#include "ESP8266httpUpdate.h"
|
||||
|
||||
//Variables
|
||||
const char* ssidServer = "";
|
||||
const char* paswServer = "";
|
||||
String ssid = "";
|
||||
String pasw = "";
|
||||
String apiToken = "";
|
||||
const int httpsPort = 443;
|
||||
const char* host = "http://dev.steelants.cz";
|
||||
const char* url = "/vasek/home/api.php";
|
||||
|
||||
const char* fingerprint = "";
|
||||
const char* host2 = "dev.steelants.cz";
|
||||
const char* url2 = "/vasek/home/update.php";
|
||||
|
||||
String content;
|
||||
bool conf = false;
|
||||
bool buttonActive = false;
|
||||
int state = 0;
|
||||
String requestJson = "";
|
||||
int unsuccessfulRounds = 0; //Unsucesful atmpt counter
|
||||
|
||||
ESP8266WebServer server(80);
|
||||
StaticJsonDocument<250> jsonContent;
|
||||
DeserializationError error;
|
||||
|
||||
//Pins
|
||||
#define SONOFF 12
|
||||
#define SONOFF_LED 13
|
||||
#define SONOFF_BUT 0 //0
|
||||
|
||||
void ICACHE_RAM_ATTR handleInterrupt ();
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
EEPROM.begin(100);
|
||||
while (!Serial) continue;
|
||||
delay(10);
|
||||
|
||||
//read saved data
|
||||
ssid = ReadEeprom(1, 33);
|
||||
pasw = ReadEeprom(33, 65);
|
||||
apiToken = ReadEeprom(65, 97);
|
||||
|
||||
//set pins
|
||||
pinMode(SONOFF_LED, OUTPUT);
|
||||
pinMode(SONOFF_BUT, INPUT_PULLUP);
|
||||
pinMode(SONOFF, OUTPUT);
|
||||
state = EEPROM.read(0);
|
||||
digitalWrite(SONOFF, state);
|
||||
|
||||
attachInterrupt(digitalPinToInterrupt(SONOFF_BUT), handleInterrupt, FALLING);
|
||||
|
||||
//wifi
|
||||
if (ssid != "") {
|
||||
WiFi.disconnect();
|
||||
WiFi.softAPdisconnect(true);
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, pasw);
|
||||
conf = wifiVerify(20);
|
||||
if (conf) {
|
||||
configTime(3 * 3600, 0, "pool.ntp.org");
|
||||
WiFiClientSecure client;
|
||||
Serial.print("connecting to ");
|
||||
Serial.println(host2);
|
||||
client.setInsecure();
|
||||
if (!client.connect(host2, httpsPort)) {
|
||||
Serial.println("connection failed");
|
||||
return;
|
||||
}
|
||||
|
||||
if (client.verify(fingerprint, host2)) {
|
||||
Serial.println("certificate matches");
|
||||
} else {
|
||||
Serial.println("certificate doesn't match");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.print("Starting OTA from: ");
|
||||
Serial.println(url2
|
||||
|
||||
);
|
||||
|
||||
auto ret = ESPhttpUpdate.update(client, host2, 80, url2);
|
||||
delay(500);
|
||||
switch(ret) {
|
||||
case HTTP_UPDATE_FAILED:
|
||||
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
Serial.println("HTTP_UPDATE_OK");
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
Serial.println();
|
||||
break;
|
||||
}
|
||||
delay(500);
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
jsonContent["values"]["on/off"]["value"] = (String)state;
|
||||
jsonContent["settings"]["network"]["ip"] = WiFi.localIP().toString();
|
||||
jsonContent["settings"]["network"]["mac"] = WiFi.macAddress();
|
||||
jsonContent["settings"]["firmware_hash"] = ESP.getSketchMD5();
|
||||
sendDataToWeb();
|
||||
return;
|
||||
}
|
||||
}
|
||||
setupAP();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (conf) {
|
||||
if (unsuccessfulRounds >= 5) {
|
||||
Serial.println("RESTARTING ESP");
|
||||
ESP.restart();
|
||||
}
|
||||
jsonContent = {};
|
||||
jsonContent["token"] = apiToken;
|
||||
requestJson = "";
|
||||
if (buttonActive) {
|
||||
jsonContent["values"]["on/off"]["value"] = (String)state;
|
||||
digitalWrite(SONOFF, state);
|
||||
EEPROM.write(0, state);
|
||||
EEPROM.commit();
|
||||
sendDataToWeb();
|
||||
buttonActive = false;
|
||||
delay(500);
|
||||
} else {
|
||||
sendDataToWeb();
|
||||
loadDataFromWeb();
|
||||
}
|
||||
} else {
|
||||
server.handleClient();
|
||||
}
|
||||
}
|
||||
|
||||
void handleInterrupt() {
|
||||
buttonActive = true;
|
||||
state = !state;
|
||||
digitalWrite(SONOFF, state);
|
||||
}
|
||||
|
||||
bool wifiVerify(int t) {
|
||||
int c = 0;
|
||||
Serial.println("Waiting for Wifi to connect to Shelly1");
|
||||
while (c < t) {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
c = t;
|
||||
Serial.println();
|
||||
Serial.println("Connected!");
|
||||
digitalWrite(SONOFF_LED, HIGH);
|
||||
return true;
|
||||
}
|
||||
if (buttonActive == true){
|
||||
digitalWrite(SONOFF, state);
|
||||
EEPROM.write(0, state);
|
||||
EEPROM.commit();
|
||||
buttonActive = false;
|
||||
}
|
||||
digitalWrite(SONOFF_LED, HIGH);
|
||||
delay(125);
|
||||
digitalWrite(SONOFF_LED, LOW);
|
||||
delay(375);
|
||||
Serial.print(WiFi.status());
|
||||
c++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void loadDataFromWeb() {
|
||||
if (error.code() != DeserializationError::Ok) {
|
||||
Serial.println(error.c_str());
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
error = DeserializationError::Ok;
|
||||
return;
|
||||
}
|
||||
|
||||
//configuration setup
|
||||
String hostName = jsonContent["device"]["hostname"];
|
||||
String requestState = jsonContent["state"];
|
||||
String command = jsonContent["command"];
|
||||
if (!buttonActive) {
|
||||
state = (int)jsonContent["value"];
|
||||
Serial.println("state: " + (String)state);
|
||||
digitalWrite(SONOFF, state);
|
||||
EEPROM.write(0, state);
|
||||
EEPROM.commit();
|
||||
delay(500);
|
||||
}
|
||||
|
||||
if (command == "reset"){
|
||||
ESP.reset();
|
||||
} else if (command == "config") {
|
||||
CleanEeprom();
|
||||
EEPROM.commit();
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
if (requestState != "succes") {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
} else if (requestState == "succes") {
|
||||
unsuccessfulRounds = 0;
|
||||
}
|
||||
|
||||
WiFi.hostname(hostName);
|
||||
}
|
||||
|
||||
void sendDataToWeb() {
|
||||
serializeJson(jsonContent, requestJson);
|
||||
Serial.println("JSON: " + requestJson);
|
||||
error = deserializeJson(jsonContent, sendHttpRequest());
|
||||
}
|
||||
|
||||
String sendHttpRequest () {
|
||||
HTTPClient http;
|
||||
http.setReuse(true);
|
||||
Serial.println("HTTP url: " + String(host) + String(url) + ""); //Print HTTP return code
|
||||
http.begin(String(host) + String(url));
|
||||
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
|
||||
Serial.println("HTTP request: " + String(requestJson) + ""); //Print HTTP return code
|
||||
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
|
||||
|
||||
if (httpCode == -1) {
|
||||
unsuccessfulRounds++;
|
||||
Serial.println("UNSUCCESSFUL ROUND NUMBER " + String(unsuccessfulRounds) + "FROM 5");
|
||||
return "";
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
void CleanEeprom() {
|
||||
for (int i = 1; i < 100; ++i) {
|
||||
EEPROM.write(i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void WriteEeprom (String data, int start = 1) {
|
||||
for (int i = 0; i < data.length(); ++i)
|
||||
{
|
||||
EEPROM.write(start + i, data[i]);
|
||||
}
|
||||
EEPROM.commit();
|
||||
}
|
||||
|
||||
String ReadEeprom(int min, int max) {
|
||||
String localString;
|
||||
for (int i = min; i < max; ++i) {
|
||||
localString += char(EEPROM.read(i));
|
||||
}
|
||||
return localString;
|
||||
}
|
||||
|
||||
void createWeb()
|
||||
{
|
||||
server.on("/", []() {
|
||||
if (server.args() == 3) {
|
||||
ssid = server.arg("wifi-ssid");
|
||||
pasw = server.arg("wifi-pasw");
|
||||
apiToken = server.arg("apiToken");
|
||||
if (ssid != "" && pasw != "" && apiToken != "") {
|
||||
CleanEeprom();
|
||||
WriteEeprom(ssid);
|
||||
WriteEeprom(pasw, 33);
|
||||
WriteEeprom(apiToken, 65);
|
||||
server.send(200, "application/json", "Restarting esp");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
}
|
||||
}
|
||||
content = "<!DOCTYPE HTML><body>";
|
||||
content += "<head><style>";
|
||||
content += "html,body {height: 100%;}";
|
||||
content += "html {display: table;margin: auto;}";
|
||||
content += "body {display: table-cell;vertical-align: middle;}";
|
||||
content += "input {width: 100%;box-sizing: border-box}";
|
||||
content += "</style></head>";
|
||||
content += "<h2>WIFI Configuration</h2>";
|
||||
content += "<h4><b>" + (String)ssidServer + "</b></h4>";
|
||||
content += "<a href='#'>Refresh</a>";
|
||||
content += "<div class=\"wifi-list\">";
|
||||
int n = WiFi.scanNetworks();
|
||||
if (n == 0)
|
||||
content += "<label>No networks found...</label>";
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
content += "<a href=\"#\" onclick=\"fillSSID(this.innerHTML)\">" + WiFi.SSID(i) + "</a><br>";
|
||||
}
|
||||
}
|
||||
content += "</div>";
|
||||
content += "<form method='get' action=''><div class='wifi-form'>";
|
||||
content += "<label>SSID: </label><input name='wifi-ssid' id='wifi-ssid' length=32 type='text'><br>";
|
||||
content += "<label>Heslo: </label><input name='wifi-pasw' length=32 type='password'><br>";
|
||||
content += "<label>Api token: </label><input name='apiToken' length=32 type='password'><br>";
|
||||
content += "<input type='submit' value='Connect'>";
|
||||
content += "</div></form>";
|
||||
content += "<script>";
|
||||
content += "function fillSSID(value) {\r\n";
|
||||
content += "document.getElementById(\"wifi-ssid\").value = value;\r\n";
|
||||
content += "}";
|
||||
content += "</script>";
|
||||
content += "</body>";
|
||||
server.send(200, "text/html", content);
|
||||
});
|
||||
}
|
||||
|
||||
void setupAP(void) {
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.disconnect();
|
||||
WiFi.softAPdisconnect(true);
|
||||
delay(100);
|
||||
int n = WiFi.scanNetworks();
|
||||
Serial.println("scan done");
|
||||
if (n == 0)
|
||||
Serial.println("no networks found");
|
||||
else
|
||||
{
|
||||
Serial.print(n);
|
||||
Serial.println(" networks found");
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
// Print SSID and RSSI for each network found
|
||||
Serial.print(i + 1);
|
||||
Serial.print(": ");
|
||||
Serial.print(WiFi.SSID(i));
|
||||
Serial.print(" (");
|
||||
Serial.print(WiFi.RSSI(i));
|
||||
Serial.print(")");
|
||||
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
|
||||
delay(10);
|
||||
}
|
||||
}
|
||||
delay(100);
|
||||
WiFi.softAP(ssidServer, paswServer);
|
||||
Serial.println("softap");
|
||||
Serial.println("");
|
||||
Serial.println("WiFi connected");
|
||||
Serial.print("Local IP: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
Serial.print("SoftAP IP: ");
|
||||
Serial.println(WiFi.softAPIP());
|
||||
createWeb();
|
||||
// Start the server
|
||||
server.begin();
|
||||
Serial.println("Server started");
|
||||
Serial.println("over");
|
||||
}
|
@@ -1,71 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<body>
|
||||
|
||||
<head>
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
html {
|
||||
display: table;
|
||||
margin: auto;
|
||||
font-family: "Metropolis", sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
display: table-cell;
|
||||
vertical-align: middle;
|
||||
background: #182239;
|
||||
color: #d4def7;
|
||||
}
|
||||
|
||||
|
||||
input {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
line-height: 1.5;
|
||||
background: #121a2b;
|
||||
border-radius: 3px;
|
||||
border: 0px solid transparent;
|
||||
color: #d4def7;
|
||||
padding: 0.5em 0.8em;
|
||||
height: 2.5rem;
|
||||
line-height: 1.5;
|
||||
background: #121a2b;
|
||||
width: 100%;
|
||||
display: block;
|
||||
}
|
||||
|
||||
a{
|
||||
display: block;
|
||||
color: #DDE7F5;
|
||||
text-decoration:underline;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<h2>WIFI Configuration</h2>
|
||||
<a href="#">Refresh</a>
|
||||
<form>
|
||||
<div class="wifi-list">
|
||||
<a href="#" onclick="fillSSID(this.innerHTML)">WifiName</a><br>
|
||||
<a href="#" onclick="fillSSID(this.innerHTML)">WifiName</a><br>
|
||||
<a href="#" onclick="fillSSID(this.innerHTML)">WifiName</a><br>
|
||||
<a href="#" onclick="fillSSID(this.innerHTML)">WifiName</a><br>
|
||||
<a href="#" onclick="fillSSID(this.innerHTML)">WifiName</a><br>
|
||||
<a href="#" onclick="fillSSID(this.innerHTML)">WifiName</a><br>
|
||||
</div>
|
||||
<div class="wifi-form">
|
||||
<input id="wifi-ssid" type="text"><br>
|
||||
<input id="password" type="text"><br>
|
||||
<input type="submit" value="Connect">
|
||||
</div>
|
||||
</form>
|
||||
<script>
|
||||
function fillSSID(value) {
|
||||
document.getElementById("wifi-ssid").value = value;
|
||||
}
|
||||
</script>
|
||||
</body>
|
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"folders": []
|
||||
}
|
@@ -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 */;
|
Before Width: | Height: | Size: 77 KiB |
Before Width: | Height: | Size: 66 KiB |
Before Width: | Height: | Size: 45 KiB |
Before Width: | Height: | Size: 108 KiB |
Before Width: | Height: | Size: 76 KiB |
Before Width: | Height: | Size: 58 KiB |
323
api.php
@@ -1,323 +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();
|
||||
$apiLogManager = new LogManager('./app/logs/api/'. date("Y-m-d").'.log');
|
||||
|
||||
//DB Conector
|
||||
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
|
||||
|
||||
//Read API data
|
||||
$json = file_get_contents('php://input');
|
||||
$obj = json_decode($json, true);
|
||||
|
||||
//Log RAW api request
|
||||
if (API_DEBUGMOD == 1) {
|
||||
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO);
|
||||
}
|
||||
|
||||
//zabespecit proti Ddosu
|
||||
if (isset($obj['user']) && $obj['user'] != ''){
|
||||
//user at home
|
||||
$user = UserManager::getUser($obj['user']);
|
||||
$userAtHome = $user['at_home'];
|
||||
if (!empty($user)) {
|
||||
$userId = $user['user_id'];
|
||||
$atHome = $obj['atHome'];
|
||||
if($userAtHome != $atHome){
|
||||
UserManager::atHome($userId, $atHome);
|
||||
$logManager->write("[USER] user " . $userId . " changet his home state to " . $atHome , LogRecordType::INFO);
|
||||
}
|
||||
echo 'Saved: ' . $atHome;
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 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!",
|
||||
), JSON_PRETTY_PRINT);
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
||||
$logManager->write("[API] acces denied from " . $_SERVER['REMOTE_ADDR'], LogRecordType::WARNING);
|
||||
exit();
|
||||
}
|
||||
}
|
||||
|
||||
//automationExecution
|
||||
try {
|
||||
AutomationManager::executeAll();
|
||||
$fallbackManager = new FallbackManager(RANGES);
|
||||
$fallbackManager->check();
|
||||
//LogKeeper::purge(LOGTIMOUT);
|
||||
} 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;
|
||||
$settings = null;
|
||||
$deviceLogs = null;
|
||||
$command = "null";
|
||||
|
||||
if (isset($obj['values'])) {
|
||||
$values = $obj['values'];
|
||||
}
|
||||
|
||||
if (isset($obj['settings'])) {
|
||||
$settings = $obj['settings'];
|
||||
}
|
||||
|
||||
if (isset($obj['logs'])) {
|
||||
$deviceLogs = $obj['logs'];
|
||||
}
|
||||
|
||||
|
||||
|
||||
//Checks
|
||||
if ($token == null || $token == "") {
|
||||
echo json_encode(array(
|
||||
'state' => 'unsuccess',
|
||||
'errorMSG' => "Missing Value Token in JSON payload",
|
||||
), JSON_PRETTY_PRINT);
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
||||
die();
|
||||
}
|
||||
|
||||
//Vstupní Checky
|
||||
if (!DeviceManager::registeret($token)) {
|
||||
$notificationMng = new NotificationManager;
|
||||
$notificationData = [];
|
||||
$notificationData = [
|
||||
'title' => 'Info',
|
||||
'body' => 'New device Detected Found',
|
||||
'icon' => BASEDIR . '/app/templates/images/icon-192x192.png',
|
||||
];
|
||||
$deviceId = DeviceManager::create($token, $token);
|
||||
foreach ($values as $key => $value) {
|
||||
if (!SubDeviceManager::getSubDeviceByMaster($deviceId, $key)) {
|
||||
SubDeviceManager::create($deviceId, $key, UNITS[$key]);
|
||||
}
|
||||
|
||||
if ($notificationData != []) {
|
||||
$subscribers = $notificationMng::getSubscription();
|
||||
foreach ($subscribers as $key => $subscriber) {
|
||||
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO);
|
||||
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Notification for newly added Device
|
||||
$subscribers = $notificationMng::getSubscription();
|
||||
foreach ($subscribers as $key => $subscriber) {
|
||||
$logManager->write("[NOTIFICATION] SENDING TO" . $subscriber['id'] . " ", LogRecordType::INFO);
|
||||
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
|
||||
}
|
||||
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
||||
echo json_encode(array(
|
||||
'state' => 'unsuccess',
|
||||
'errorMSG' => "Device not registeret",
|
||||
), JSON_PRETTY_PRINT);
|
||||
$logManager->write("[API] Registering Device", LogRecordType::INFO);
|
||||
exit();
|
||||
}
|
||||
|
||||
if (!DeviceManager::approved($token)) {
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 401 Unauthorized");
|
||||
echo json_encode(array(
|
||||
'state' => 'unsuccess',
|
||||
'errorMSG' => "Unaproved Device",
|
||||
), JSON_PRETTY_PRINT);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Diagnostic Data Write to DB
|
||||
if ($settings != null && $settings != ""){
|
||||
$data = ['mac' => $settings["network"]["mac"], 'ip_address' => $settings["network"]["ip"]];
|
||||
if (array_key_exists("firmware_hash", $settings)) {
|
||||
$data['firmware_hash'] = $settings["firmware_hash"];
|
||||
}
|
||||
DeviceManager::editByToken($token, $data);
|
||||
$jsonAnswer = [
|
||||
'state' => 'succes',
|
||||
'command' => $command,
|
||||
];
|
||||
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||
die();
|
||||
}
|
||||
|
||||
// Issuing command
|
||||
if ($command == "null"){
|
||||
$device = DeviceManager::getDeviceByToken($token);
|
||||
$deviceId = $device['device_id'];
|
||||
$deviceCommand = $device["command"];
|
||||
if ($deviceCommand != '' && $deviceCommand != null && $deviceCommand != "null")
|
||||
{
|
||||
$command = $deviceCommand;
|
||||
$data = [
|
||||
'command'=>'null'
|
||||
];
|
||||
DeviceManager::editByToken($token, $data);
|
||||
$logManager->write("[API] Device_ID " . $deviceId . " executing command " . $command, LogRecordType::INFO);
|
||||
}
|
||||
}
|
||||
|
||||
// Diagnostic Logs Write To log File
|
||||
if ($deviceLogs != null && $deviceLogs != ""){
|
||||
foreach ($deviceLogs as $log) {
|
||||
$logManager->write("[Device Log Msg] Device_ID " . $deviceId . "->" . $log, LogRecordType::ERROR);
|
||||
}
|
||||
$jsonAnswer = [
|
||||
'state' => 'succes',
|
||||
'command' => $command,
|
||||
];
|
||||
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||
die();
|
||||
}
|
||||
|
||||
// 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'],3));
|
||||
$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' => 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'] . " ", LogRecordType::INFO);
|
||||
$notificationMng::sendSimpleNotification(SERVERKEY, $subscriber['token'], $notificationData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$hostname = strtolower($device['name']);
|
||||
$hostname = str_replace(' ', '_', $hostname);
|
||||
//upravit format na setings-> netvork etc
|
||||
$jsonAnswer = [
|
||||
'device' => [
|
||||
'hostname' => $hostname,
|
||||
'ipAddress' => $device['ip_address'],
|
||||
'subnet' => $device['subnet'],
|
||||
'gateway' => $device['gateway'],
|
||||
],
|
||||
'state' => 'succes',
|
||||
'command' => $command,
|
||||
];
|
||||
|
||||
$subDevicesTypeList = SubDeviceManager::getSubDeviceSTypeForMater($deviceId);
|
||||
if (!in_array($subDevicesTypeList, ['on/off', 'door', 'water'])) {
|
||||
$jsonAnswer['device']['sleepTime'] = $device['sleep_time'];
|
||||
}
|
||||
echo json_encode($jsonAnswer, JSON_PRETTY_PRINT);
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||
} else {
|
||||
//Vypis
|
||||
$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'], LogRecordType::INFO);
|
||||
RecordManager::setExecuted($subDeviceLastReord['record_id']);
|
||||
}
|
||||
|
||||
echo json_encode(array(
|
||||
'device' => [
|
||||
'hostname' => $device['name'],
|
||||
'ipAddress' => $device['ip_address'],
|
||||
'subnet' => $device['subnet'],
|
||||
'gateway' => $device['gateway'],
|
||||
],
|
||||
'state' => 'succes',
|
||||
'value' => $subDeviceLastReordValue,
|
||||
'command' => $command,
|
||||
), JSON_PRETTY_PRINT);
|
||||
header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
|
||||
}
|
||||
|
||||
unset($logManager);
|
||||
Db::disconect();
|
||||
die();
|
43
apiFront.php
@@ -1,43 +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;
|
||||
}
|
||||
|
||||
//Log
|
||||
$apiLogManager = new LogManager('./app/logs/apiFront/'. date("Y-m-d").'.log');
|
||||
|
||||
//DB Conector
|
||||
Db::connect (DBHOST, DBUSER, DBPASS, DBNAME);
|
||||
|
||||
//Read API data
|
||||
$json = file_get_contents('php://input');
|
||||
$obj = json_decode($json, true);
|
||||
|
||||
//Log RAW api request
|
||||
if (API_DEBUGMOD == 1) {
|
||||
$apiLogManager->write("[API] request body\n" . json_encode($obj, JSON_PRETTY_PRINT), LogRecordType::INFO);
|
||||
}
|
||||
|
||||
unset($logManager);
|
||||
Db::disconect();
|
||||
die();
|
41
app/Console/Kernel.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console;
|
||||
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
|
||||
|
||||
class Kernel extends ConsoleKernel
|
||||
{
|
||||
/**
|
||||
* The Artisan commands provided by your application.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $commands = [
|
||||
//
|
||||
];
|
||||
|
||||
/**
|
||||
* Define the application's command schedule.
|
||||
*
|
||||
* @param \Illuminate\Console\Scheduling\Schedule $schedule
|
||||
* @return void
|
||||
*/
|
||||
protected function schedule(Schedule $schedule)
|
||||
{
|
||||
// $schedule->command('inspire')->hourly();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the commands for the application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function commands()
|
||||
{
|
||||
$this->load(__DIR__.'/Commands');
|
||||
|
||||
require base_path('routes/console.php');
|
||||
}
|
||||
}
|
21
app/Domain/Device/Factories/DeviceFactory.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Device\Factories;
|
||||
|
||||
use App\Models\Device;
|
||||
|
||||
/**
|
||||
* Class DeviceFactory
|
||||
* @package App\Domain\Device\Factories
|
||||
*/
|
||||
class DeviceFactory
|
||||
{
|
||||
public function create(string $name, ?string $description = null): Device
|
||||
{
|
||||
return Device::create([
|
||||
'name' => $name,
|
||||
'description' => $description
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
12
app/Domain/Device/Repositories/DeviceRepository.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Device\Repositories;
|
||||
|
||||
/**
|
||||
* Class DeviceRepository
|
||||
* @package App\Domain\Device\Repositories
|
||||
*/
|
||||
class DeviceRepository
|
||||
{
|
||||
|
||||
}
|
35
app/Domain/Legacy/Transformers/DeviceTransformer.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Legacy\Transformers;
|
||||
|
||||
use App\Models\Device;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class DeviceTransformer
|
||||
{
|
||||
public function index(Collection $devices): array
|
||||
{
|
||||
return $devices->map(function (Device $device) {
|
||||
return [
|
||||
"device" => [
|
||||
"hostname" => "2",
|
||||
"sleepTime" => 0,
|
||||
],
|
||||
"state" => "success",
|
||||
"value" => "0"
|
||||
];
|
||||
})->toArray();
|
||||
}
|
||||
|
||||
public function show(Device $device): array
|
||||
{
|
||||
return [
|
||||
"device" => [
|
||||
"hostname" => "2",
|
||||
"sleepTime" => 0,
|
||||
],
|
||||
"state" => "success",
|
||||
"value" => "0"
|
||||
];
|
||||
}
|
||||
}
|
19
app/Domain/Room/Factories/RoomFactory.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Room\Factories;
|
||||
|
||||
use App\Models\Room;
|
||||
|
||||
/**
|
||||
* Class RoomFactory
|
||||
* @package App\Domain\Room\Factories
|
||||
*/
|
||||
class RoomFactory
|
||||
{
|
||||
public function create(string $name): Room
|
||||
{
|
||||
return Room::create([
|
||||
'name' => $name
|
||||
]);
|
||||
}
|
||||
}
|
17
app/Domain/Room/Repositories/RoomRepository.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Room\Repositories;
|
||||
|
||||
use App\Models\Room;
|
||||
|
||||
/**
|
||||
* Class RoomRepository
|
||||
* @package App\Domain\Room\Repositories
|
||||
*/
|
||||
class RoomRepository
|
||||
{
|
||||
public function all()
|
||||
{
|
||||
return Room::all();
|
||||
}
|
||||
}
|
40
app/Exceptions/Handler.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Throwable;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
{
|
||||
/**
|
||||
* A list of the exception types that are not reported.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $dontReport = [
|
||||
//
|
||||
];
|
||||
|
||||
/**
|
||||
* A list of the inputs that are never flashed for validation exceptions.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $dontFlash = [
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register the exception handling callbacks for the application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
{
|
||||
$this->reportable(function (Throwable $e) {
|
||||
//
|
||||
});
|
||||
}
|
||||
}
|
13
app/Http/Controllers/Controller.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Bus\DispatchesJobs;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
|
||||
}
|
43
app/Http/Controllers/RoomController.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Domain\Room\Factories\RoomFactory;
|
||||
use App\Domain\Room\Repositories\RoomRepository;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class RoomController extends Controller
|
||||
{
|
||||
private RoomRepository $roomRepository;
|
||||
|
||||
public function __construct(RoomRepository $roomRepository)
|
||||
{
|
||||
$this->roomRepository = $roomRepository;
|
||||
}
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$rooms = $this->roomRepository->all();
|
||||
return response()->json(
|
||||
$rooms->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
public function store(RoomFactory $roomFactory): JsonResponse
|
||||
{
|
||||
$this->validate(request(), [
|
||||
'name' => 'required|string|unique:rooms,name'
|
||||
]);
|
||||
|
||||
$room = $roomFactory->create(
|
||||
request()->post('name')
|
||||
);
|
||||
|
||||
return response()->json(
|
||||
$room->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
}
|
66
app/Http/Kernel.php
Normal file
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
|
||||
class Kernel extends HttpKernel
|
||||
{
|
||||
/**
|
||||
* The application's global HTTP middleware stack.
|
||||
*
|
||||
* These middleware are run during every request to your application.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $middleware = [
|
||||
// \App\Http\Middleware\TrustHosts::class,
|
||||
\App\Http\Middleware\TrustProxies::class,
|
||||
\Fruitcake\Cors\HandleCors::class,
|
||||
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
||||
\App\Http\Middleware\TrimStrings::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware groups.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $middlewareGroups = [
|
||||
'web' => [
|
||||
\App\Http\Middleware\EncryptCookies::class,
|
||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||
\Illuminate\Session\Middleware\StartSession::class,
|
||||
// \Illuminate\Session\Middleware\AuthenticateSession::class,
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
|
||||
'api' => [
|
||||
'throttle:api',
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware.
|
||||
*
|
||||
* These middleware may be assigned to groups or used individually.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $routeMiddleware = [
|
||||
'auth' => \App\Http\Middleware\Authenticate::class,
|
||||
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
|
||||
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
|
||||
'can' => \Illuminate\Auth\Middleware\Authorize::class,
|
||||
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
|
||||
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
|
||||
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
|
||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||
];
|
||||
}
|
21
app/Http/Middleware/Authenticate.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
|
||||
class Authenticate extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the path the user should be redirected to when they are not authenticated.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return string|null
|
||||
*/
|
||||
protected function redirectTo($request)
|
||||
{
|
||||
if (! $request->expectsJson()) {
|
||||
return route('login');
|
||||
}
|
||||
}
|
||||
}
|
17
app/Http/Middleware/EncryptCookies.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
|
||||
|
||||
class EncryptCookies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the cookies that should not be encrypted.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
17
app/Http/Middleware/PreventRequestsDuringMaintenance.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
|
||||
|
||||
class PreventRequestsDuringMaintenance extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be reachable while maintenance mode is enabled.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
32
app/Http/Middleware/RedirectIfAuthenticated.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class RedirectIfAuthenticated
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \Closure $next
|
||||
* @param string|null ...$guards
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, ...$guards)
|
||||
{
|
||||
$guards = empty($guards) ? [null] : $guards;
|
||||
|
||||
foreach ($guards as $guard) {
|
||||
if (Auth::guard($guard)->check()) {
|
||||
return redirect(RouteServiceProvider::HOME);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
18
app/Http/Middleware/TrimStrings.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
|
||||
|
||||
class TrimStrings extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the attributes that should not be trimmed.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
}
|
20
app/Http/Middleware/TrustHosts.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustHosts as Middleware;
|
||||
|
||||
class TrustHosts extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the host patterns that should be trusted.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function hosts()
|
||||
{
|
||||
return [
|
||||
$this->allSubdomainsOfApplicationUrl(),
|
||||
];
|
||||
}
|
||||
}
|
23
app/Http/Middleware/TrustProxies.php
Normal file
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Fideloper\Proxy\TrustProxies as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TrustProxies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The trusted proxies for this application.
|
||||
*
|
||||
* @var array|string|null
|
||||
*/
|
||||
protected $proxies;
|
||||
|
||||
/**
|
||||
* The headers that should be used to detect proxies.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $headers = Request::HEADER_X_FORWARDED_ALL;
|
||||
}
|
17
app/Http/Middleware/VerifyCsrfToken.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
|
||||
|
||||
class VerifyCsrfToken extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be excluded from CSRF verification.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
13
app/Models/Device.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Device extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = ['name', 'description'];
|
||||
}
|
15
app/Models/Room.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Room extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'name'
|
||||
];
|
||||
}
|
43
app/Models/User.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
use HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be hidden for arrays.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $hidden = [
|
||||
'password',
|
||||
'remember_token',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be cast to native types.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $casts = [
|
||||
'email_verified_at' => 'datetime',
|
||||
];
|
||||
}
|
28
app/Providers/AppServiceProvider.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register any application services.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function boot()
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
30
app/Providers/AuthServiceProvider.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
|
||||
class AuthServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The policy mappings for the application.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $policies = [
|
||||
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register any authentication / authorization services.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function boot()
|
||||
{
|
||||
$this->registerPolicies();
|
||||
|
||||
//
|
||||
}
|
||||
}
|
21
app/Providers/BroadcastServiceProvider.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\Broadcast;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class BroadcastServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function boot()
|
||||
{
|
||||
Broadcast::routes();
|
||||
|
||||
require base_path('routes/channels.php');
|
||||
}
|
||||
}
|
32
app/Providers/EventServiceProvider.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
|
||||
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
|
||||
class EventServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The event listener mappings for the application.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $listen = [
|
||||
Registered::class => [
|
||||
SendEmailVerificationNotification::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Register any events for your application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function boot()
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
63
app/Providers/RouteServiceProvider.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
class RouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The path to the "home" route for your application.
|
||||
*
|
||||
* This is used by Laravel authentication to redirect users after login.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const HOME = '/home';
|
||||
|
||||
/**
|
||||
* The controller namespace for the application.
|
||||
*
|
||||
* When present, controller route declarations will automatically be prefixed with this namespace.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
// protected $namespace = 'App\\Http\\Controllers';
|
||||
|
||||
/**
|
||||
* Define your route model bindings, pattern filters, etc.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function boot()
|
||||
{
|
||||
$this->configureRateLimiting();
|
||||
|
||||
$this->routes(function () {
|
||||
Route::prefix('api')
|
||||
->middleware('api')
|
||||
->namespace($this->namespace)
|
||||
->group(base_path('routes/api.php'));
|
||||
|
||||
Route::middleware('web')
|
||||
->namespace($this->namespace)
|
||||
->group(base_path('routes/web.php'));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the rate limiters for the application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function configureRateLimiting()
|
||||
{
|
||||
RateLimiter::for('api', function (Request $request) {
|
||||
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
|
||||
});
|
||||
}
|
||||
}
|
@@ -1,175 +0,0 @@
|
||||
<?php
|
||||
|
||||
class AutomationManager{
|
||||
public static $automation;
|
||||
|
||||
public 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 function restart($automationId) {
|
||||
return Db::command ('UPDATE automation SET executed = 0 WHERE automation_id=?', array ($automationId));
|
||||
}
|
||||
|
||||
public 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,
|
||||
);
|
||||
try {
|
||||
if ($automationId == "") {
|
||||
Db::add ('automation', $scene);
|
||||
} else {
|
||||
Db::edit ('automation', $scene, 'WHERE automation_id = ?', array ($automationId));
|
||||
}
|
||||
} catch(PDOException $error) {
|
||||
echo $error->getMessage();
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
public function getAll(){
|
||||
return Db::loadAll ("SELECT * FROM automation");
|
||||
|
||||
}
|
||||
|
||||
public function executeAll(){
|
||||
global $logManager;
|
||||
|
||||
$automations = Db::loadAll ("SELECT * FROM automation");
|
||||
$dayNameNow = strtolower (date('D', time()));
|
||||
|
||||
foreach ($automations as $automation) {
|
||||
$onValue = json_decode($automation['if_something'], true);
|
||||
$sceneDoJson = $automation['do_something'];
|
||||
$actionDays = json_decode($automation['on_days'], true);
|
||||
$value = time();
|
||||
$run = false;
|
||||
$restart = false;
|
||||
|
||||
if ($automation['active'] == 1 && $automation['locked'] != 1){
|
||||
Db::edit('automation', array('locked' => 1), 'WHERE automation_id = ?', array($automation['automation_id']));
|
||||
if (in_array($dayNameNow, $actionDays)){
|
||||
if (in_array($onValue['type'], ['sunSet', 'sunRise', 'time','now'])) {
|
||||
if ($onValue['type'] == 'sunSet') {
|
||||
$value = date_sunset($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90);
|
||||
} else if ($onValue['type'] == 'sunRise') {
|
||||
$value = date_sunrise($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90);
|
||||
} else if ($onValue['type'] == 'time') {
|
||||
$onValue = explode(':',$onValue['value']);
|
||||
$today = date_create('now');
|
||||
$onValue = $today->setTime($onValue[0], $onValue[1]);
|
||||
$value = $today->getTimestamp();
|
||||
}
|
||||
|
||||
if (time() > $value && $automation['executed'] == 0){
|
||||
$run = true;
|
||||
} else if (time() < $value && $automation['executed'] == 1) { //recovery realowing of automation
|
||||
$restart = true;
|
||||
}
|
||||
|
||||
} 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;
|
||||
foreach ($users as $key => $user) {
|
||||
if ($user['at_home'] == 'true'){
|
||||
$membersHome++;
|
||||
}
|
||||
}
|
||||
if ($membersHome == 0 && $automation['executed'] == 0) {
|
||||
$run = true;
|
||||
} else if ($membersHome > 0 && $automation['executed'] == 1){
|
||||
$restart = true;
|
||||
}
|
||||
} else if ($onValue['type'] == 'someOneHome') {
|
||||
$users = UserManager::getUsers();
|
||||
$membersHome = 0;
|
||||
foreach ($users as $key => $user) {
|
||||
if ($user['at_home'] == 'true'){
|
||||
$membersHome++;
|
||||
}
|
||||
}
|
||||
if ($membersHome == 0 && $automation['executed'] == 1) {
|
||||
$restart = true;
|
||||
} 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
|
||||
if ($run) {
|
||||
$body = '';
|
||||
|
||||
$sceneDoArray = json_decode($sceneDoJson);
|
||||
foreach ($sceneDoArray as $deviceId => $deviceState) {
|
||||
RecordManager::create($deviceId, 'on/off', $deviceState);
|
||||
}
|
||||
|
||||
$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/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, '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']));
|
||||
}
|
||||
Db::edit('automation', array('locked' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,194 +0,0 @@
|
||||
<?php
|
||||
abstract class ChartJS
|
||||
{
|
||||
/**
|
||||
* @var array chart data
|
||||
*/
|
||||
protected $_datasets = array();
|
||||
/**
|
||||
* @var array chart labels
|
||||
*/
|
||||
protected $_labels = array();
|
||||
/**
|
||||
* The chart type
|
||||
* @var string
|
||||
*/
|
||||
protected $_type = '';
|
||||
/**
|
||||
* @var array Specific options for chart
|
||||
*/
|
||||
protected $_options = array();
|
||||
/**
|
||||
* @var string Chartjs canvas' ID
|
||||
*/
|
||||
protected $_id;
|
||||
/**
|
||||
* @var string Canvas width
|
||||
*/
|
||||
protected $_width;
|
||||
/**
|
||||
* @var string Canvas height
|
||||
*/
|
||||
protected $_height;
|
||||
/**
|
||||
* @var array Canvas attributes (class,
|
||||
*/
|
||||
protected $_attributes = array();
|
||||
/**
|
||||
* @var array Default colors
|
||||
*/
|
||||
protected static $_defaultColors = array('fill' => 'rgba(220,220,220,0.2)', 'stroke' => 'rgba(220,220,220,1)', 'point' => 'rgba(220,220,220,1)', 'pointStroke' => '#fff');
|
||||
/**
|
||||
* Add label(s)
|
||||
* @param array $labels
|
||||
* @param bool $reset
|
||||
*/
|
||||
public function addLabels(array $labels, $reset = false)
|
||||
{
|
||||
if ($reset) {
|
||||
$this->_labels = array();
|
||||
}
|
||||
$this->_labels = $this->_labels + $labels;
|
||||
}
|
||||
/**
|
||||
* Add dataset
|
||||
* @param $dataset
|
||||
* @param $reset
|
||||
*/
|
||||
public function addDataset($dataset, $reset)
|
||||
{
|
||||
if ($reset) {
|
||||
$this->_datasets = array();
|
||||
}
|
||||
$this->_datasets += $dataset;
|
||||
}
|
||||
public function __construct($id = null, $width = '', $height = '', $otherAttributes = array())
|
||||
{
|
||||
if (!$id) {
|
||||
$id = uniqid('chartjs_', true);
|
||||
}
|
||||
$this->_id = $id;
|
||||
$this->_width = $width;
|
||||
$this->_height = $height;
|
||||
// Always save otherAttributes as array
|
||||
if ($otherAttributes && !is_array($otherAttributes)) {
|
||||
$otherAttributes = array($otherAttributes);
|
||||
}
|
||||
$this->_attributes = $otherAttributes;
|
||||
}
|
||||
/**
|
||||
* This method allows to echo ChartJS object and directly renders canvas (instead of using ChartJS->render())
|
||||
*/
|
||||
public function __toString()
|
||||
{
|
||||
return $this->renderCanvas();
|
||||
}
|
||||
public function renderCanvas()
|
||||
{
|
||||
$data = $this->_renderData();
|
||||
$options = $this->_renderOptions();
|
||||
$height = $this->_renderHeight();
|
||||
$width = $this->_renderWidth();
|
||||
$attributes = $this->_renderAttributes();
|
||||
$canvas = '<canvas id="' . $this->_id . '" data-chartjs="' . $this->_type . '"' . $height . $width . $attributes . $data . $options . '></canvas>';
|
||||
return $canvas;
|
||||
}
|
||||
/**
|
||||
* Prepare canvas' attributes
|
||||
* @return string
|
||||
*/
|
||||
protected function _renderAttributes()
|
||||
{
|
||||
$attributes = '';
|
||||
foreach ($this->_attributes as $attribute => $value) {
|
||||
$attributes .= ' ' . $attribute . '="' . $value . '"';
|
||||
}
|
||||
return $attributes;
|
||||
}
|
||||
/**
|
||||
* Prepare width attribute for canvas
|
||||
* @return string
|
||||
*/
|
||||
protected function _renderWidth()
|
||||
{
|
||||
$width = '';
|
||||
if ($this->_width) {
|
||||
$width = ' width="' . $this->_width . '"';
|
||||
}
|
||||
return $width;
|
||||
}
|
||||
/**
|
||||
* Prepare height attribute for canvas
|
||||
* @return string
|
||||
*/
|
||||
protected function _renderHeight()
|
||||
{
|
||||
$height = '';
|
||||
if ($this->_height) {
|
||||
$height = ' height="' . $this->_height . '"';
|
||||
}
|
||||
return $height;
|
||||
}
|
||||
/**
|
||||
* Render custom options for the chart
|
||||
* @return string
|
||||
*/
|
||||
protected function _renderOptions()
|
||||
{
|
||||
if (empty($this->_options)) {
|
||||
return '';
|
||||
}
|
||||
return ' data-options=\'' . json_encode($this->_options) . '\'';
|
||||
}
|
||||
/**
|
||||
* Prepare data (labels and dataset) for the chart
|
||||
* @return string
|
||||
*/
|
||||
protected function _renderData()
|
||||
{
|
||||
$array_data = array('labels' => array(), 'datasets' => array());
|
||||
$i = 0;
|
||||
foreach ($this->_datasets as $line) {
|
||||
$this->_completeColors($line['options'], $i);
|
||||
$array_data['datasets'][] = $line['options'] + array('data' => $line['data']);
|
||||
$i++;
|
||||
}
|
||||
$array_data['labels'] = $this->_labels;
|
||||
return ' data-data=\'' . json_encode($array_data) . '\'';
|
||||
}
|
||||
/**
|
||||
* Set default colors
|
||||
* @param array $defaultColors
|
||||
*/
|
||||
public static function setDefaultColors(array $defaultColors)
|
||||
{
|
||||
self::$_defaultColors = $defaultColors;
|
||||
}
|
||||
/**
|
||||
* @param array $color
|
||||
*/
|
||||
public static function addDefaultColor(array $color)
|
||||
{
|
||||
if (!empty($color['fill']) && !empty($color['stroke']) && !empty($color['point']) && !empty($color['pointStroke'])) {
|
||||
self::$_defaultColors[] = $color;
|
||||
} else {
|
||||
trigger_error('Color is missing to add this theme (need fill, stroke, point and pointStroke) : color not added', E_USER_WARNING);
|
||||
}
|
||||
}
|
||||
protected function _completeColors(&$options, &$i)
|
||||
{
|
||||
if (empty(static::$_defaultColors[$i])) {
|
||||
$i = 0;
|
||||
}
|
||||
$colors = static::$_defaultColors[$i];
|
||||
foreach (static::$_colorsRequired as $name) {
|
||||
if (empty($options[$name])) {
|
||||
$shortName = str_replace('Color', '', $name);
|
||||
if (empty($colors[$shortName])) {
|
||||
$shortName = static::$_colorsReplacement[$shortName];
|
||||
}
|
||||
$options[$name] = $colors[$shortName];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,21 +0,0 @@
|
||||
<?php
|
||||
class ChartJS_Line extends ChartJS
|
||||
{
|
||||
protected $_type = 'Line';
|
||||
protected static $_colorsRequired = array('fillColor', 'strokeColor', 'pointColor', 'pointStrokeColor', 'pointHighlightFill', 'pointHighlightStroke');
|
||||
protected static $_colorsReplacement = array('pointHighlightFill' => 'point', 'pointHighlightStroke' => 'pointStroke');
|
||||
/**
|
||||
* Add a set of data
|
||||
* @param array $data
|
||||
* @param array $options
|
||||
* @param null $name Name cas be use to change data / options later
|
||||
*/
|
||||
public function addLine($data = array(), $options = array(), $name = null)
|
||||
{
|
||||
if (!$name) {
|
||||
$name = count($this->_datasets) + 1;
|
||||
}
|
||||
$this->_datasets[$name]['data'] = $data;
|
||||
$this->_datasets[$name]['options'] = $options;
|
||||
}
|
||||
}
|
@@ -1,129 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
?>
|
100
app/class/DB.php
@@ -1,100 +0,0 @@
|
||||
<?php
|
||||
class Db{
|
||||
private static $join;
|
||||
private static $commandDatabase = array (
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
|
||||
PDO::ATTR_EMULATE_PREPARES => false
|
||||
);
|
||||
|
||||
public static function connect ($host, $user, $password, $database) {
|
||||
if (!isset (self::$join)) {
|
||||
self::$join = @new PDO(
|
||||
"mysql:host=$host;dbname=$database;charset=utf8",
|
||||
$user,
|
||||
$password,
|
||||
self::$commandDatabase
|
||||
);
|
||||
self::$join->exec ("set names utf8");
|
||||
}
|
||||
}
|
||||
|
||||
public static function disconect(){
|
||||
self::$join = null;
|
||||
}
|
||||
|
||||
public static function loadOne ($sql, $values = array (), $numberKey = false) {
|
||||
$answer = self::$join->prepare ($sql);
|
||||
$answer->execute ($values);
|
||||
if (!$numberKey) {
|
||||
return $answer->fetch (PDO::FETCH_ASSOC);
|
||||
} else {
|
||||
return $answer->fetch (PDO::FETCH_NUM);
|
||||
}
|
||||
}
|
||||
|
||||
public static function command ($sql, $values = array()) {
|
||||
$answer = self::$join->prepare ($sql);
|
||||
return $answer->execute ($values);
|
||||
}
|
||||
|
||||
public static function loadAll ($sql, $values = array(), $numberKey = false) {
|
||||
$answer = self::$join->prepare ($sql);
|
||||
$answer->execute ($values);
|
||||
if (!$numberKey) {
|
||||
return $answer->fetchALL (PDO::FETCH_ASSOC);
|
||||
} else {
|
||||
return $answer->fetchALL (PDO::FETCH_NUM);
|
||||
}
|
||||
}
|
||||
|
||||
public static function loadAlone ($sql, $values = array()) {
|
||||
$answer = self::$join->prepare ($sql);
|
||||
$answer->execute ($values);
|
||||
return $answer->fetch (PDO::FETCH_NUM)[0];
|
||||
}
|
||||
|
||||
public static function add ($table, $values = array()) {
|
||||
return self::command (
|
||||
"INSERT INTO `$table` (`" .
|
||||
implode('`, `', array_keys($values)) .
|
||||
"`) VALUES (" .
|
||||
str_repeat('?,', (count($values) > 0 ? count($values)-1 : 0)) .
|
||||
"?)"
|
||||
, array_values ($values));
|
||||
}
|
||||
// TODO: pokud vlozim prazdne pole tak chyba ??
|
||||
public static function addAll ($table, $values = array ()) {
|
||||
try {
|
||||
foreach ($values as $value) {
|
||||
self::add ($table, $value);
|
||||
}
|
||||
} catch (PDOException $ex) {
|
||||
throw new PDOException ($ex->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static function edit (
|
||||
$table,
|
||||
$values = array(),
|
||||
$conditions,
|
||||
$values2 = array()
|
||||
) {
|
||||
return self::command (
|
||||
"UPDATE `$table` SET `" .
|
||||
implode('` =?, `', array_keys($values)) .
|
||||
"` =? " .
|
||||
$conditions
|
||||
, array_merge (array_values ($values), $values2));
|
||||
}
|
||||
|
||||
public static function insertId () {
|
||||
return self::$join->lastInsertId ();
|
||||
}
|
||||
|
||||
public static function addId ($lastTable, $lastIdName) {
|
||||
$answer = self::$join->prepare ("SELECT `$lastIdName` FROM `$lastTable` ORDER BY `$lastIdName` DESC");
|
||||
$answer->execute ();
|
||||
return $answer->fetch (PDO::FETCH_NUM)[0];
|
||||
}
|
||||
}
|
@@ -1,41 +0,0 @@
|
||||
<?php
|
||||
class DashboardManager{
|
||||
public static $devices;
|
||||
|
||||
|
||||
function getAllDashboards ($userId) {
|
||||
return Db::loadAll ("SELECT * FROM dashboard WHERE user_id=?", array($userId));
|
||||
}
|
||||
|
||||
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) {
|
||||
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) {
|
||||
if (self::getSubDevice(UserManager::getUserData('user_id'), $subDeviceId) == null){
|
||||
|
||||
// to do: pokud existuje nepridej
|
||||
//
|
||||
//
|
||||
$dashboardItem = array (
|
||||
'user_id' => UserManager::getUserData('user_id'),
|
||||
'subdevice_id' => $subDeviceId,
|
||||
);
|
||||
try {
|
||||
Db::add ('dashboard', $dashboardItem);
|
||||
} catch(PDOException $error) {
|
||||
echo $error->getMessage();
|
||||
die();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Remove ($subDeviceId){
|
||||
$userId = UserManager::getUserData('user_id');
|
||||
Db::command ('DELETE FROM dashboard WHERE subdevice_id=? AND user_id = ?', array ($subDeviceId, $userId));
|
||||
}
|
||||
}
|
@@ -1,96 +0,0 @@
|
||||
<?php
|
||||
class DeviceManager{
|
||||
public static $devices;
|
||||
|
||||
function getAllDevices () {
|
||||
return Db::loadAll ("SELECT * FROM devices WHERE approved != ?", Array(2));
|
||||
}
|
||||
|
||||
function getAllDevicesInRoom ($roomId = "") {
|
||||
return Db::loadAll ("SELECT * FROM devices WHERE room_id = ? AND approved != ?", Array($roomId, 2));
|
||||
}
|
||||
|
||||
function getOtherDevices(){
|
||||
return Db::loadAll ("SELECT * FROM devices WHERE room_id IS NULL ");
|
||||
}
|
||||
|
||||
function getDeviceByToken($deviceToken) {
|
||||
return Db::loadOne("SELECT * FROM devices WHERE token = ?", array($deviceToken));
|
||||
}
|
||||
|
||||
function getDeviceByMac($deviceMac) {
|
||||
return Db::loadOne("SELECT * FROM devices WHERE mac = ?", array($deviceMac));
|
||||
}
|
||||
|
||||
function getDeviceById($deviceId) {
|
||||
return Db::loadOne("SELECT * FROM devices WHERE device_id = ?", array($deviceId));
|
||||
}
|
||||
|
||||
public function create ($name, $token) {
|
||||
$defaultRoom = RoomManager::getDefaultRoomId();
|
||||
$device = array (
|
||||
'name' => $name,
|
||||
'token' => $token,
|
||||
'room_id' => $defaultRoom,
|
||||
);
|
||||
try {
|
||||
Db::add ('devices', $device);
|
||||
return Db::loadOne("SELECT device_id FROM devices WHERE token = ?", array($token))['device_id'];
|
||||
} catch(PDOException $error) {
|
||||
echo $error->getMessage();
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
public function edit ($deviceId, $values = []) {
|
||||
try {
|
||||
Db::edit ('devices', $values, 'WHERE device_id = ?', array($deviceId));
|
||||
} catch(PDOException $error) {
|
||||
echo $error->getMessage();
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
public 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) {
|
||||
$device = array (
|
||||
'room_id' => $roomId,
|
||||
);
|
||||
try {
|
||||
Db::edit ('devices', $device, 'WHERE device_id = ?', array($deviceId));
|
||||
} catch(PDOException $error) {
|
||||
echo $error->getMessage();
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [delete Smazání zařízení]
|
||||
* @param [type] $deviceId [Id zařízení ke smazání]
|
||||
*/
|
||||
public function delete ($deviceId) {
|
||||
Db::command ('DELETE FROM devices WHERE device_id=?', array ($deviceId));
|
||||
}
|
||||
|
||||
public function registeret ($deviceToken) {
|
||||
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=?", array($deviceToken))) == 1 ? true : false);
|
||||
}
|
||||
|
||||
public function approved ($deviceToken) {
|
||||
return (count(Db::loadAll ("SELECT * FROM devices WHERE token=? AND approved = ?", array($deviceToken, 1))) == 1 ? true : false);
|
||||
}
|
||||
}
|
||||
?>
|
@@ -1,44 +0,0 @@
|
||||
<?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"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,121 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* [InputTypes datatype for input types]
|
||||
*/
|
||||
class InputTypes
|
||||
{
|
||||
const TEXT = 'text';
|
||||
const NUMBER = 'number';
|
||||
const COLOR = 'color';
|
||||
const CHECK = 'checkbox';
|
||||
const BUTTON = 'button';
|
||||
const DATE = 'date';
|
||||
const DATETIME = 'datetime';
|
||||
const SUBMIT = 'submit';
|
||||
const HIDEN = 'hidden';
|
||||
const EMAIL = 'email';
|
||||
}
|
||||
/**
|
||||
* [Form Form Generator Class]
|
||||
*/
|
||||
class Form {
|
||||
|
||||
public $formContent = "";
|
||||
private $formName;
|
||||
private $formId;
|
||||
private $method;
|
||||
private $action;
|
||||
|
||||
/**
|
||||
* [__construct description]
|
||||
* @param String $name [description]
|
||||
* @param String $id [description]
|
||||
* @param String $method [description]
|
||||
* @param String $action [description]
|
||||
*/
|
||||
function __construct(String $name, String $id, String $method, String $action) {
|
||||
if ($name != "") {
|
||||
$this->formName = 'name="'.$name.'"';
|
||||
}
|
||||
if ($id != "") {
|
||||
$this->formId = 'id="'.$id.'"';
|
||||
}
|
||||
if ($method != "") {
|
||||
$this->method = 'method="'.$method.'"';
|
||||
}
|
||||
if ($action != "") {
|
||||
$this->$action = 'action="'.$action.'"';
|
||||
}
|
||||
}
|
||||
/**
|
||||
* [addInput description]
|
||||
* @param String $type Type of input element (text, number, color,checkbox, button, date, datetime, submit)
|
||||
* @param String $name name of element
|
||||
* @param String $id id of element
|
||||
* @param String $label label of element
|
||||
* @param String $value value of element
|
||||
* @param boolean $require require selector toggle
|
||||
* @param boolean $enabled enable selector toggle
|
||||
*/
|
||||
function addInput(String $type, String $name, String $id, String $label, String $value, Bool $require = false, Bool $enabled = true){
|
||||
$this->formContent .= '<div class="field">';
|
||||
if ($label != "") {
|
||||
$this->formContent .= '<div class="label">'.$label.'</div>';
|
||||
}
|
||||
$this->formContent .= '<input class="input" type="'.$type.'" name="'.$name.'" value="'.$value.'" ' . ($enabled ? '' : 'disabled') . ($require ? '' : 'required') .'>';
|
||||
$this->formContent .= '</div>';
|
||||
}
|
||||
|
||||
//TODO: add Group support
|
||||
/**
|
||||
* [addSelect description]
|
||||
* @param String $name name of element
|
||||
* @param String $id id of element
|
||||
* @param String $label label of element
|
||||
* @param Array $data array of options [value => valueName]
|
||||
* @param boolean $multiple multiple selector toggle
|
||||
* @param boolean $enabled enable selector toggle
|
||||
*/
|
||||
function addSelect(String $name, String $id, String $label, Array $data, Bool $multiple = false, Bool $require = false, Bool $enabled = true){
|
||||
$this->formContent .= '<div class="field">';
|
||||
if ($label != "") {
|
||||
$this->formContent .= '<div class="label">'.$label.'</div>';
|
||||
}
|
||||
$this->formContent .= '<select class="input"' . ($multiple ? '' : 'multiple') . ($enabled ? '' : 'disabled') . ($require ? '' : 'required') .'>';
|
||||
foreach ($data as $value => $text) {
|
||||
$this->formContent .= '<option value="' . $value . '">' . $text . '</option>';
|
||||
}
|
||||
$this->formContent .= '</select>';
|
||||
$this->formContent .= '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* [addTextarea description]
|
||||
* @param String $name name of element
|
||||
* @param String $id id of element
|
||||
* @param String $label label of element
|
||||
* @param String $value value of element
|
||||
* @param boolean $enabled enable selector toggle
|
||||
*/
|
||||
function addTextarea(String $name, String $id, String $label, Array $value, Bool $require = false, Bool $enabled = true){
|
||||
$this->formContent .= '<div class="field">';
|
||||
if ($label != "") {
|
||||
$this->formContent .= '<div class="label">'.$label.'</div>';
|
||||
}
|
||||
$this->formContent .= '<textarea class="input"' . ($enabled ? '' : 'disabled') . ($require ? '' : 'required') .'>';
|
||||
$this->formContent .= $value;
|
||||
$this->formContent .= '</textarea>';
|
||||
$this->formContent .= '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* [render function whitch dysplay generated form]
|
||||
*/
|
||||
function render(){
|
||||
self::addInput(InputTypes::SUBMIT, 'formSubmit', '', 'Submit', 'Submit');
|
||||
$form = '<form '.$this->formName.$this->formId.$this->method.$this->action.'">';
|
||||
$form .= $this->formContent;
|
||||
$form .= '</form>';
|
||||
echo $form;
|
||||
}
|
||||
}
|
@@ -1,59 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Language Manager
|
||||
*/
|
||||
class LanguageManager
|
||||
{
|
||||
|
||||
private $lngCode = 'en';
|
||||
private $lngDatabase = [];
|
||||
private $debug = false;
|
||||
|
||||
function __construct(string $lngCode, bool $debug = false)
|
||||
{
|
||||
$this->lngCode = $lngCode;
|
||||
$this->debug = $debug;
|
||||
}
|
||||
|
||||
function load()
|
||||
{
|
||||
$file = './app/lang/en.php';
|
||||
if (!file_exists($file)){
|
||||
die();
|
||||
//TODO add lng EXEPTIONS
|
||||
}
|
||||
$arrayFirst = include($file);
|
||||
$file = './app/lang/' . $this->lngCode . '.php';
|
||||
$arraySecond = [];
|
||||
if (file_exists($file)){
|
||||
$arraySecond = include($file);
|
||||
}
|
||||
$this->lngDatabase = array_merge($arrayFirst,$arraySecond);
|
||||
return true;
|
||||
}
|
||||
|
||||
function get(string $stringKey)
|
||||
{
|
||||
if ($this->debug) {
|
||||
return $stringKey;
|
||||
}
|
||||
if (isset($this->lngDatabase[$stringKey])) {
|
||||
return $this->lngDatabase[$stringKey];
|
||||
}
|
||||
return $stringKey;
|
||||
}
|
||||
|
||||
function echo(string $stringKey)
|
||||
{
|
||||
if ($this->debug) {
|
||||
echo $stringKey;
|
||||
return;
|
||||
}
|
||||
if (isset($this->lngDatabase[$stringKey])) {
|
||||
echo $this->lngDatabase[$stringKey];
|
||||
return;
|
||||
}
|
||||
echo $stringKey;
|
||||
return;
|
||||
}
|
||||
}
|
@@ -1,60 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
*
|
||||
*/
|
||||
|
||||
class LogRecordType{
|
||||
const WARNING = 'warning';
|
||||
const ERROR = 'error';
|
||||
const INFO = 'info';
|
||||
}
|
||||
|
||||
class LogKeeper
|
||||
{
|
||||
function purge($days){
|
||||
$todayFileName = date("Y-m-d").'.log';
|
||||
$seconds = $days * 86400;
|
||||
|
||||
$logFiles = scandir('./app/logs/');
|
||||
foreach ($logFiles as $key => $file) {
|
||||
if (in_array($file,array(".","..", ".gitkeep", $todayFileName)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (filemtime($file) > $seconds) {
|
||||
unlink('./app/logs/'.$file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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";
|
||||
if (strlen($record) > 65 ) {
|
||||
$record = Utilities::stringInsert($record,"\n",65);
|
||||
}
|
||||
fwrite($this->logFile, $record);
|
||||
}
|
||||
|
||||
function __destruct(){
|
||||
if (isset($this->logFile)) {
|
||||
fclose($this->logFile);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,18 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
*
|
||||
*/
|
||||
class NetvorkManager
|
||||
{
|
||||
|
||||
function __construct()
|
||||
{
|
||||
// code...
|
||||
}
|
||||
|
||||
function validateIp($ip = '0.0.0.0'){
|
||||
if (!filter_var($ip, FILTER_VALIDATE_IP)){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,107 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Notification Manager
|
||||
*/
|
||||
//TODO: Working timestamp to body or $title
|
||||
class NotificationManager
|
||||
{
|
||||
function addSubscriber($userID = '', $token = ''){
|
||||
$notificationSubscriber = $subDeviceId = Db::loadOne('SELECT id FROM notifications WHERE token = ?;', array($token));
|
||||
if ($notificationSubscriber == ''){
|
||||
$notification = array (
|
||||
'user_id' => $userID,
|
||||
'token' => $token,
|
||||
);
|
||||
Db::add ('notifications', $notification);
|
||||
}
|
||||
}
|
||||
|
||||
function getSubscription () {
|
||||
return Db::loadAll ("SELECT * FROM notifications");
|
||||
}
|
||||
|
||||
function sendSimpleNotification(string $serverKey, string $to, array $data, bool $timeStamp = false){
|
||||
$dataTemplate = [
|
||||
'title' => '',
|
||||
'body' => '',
|
||||
'icon' => '',
|
||||
];
|
||||
|
||||
if (array_diff_key ($dataTemplate , $data)){
|
||||
return;
|
||||
}
|
||||
|
||||
if ($timeStamp) {
|
||||
$data['title'] = $data['title'] . date();
|
||||
}
|
||||
|
||||
$notification = new Notification($serverKey);
|
||||
$notification->to($to);
|
||||
$notification->notification($data['title'], $data['body'], $data['icon'], '');
|
||||
$answer = $notification->send();
|
||||
$notification = null;
|
||||
|
||||
return $answer;
|
||||
}
|
||||
}
|
||||
|
||||
class Notification
|
||||
{
|
||||
public $server_key = '';
|
||||
public $jsonPayload = [
|
||||
"to" => '',
|
||||
"data" => [
|
||||
"notification" => [
|
||||
"body" => '',
|
||||
"title" => '',
|
||||
"icon" => '',
|
||||
"click_action" => '',
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
function __construct($serverKey = '')
|
||||
{
|
||||
$this->server_key = $serverKey;
|
||||
}
|
||||
|
||||
function to($to = ''){
|
||||
$this->jsonPayload["to"] = $to;
|
||||
}
|
||||
|
||||
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;
|
||||
$this->jsonPayload["data"]["notification"]["click_action"] = $action;
|
||||
}
|
||||
|
||||
function send(){
|
||||
$data = json_encode($this->jsonPayload);
|
||||
$url = 'https://fcm.googleapis.com/fcm/send';
|
||||
$headers = array(
|
||||
'Content-Type:application/json',
|
||||
'Authorization:key='.$this->server_key,
|
||||
);
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
|
||||
$result = curl_exec($ch);
|
||||
if ($result === FALSE) {
|
||||
die('Oops! FCM Send Error: ' . curl_error($ch));
|
||||
}
|
||||
curl_close($ch);
|
||||
return $result;
|
||||
}
|
||||
}
|
@@ -1,34 +0,0 @@
|
||||
<?php
|
||||
class Partial{
|
||||
var $assignedValues = [];
|
||||
var $partBuffer;
|
||||
var $path;
|
||||
var $debug;
|
||||
|
||||
function __construct($path = "", $debug = false) {
|
||||
$this->debug = $debug;
|
||||
if (!empty('app/templates/part/' . $path . '.phtml') && file_exists('app/templates/part/' . $path . '.phtml')) {
|
||||
$this->path = $path;
|
||||
} else {
|
||||
echo '<pre>';
|
||||
echo 'PHTML: Parial 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() {
|
||||
if (!empty($this->assignedValues)){
|
||||
extract($this->assignedValues);
|
||||
}
|
||||
|
||||
require('app/templates/part/' . $this->path . '.phtml');
|
||||
}
|
||||
}
|
@@ -1,80 +0,0 @@
|
||||
<?php
|
||||
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;
|
||||
};
|
||||
$record = array (
|
||||
'subdevice_id' => $subDeviceId,
|
||||
'value' => $value,
|
||||
);
|
||||
try {
|
||||
return Db::add ('records', $record);
|
||||
} catch(PDOException $error) {
|
||||
echo $error->getMessage();
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
public static function setExecuted($recordId) {
|
||||
try {
|
||||
Db::edit ('records', ['execuded' => 1], 'WHERE record_id = ?', array($recordId));
|
||||
} catch(PDOException $error) {
|
||||
echo $error->getMessage();
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
public static function getRecordById($recordId) {
|
||||
return Db::loadOne('SELECT * FROM records WHERE record_id = ?;', array($recordId));
|
||||
}
|
||||
|
||||
public static function getLastInsertedRecordId() {
|
||||
return Db::insertId();
|
||||
}
|
||||
|
||||
public static function getLastRecord($subDeviceId, $num = 1) {
|
||||
if ($num == 1)
|
||||
return Db::loadOne('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC;', array($subDeviceId, 999));
|
||||
return Db::loadAll('SELECT * FROM records WHERE subdevice_id = ? AND value != ? ORDER BY time DESC LIMIT ?;', array($subDeviceId, 999, $num));
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
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');
|
||||
$groupBy = strtoupper($groupBy).'(time)';
|
||||
$sql = 'SELECT value, time FROM records
|
||||
WHERE
|
||||
subdevice_id = ?
|
||||
AND
|
||||
value != 999
|
||||
AND
|
||||
time > ?
|
||||
GROUP BY '.$groupBy.'
|
||||
ORDER BY time ASC';
|
||||
//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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//TODO: zkontrolovat jestli neco nezbilo po smazaní
|
||||
public static function cleanSubdeviceRecords ($subDeviceId) {
|
||||
Db::command ('DELETE FROM records WHERE subdevice_id = ?);', array($subDeviceId));
|
||||
}
|
||||
}
|
||||
?>
|