diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..a91ca8f --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,11 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack", + "pioarduino.pioarduino-ide" + ] +} diff --git a/data/root.css b/data/root.css new file mode 100644 index 0000000..90d6368 --- /dev/null +++ b/data/root.css @@ -0,0 +1,188 @@ + /* Общие стили для страницы */ + body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #121212; /* Глубокий черный фон */ + color: #ffffff; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + align-items: center; + } + + /* --- TOP BAR STYLE --- */ + .top-bar { + width: 100%; + background-color: #1a1a1a; /* Темно-серый фон панели */ + border-bottom: 2px solid #ff6600; /* Оранжевая полоса снизу */ + box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5); + position: sticky; + top: 0; + z-index: 1000; + } + + .top-bar-container { + max-width: 1200px; + margin: 0 auto; + padding: 0 20px; + height: 60px; + display: flex; + justify-content: space-between; + align-items: center; + } + + /* Логотип / Название проекта */ + .logo { + font-size: 20px; + font-weight: bold; + color: #ffffff; + text-decoration: none; + text-transform: uppercase; + letter-spacing: 1px; + } + .logo span { + color: #ff6600; /* Оранжевый акцент */ + } + + /* Навигация и кнопка настроек */ + .nav-links { + display: flex; + align-items: center; + gap: 20px; + } + + .nav-link { + color: #e0e0e0; + text-decoration: none; + font-size: 15px; + transition: color 0.2s ease; + } + .nav-link:hover { + color: #ff6600; + } + + /* Кнопка настроек */ + .settings-btn { + display: flex; + align-items: center; + gap: 8px; + background-color: transparent; + color: #ff6600; + border: 1px solid #ff6600; + padding: 8px 16px; + border-radius: 4px; + cursor: pointer; + font-weight: 600; + text-decoration: none; + font-size: 14px; + transition: all 0.3s ease; + } + .settings-btn:hover { + background-color: #ff6600; + color: #000000; + box-shadow: 0 0 10px rgba(255, 102, 0, 0.4); + } + + /* --- ОСНОВНОЙ КОНТЕНТ --- */ + .main-content { + width: 100%; + max-width: 940px; + padding: 40px 20px; + box-sizing: border-box; + display: flex; + flex-direction: column; + align-items: center; + } + + h1 { + color: #ff6600; + margin-bottom: 30px; + text-transform: uppercase; + letter-spacing: 2px; + border-bottom: 2px solid #ff6600; + padding-bottom: 10px; + align-self: flex-start; + } + + /* Контейнер для адаптивности таблицы */ + .table-container { + width: 100%; + overflow-x: auto; + box-shadow: 0 4px 15px rgba(255, 102, 0, 0.15); + border-radius: 8px; + } + + /* Стили таблицы */ + table { + width: 100%; + border-collapse: collapse; + background-color: #1a1a1a; + text-align: left; + min-width: 600px; + } + + /* Шапка таблицы */ + th { + background-color: #ff6600; + color: #000000; + padding: 15px; + font-weight: bold; + text-transform: uppercase; + font-size: 14px; + } + + /* Ячейки таблицы */ + td { + padding: 15px; + border-bottom: 1px solid #333333; + color: #e0e0e0; + font-size: 15px; + } + + /* Чередование цветов строк (зебра) */ + tr:nth-child(even) { + background-color: #222222; + } + + /* Эффект наведения на строку */ + tr:hover td { + background-color: #2a2a2a; + color: #ff8533; + transition: all 0.2s ease; + } + + @media (max-width: 680px) { + .top-bar-container { + height: auto; + padding: 12px 16px; + flex-direction: column; + align-items: flex-start; + gap: 12px; + } + + .nav-links { + width: 100%; + justify-content: space-between; + flex-wrap: wrap; + gap: 10px; + } + + .settings-btn { + width: 100%; + justify-content: center; + } + + .main-content { + padding: 24px 14px; + } + + h1 { + font-size: 24px; + letter-spacing: 1px; + } + + th, td { + padding: 10px 8px; + font-size: 12px; + } + } diff --git a/data/root.html b/data/root.html new file mode 100644 index 0000000..2079afc --- /dev/null +++ b/data/root.html @@ -0,0 +1,50 @@ + + + + + + Панель управления — Список пользователей + + + + +
+
+ + + +
+
+ +
+

Список пользователей

+ +
+ + + + + + + + + +
IPMAC
+
+
+ + + + \ No newline at end of file diff --git a/data/root.js b/data/root.js new file mode 100644 index 0000000..98c99dd --- /dev/null +++ b/data/root.js @@ -0,0 +1,39 @@ +function add_user(ip, mac) +{ + const tabel = document.querySelector("#user-list"); + + const tr = document.createElement('tr'); + + const rdIP = document.createElement('td'); + rdIP.textContent = ip; + + const rdMAC = document.createElement('td'); + rdMAC.textContent = mac; + + tr.appendChild(rdIP); + tr.appendChild(rdMAC); + + tabel.appendChild(tr); +} + +async function update_user_list() +{ + const res = await fetch("http://192.168.4.1/user_list", { + method: "GET" + }); + + if (res.ok) + { + const body = await res.json(); + + const tabel = document.querySelector("#user-list"); + tabel.textContent = ''; + + for (let i = 0; i < body.user_ip.length; i++) { + add_user(body.user_ip[i], body.user_mac[i]); + } + } +} + +update_user_list(); +setInterval(update_user_list, 10000); \ No newline at end of file diff --git a/data/settings.conf b/data/settings.conf new file mode 100644 index 0000000..cec1b34 --- /dev/null +++ b/data/settings.conf @@ -0,0 +1,12 @@ + + +Mirror +*$sd!Df^67_sS52d +admin +admin +1000 +20 +192.168.4.1 +192.168.4.1 +255.255.255.0 +false \ No newline at end of file diff --git a/data/settings.css b/data/settings.css new file mode 100644 index 0000000..80c8bcd --- /dev/null +++ b/data/settings.css @@ -0,0 +1,291 @@ + /* Общие стили для страницы */ + body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #121212; /* Глубокий черный фон */ + color: #ffffff; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + align-items: center; + } + + /* --- TOP BAR STYLE --- */ + .top-bar { + width: 100%; + background-color: #1a1a1a; + border-bottom: 2px solid #ff6600; /* Оранжевая полоса снизу */ + box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5); + position: sticky; + top: 0; + z-index: 1000; + } + + .top-bar-container { + max-width: 1200px; + margin: 0 auto; + padding: 0 20px; + height: 60px; + display: flex; + justify-content: space-between; + align-items: center; + } + + .logo { + font-size: 20px; + font-weight: bold; + color: #ffffff; + text-decoration: none; + text-transform: uppercase; + letter-spacing: 1px; + } + .logo span { + color: #ff6600; + } + + .nav-links { + display: flex; + align-items: center; + gap: 20px; + } + + .nav-link { + color: #e0e0e0; + text-decoration: none; + font-size: 15px; + transition: color 0.2s ease; + } + .nav-link:hover { + color: #ff6600; + } + + .nav-link.active { + color: #ff6600; + font-weight: 600; + } + + /* --- ОСНОВНОЙ КОНТЕНТ --- */ + .main-content { + width: 100%; + max-width: 700px; /* Немного расширили для двух карточек */ + padding: 40px 20px; + box-sizing: border-box; + } + + /* Ссылка назад к списку */ + .back-link { + display: inline-flex; + align-items: center; + gap: 8px; + color: #a0a0a0; + text-decoration: none; + font-size: 14px; + margin-bottom: 20px; + transition: color 0.2s ease; + } + .back-link:hover { + color: #ff6600; + } + + h1 { + color: #ff6600; + margin: 0 0 30px 0; + text-transform: uppercase; + letter-spacing: 2px; + border-bottom: 2px solid #ff6600; + padding-bottom: 10px; + } + + /* Сетка для блоков настроек */ + .settings-grid { + display: flex; + flex-direction: column; + gap: 30px; + } + + /* --- СТИЛИ КАРТОЧКИ --- */ + .settings-card { + background-color: #1a1a1a; /* Темный фон карточки */ + border-radius: 8px; + padding: 30px; + box-shadow: 0 4px 15px rgba(255, 102, 0, 0.05); + border: 1px solid #2a2a2a; + } + + .card-title { + font-size: 18px; + font-weight: 600; + margin-bottom: 25px; + color: #ffffff; + display: flex; + align-items: center; + gap: 10px; + } + + .form-group { + margin-bottom: 20px; + display: flex; + flex-direction: column; + gap: 8px; + } + + label { + color: #a0a0a0; + font-size: 14px; + font-weight: 500; + } + + /* Поля ввода (универсальный стиль) */ + input[type="text"], + input[type="password"] { + width: 100%; + box-sizing: border-box; + background-color: #121212; + border: 1px solid #333333; + color: #ffffff; + padding: 12px 16px; + border-radius: 4px; + font-size: 15px; + outline: none; + transition: all 0.3s ease; + } + + /* Состояние фокуса */ + input[type="text"]:focus, + input[type="password"]:focus { + border-color: #ff6600; + box-shadow: 0 0 8px rgba(255, 102, 0, 0.2); + } + + /* --- СТИЛИ ДЛЯ ЧЕКБОКСА (CHECKBUTTON) --- */ + .checkbox-group { + flex-direction: row; + align-items: center; + gap: 12px; + cursor: pointer; + user-select: none; + margin-bottom: 25px; + } + + /* Скрываем дефолтный чекбокс, чтобы сделать красивый кастомный */ + .checkbox-group input[type="checkbox"] { + position: absolute; + opacity: 0; + cursor: pointer; + height: 0; + width: 0; + } + + /* Наш кастомный чекбокс */ + .checkmark { + height: 20px; + width: 20px; + background-color: #121212; + border: 1px solid #333333; + border-radius: 4px; + display: inline-block; + position: relative; + transition: all 0.2s ease; + } + + /* Эффект при наведении */ + .checkbox-group:hover input[type="checkbox"] ~ .checkmark { + border-color: #ff6600; + } + + /* Когда чекбокс активен (выбран) */ + .checkbox-group input[type="checkbox"]:checked ~ .checkmark { + background-color: #ff6600; + border-color: #ff6600; + } + + /* Стрелочка внутри чекбокса */ + .checkmark:after { + content: ""; + position: absolute; + display: none; + left: 6px; + top: 2px; + width: 5px; + height: 10px; + border: solid #000000; + border-width: 0 2px 2px 0; + transform: rotate(45deg); + } + + /* Показываем стрелочку при выборе */ + .checkbox-group input[type="checkbox"]:checked ~ .checkmark:after { + display: block; + } + + .checkbox-label { + color: #e0e0e0; + font-size: 14px; + font-weight: 600; + letter-spacing: 0.5px; + } + + /* Кнопка отправки формы */ + .submit-btn { + background-color: #ff6600; + color: #000000; + border: none; + padding: 14px; + border-radius: 4px; + font-size: 16px; + font-weight: bold; + cursor: pointer; + width: 100%; + margin-top: 10px; + transition: all 0.3s ease; + text-transform: uppercase; + letter-spacing: 1px; + } + + .submit-btn:hover { + background-color: #ff8533; + box-shadow: 0 4px 12px rgba(255, 102, 0, 0.3); + } + + @media (max-width: 768px) { + .top-bar-container { + height: auto; + padding: 12px 16px; + flex-direction: column; + align-items: flex-start; + gap: 12px; + } + + .nav-links { + width: 100%; + justify-content: space-between; + flex-wrap: wrap; + gap: 10px; + } + + .main-content { + padding: 24px 14px; + } + + h1 { + font-size: 24px; + letter-spacing: 1px; + } + + .settings-card { + padding: 20px 16px; + } + + .form-group { + margin-bottom: 16px; + } + + .checkbox-group { + margin-bottom: 20px; + } + + .submit-btn { + padding: 12px 10px; + font-size: 14px; + } + } diff --git a/data/settings.html b/data/settings.html new file mode 100644 index 0000000..2e7ea1b --- /dev/null +++ b/data/settings.html @@ -0,0 +1,133 @@ + + + + + + Панель управления — Настройки сети + + + + + + +
+
+ + + +
+
+ +
+ + + + + + + Назад к списку пользователей + + +

Настройки

+ +
+ + +
+
+ + + + + + + Параметры Wi-Fi сети +
+ +
+ +
+ + +
+ + +
+ + +
+ + +
+
+ +
+
+ + + + + + + Основная сеть +
+ +
+ +
+ + +
+ + +
+ + +
+ + +
+
+ + + + + +
+
+ + + + + Безопасность (Смена пароля администратора) +
+ +
+
+ + +
+ +
+ + +
+ + +
+
+ +
+
+ + + + \ No newline at end of file diff --git a/data/settings.js b/data/settings.js new file mode 100644 index 0000000..582b5a4 --- /dev/null +++ b/data/settings.js @@ -0,0 +1,106 @@ +async function ap_update() +{ + const ssid = document.querySelector('#ap-ssid'); + const pass = document.querySelector('#ap-password'); + + const response = await fetch("http://192.168.4.1/settings/ap_update", { + method: "POST", + headers: { + 'Content-Type': 'application/json;charset=utf-8' + }, + body: JSON.stringify({ssid: ssid.value, pass: pass.value}) + }); + + if (!response.ok) + alert("Fail set AP settings"); +} +async function sta_update() +{ + const ssid = document.querySelector('#sta-ssid'); + const pass = document.querySelector('#sta-password'); + + const response = await fetch("http://192.168.4.1/settings/sta_update", { + method: "POST", + headers: { + 'Content-Type': 'application/json;charset=utf-8' + }, + body: JSON.stringify({ssid: ssid.value, pass: pass.value}) + }); + + if (!response.ok) + alert("Fail set STA settings"); +} +async function admin_update() +{ + const new_pass = document.getElementById('new-password'); + const confirm_pass = document.getElementById('confirm-password'); + + if (new_pass.value !== confirm_pass.value) + { + alert("Пароли должны совпадать"); + return; + } + + const res = await fetch("http://192.168.4.1/settings/admin_update", { + method: "POST", + headers:{ + 'Content-Type': 'application/json;charset=utf-8' + }, + body:JSON.stringify({new_pass: new_pass.value}) + }); + + if (!res.ok) + alert("Ошибка! Пароль не обновился"); +} + +async function set_conn_out() +{ + const checkbox = document.getElementById('connection-out'); + + const response = await fetch("http://192.168.4.1/settings/set_conn_out", { + method: "POST", + headers: { + 'Content-Type': 'application/json;charset=utf-8' + }, + body: JSON.stringify({is_conn_out: checkbox.checked}) + }); + + if (!response.ok) + alert("Fail set CONN_TO_OUT settings"); +} + +async function init() +{ + try { + const res = await fetch("http://192.168.4.1/settings/is_conn_out", { + method: "GET" + }); + + if (res.ok) { + const data = await res.json(); + + const conn_out = document.getElementById('connection-out'); + + conn_out.checked = data.is_conn_out; + } else { + console.warn("Сервер вернул ошибку:", res.status); + } + } catch (error) { + console.error("Ошибка при выполнении запроса:", error); + } +} + + +init(); + +button = document.querySelector('#ap_update'); +button.addEventListener('click', ap_update); + +button = document.querySelector('#sta_update'); +button.addEventListener('click', sta_update); + +button = document.querySelector('#admin_update'); +button.addEventListener('click', admin_update); + +const checkbox = document.getElementById('connection-out'); +checkbox.addEventListener('change', set_conn_out); \ No newline at end of file diff --git a/include/README b/include/README new file mode 100644 index 0000000..49819c0 --- /dev/null +++ b/include/README @@ -0,0 +1,37 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the convention is to give header files names that end with `.h'. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/README b/lib/README new file mode 100644 index 0000000..9379397 --- /dev/null +++ b/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into the executable file. + +The source code of each library should be placed in a separate directory +("lib/your_library_name/[Code]"). + +For example, see the structure of the following example libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional. for custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +Example contents of `src/main.c` using Foo and Bar: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +The PlatformIO Library Dependency Finder will find automatically dependent +libraries by scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/platformio.ini b/platformio.ini new file mode 100644 index 0000000..c2a303e --- /dev/null +++ b/platformio.ini @@ -0,0 +1,19 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp12e] +platform = espressif8266 +board = esp12e +framework = arduino +upload_port = COM6 +monitor_speed = 115200 +board_build.filesystem = littlefs +lib_deps = + bblanchon/ArduinoJson @ ^7.0.0 \ No newline at end of file diff --git a/src/Settings.cpp b/src/Settings.cpp new file mode 100644 index 0000000..eab29b7 --- /dev/null +++ b/src/Settings.cpp @@ -0,0 +1,137 @@ +#include "Settings.h" + +#include + +void Settings::save() +{ + File settings = LittleFS.open("/settings.conf", "w"); + + settings.println(MODEM_SSID); + settings.println(MODEM_PASS); + settings.println(AP_SSID); + settings.println(AP_PASS); + settings.println(ADMIN_LOGIN); + settings.println(ADMIN_PASS); + settings.println(DELAY); + settings.println(CNT_RETRY); + settings.println(IP); + settings.println(GATEWAY); + settings.println(MASK); + settings.println(CONN_TO_OUT ? "true" : "false"); + + settings.close(); +} + +void Settings::init() +{ + File settings = LittleFS.open("/settings.conf", "r"); + if (!settings) + return; + + MODEM_SSID = settings.readStringUntil('\n'); + MODEM_SSID.trim(); + + MODEM_PASS = settings.readStringUntil('\n'); + MODEM_PASS.trim(); + + AP_SSID = settings.readStringUntil('\n'); + AP_SSID.trim(); + + AP_PASS = settings.readStringUntil('\n'); + AP_PASS.trim(); + ADMIN_LOGIN = settings.readStringUntil('\n'); + ADMIN_LOGIN.trim(); + + ADMIN_PASS = settings.readStringUntil('\n'); + ADMIN_PASS.trim(); + + DELAY = atoi(settings.readStringUntil('\n').c_str()); + CNT_RETRY = atoi(settings.readStringUntil('\n').c_str()); + + IP.fromString(settings.readStringUntil('\n')); + GATEWAY.fromString(settings.readStringUntil('\n')); + MASK.fromString(settings.readStringUntil('\n')); + + String str_conn_out = settings.readStringUntil('\n'); + str_conn_out.trim(); + CONN_TO_OUT = (str_conn_out == "true" ? true : false); + + settings.close(); +} + +void Settings::print() +{ + Serial.printf("MODEM_SSID %s\n", MODEM_SSID.c_str()); + Serial.printf("MODEM_PASS %s\n", MODEM_PASS.c_str()); + Serial.printf("AP_SSID %s\n", AP_SSID.c_str()); + Serial.printf("AP_PASS %s\n", AP_PASS.c_str()); + Serial.printf("ADMIN_LOGIN %s\n", ADMIN_LOGIN.c_str()); + Serial.printf("ADMIN_PASS %s\n", ADMIN_PASS.c_str()); + Serial.printf("DELAY %u\n", DELAY); + Serial.printf("CNT_RETRY %u\n", CNT_RETRY); + Serial.printf("IP: %s\n", IP.toString().c_str()); + Serial.printf("GATEWAY: %s\n", GATEWAY.toString().c_str()); + Serial.printf("MASK: %s\n", MASK.toString().c_str()); + Serial.printf("CONN TO OUT: %s\n", (CONN_TO_OUT ? "true" : "false")); +} + +void Settings::setModemSSID(String ssid) +{ + MODEM_SSID = ssid; + save(); +} +void Settings::setModemPASS(String pass) +{ + MODEM_PASS = pass; + save(); +} +void Settings::setAPSSID(String ssid) +{ + AP_SSID = ssid; + save(); +} +void Settings::setAPPASS(String pass) +{ + AP_PASS = pass; + save(); +} +void Settings::setAdminLogin(String login) +{ + ADMIN_LOGIN = login; + save(); +} +void Settings::setAdminPass(String pass) +{ + ADMIN_PASS = pass; + save(); +} +void Settings::setDelay(unsigned int delay) +{ + DELAY = delay; + save(); +} +void Settings::setCntRetry(unsigned cnt_retry) +{ + CNT_RETRY = cnt_retry; + save(); +} +void Settings::setSelfIP(IPAddress ip) +{ + IP = ip; + save(); +} +void Settings::setGateway(IPAddress gateway) +{ + GATEWAY = gateway; + save(); +} +void Settings::setMask(IPAddress mask) +{ + MASK = mask; + save(); +} +void Settings::setConnToOut(bool conn_to_out) +{ + CONN_TO_OUT = conn_to_out; + save(); +} \ No newline at end of file diff --git a/src/Settings.h b/src/Settings.h new file mode 100644 index 0000000..8a4e6db --- /dev/null +++ b/src/Settings.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +class Settings +{ + String MODEM_SSID, MODEM_PASS; + String AP_SSID, AP_PASS; + String ADMIN_LOGIN, ADMIN_PASS; + IPAddress IP, GATEWAY, MASK; + unsigned int DELAY, CNT_RETRY; + bool CONN_TO_OUT; + + void save(); +public: + String getModemSSID() const { return MODEM_SSID; } + String getModemPASS() const { return MODEM_PASS; } + String getAPSSID() const { return AP_SSID; } + String getAPPASS() const { return AP_PASS; } + String getAdminLogin() const { return ADMIN_LOGIN; } + String getAdminPass() const { return ADMIN_PASS; } + unsigned int getDelay() const { return DELAY; } + unsigned int getCntRetry() const { return CNT_RETRY; } + IPAddress getSelfIP() const { return IP; } + IPAddress getGateway() const { return GATEWAY; } + IPAddress getMask() const { return MASK; } + bool getConnToOut() const { return CONN_TO_OUT; } + + + void setModemSSID(String ssid); + void setModemPASS(String pass); + void setAPSSID(String ssid); + void setAPPASS(String pass); + void setAdminLogin(String login); + void setAdminPass(String pass); + void setDelay(unsigned int delay); + void setCntRetry(unsigned cnt_retry); + void setSelfIP(IPAddress ip); + void setGateway(IPAddress gateway); + void setMask(IPAddress mask); + void setConnToOut(bool conn_to_out); + + void init(); + void print(); +}; \ No newline at end of file diff --git a/src/WebServer.cpp b/src/WebServer.cpp new file mode 100644 index 0000000..d6b1698 --- /dev/null +++ b/src/WebServer.cpp @@ -0,0 +1,352 @@ +#include "WebServer.h" + +#include +#include +#include +#include + +extern "C" { + #include "user_interface.h" +} + +void WebServer::root_call() +{ + if (web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str()) == false) + { + web_server.requestAuthentication(); + return; + } + + File html = LittleFS.open("/root.html", "r"); + if (!html) + { + web_server.send(404); + return; + } + web_server.streamFile(html, "text/html"); + html.close(); +} + +void WebServer::js_root_call() +{ + if (web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str()) == false) + { + web_server.requestAuthentication(); + return; + } + + File js = LittleFS.open("/root.js", "r"); + if (!js) + { + web_server.send(404); + return; + } + + web_server.streamFile(js, "application/javascript"); + js.close(); +} + +void WebServer::css_root_call() +{ + if (web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str()) == false) + { + web_server.requestAuthentication(); + return; + } + + File css = LittleFS.open("/root.css", "r"); + if (!css) + { + web_server.send(404); + return; + } + + web_server.streamFile(css, "text/css"); + css.close(); +} + +void WebServer::settings_call() +{ + if (web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str()) == false) + { + web_server.requestAuthentication(); + return; + } + + File html = LittleFS.open("/settings.html", "r"); + if (!html) + { + web_server.send(404); + return; + } + web_server.streamFile(html, "text/html"); + html.close(); +} + +void WebServer::js_settings_call() +{ + if (web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str()) == false) + { + web_server.send(401); + return; + } + + File js_script = LittleFS.open("/settings.js", "r"); + if (!js_script) + { + web_server.send(404); + return; + } + web_server.streamFile(js_script, "application/javascript"); + js_script.close(); +} + +void WebServer::css_settings_call() +{ + if (web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str()) == false) + { + web_server.send(401); + return; + } + + File css_script = LittleFS.open("/settings.css", "r"); + if (!css_script) + { + web_server.send(404); + return; + } + web_server.streamFile(css_script, "text/css"); + css_script.close(); +} + +void WebServer::ap_update() +{ + if (!web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str())) + { + web_server.send(401); + return; + } + + JsonDocument json; + DeserializationError err = deserializeJson(json, web_server.arg("plain")); + if (err) + { + web_server.send(400); + return; + } + if (json["ssid"].isNull() || json["pass"].isNull()) + { + web_server.send(400); + return; + } + + String ssid = json["ssid"]; + if (ssid.isEmpty()) + { + web_server.send(400); + return; + } + settings_.setAPSSID(ssid); + + String pass = json["pass"]; + settings_.setAPPASS(pass); + + + web_server.send(200); + delay(100); + ESP.restart(); +} +void WebServer::sta_update() +{ + if (!web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str())) + { + web_server.send(401); + return; + } + + JsonDocument json; + DeserializationError err = deserializeJson(json, web_server.arg("plain")); + if (err) + { + web_server.send(400); + return; + } + if (json["ssid"].isNull() || json["pass"].isNull()) + { + web_server.send(400); + return; + } + + String ssid = json["ssid"]; + if (ssid.isEmpty()) + { + web_server.send(400); + return; + } + settings_.setModemSSID(ssid); + + String pass = json["pass"]; + settings_.setModemPASS(pass); + + web_server.send(200); + delay(100); + ESP.restart(); +} +void WebServer::admin_update() +{ + if (!web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str())) + { + web_server.send(401); + return; + } + + JsonDocument json; + DeserializationError err = deserializeJson(json, web_server.arg("plain")); + if (err) + { + web_server.send(400); + return; + } + if (json["new_pass"].isNull()) + { + web_server.send(400); + return; + } + + settings_.setAdminPass(json["new_pass"]); + web_server.send(200); +} +void WebServer::is_conn_out() +{ + if (!web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str())) + { + web_server.send(401); + return; + } + + bool is_conn_out = settings_.getConnToOut(); + JsonDocument json; + json["is_conn_out"] = is_conn_out; + String serialize; + serializeJson(json, serialize); + web_server.send(200, "application/json", serialize); +} + +void WebServer::set_conn_out() +{ + if (!web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str())) + { + web_server.send(401); + return; + } + + JsonDocument json; + DeserializationError err = deserializeJson(json, web_server.arg("plain")); + if (err) + { + web_server.send(400); + return; + } + if (json["is_conn_out"].isNull()) + { + web_server.send(400); + return; + } + + settings_.setConnToOut(json["is_conn_out"]); + web_server.send(200); + delay(100); + ESP.restart(); +} + +void WebServer::get_user_list() +{ + if (!web_server.authenticate(settings_.getAdminLogin().c_str(), settings_.getAdminPass().c_str())) + { + web_server.send(401); + return; + } + + JsonDocument json; + JsonArray IPs = json["user_ip"].to(), MACs = json["user_mac"].to(); + + struct station_info *stat_info = wifi_softap_get_station_info(); + while (stat_info != nullptr) + { + String mac; + for(int i = 0; i < 6; ++i) + { + char num[2]; + itoa(stat_info->bssid[i], num, 16); + mac += num; + if (i < 5) mac += ':'; + } + MACs.add(mac); + + IPAddress ip = IPAddress(stat_info->ip); + IPs.add(ip.toString()); + stat_info = STAILQ_NEXT(stat_info, next); + } + wifi_softap_free_station_info(); + + String serialized; + serializeJson(json, serialized); + + web_server.send(200, "application/json", serialized); +} + +WebServer::WebServer(Settings& settings, int port): +web_server(port), +settings_(settings) +{ + web_server.on("/", [this](){ + root_call(); + }); + web_server.on("/root.js", [this](){ + js_root_call(); + }); + web_server.on("/root.css", [this](){ + css_root_call(); + }); + + web_server.on("/settings", [this](){ + settings_call(); + }); + web_server.on("/settings.js", [this](){ + js_settings_call(); + }); + web_server.on("/settings.css", [this](){ + css_settings_call(); + }); + + web_server.on("/settings/ap_update", [this](){ + ap_update(); + }); + + web_server.on("/settings/sta_update", [this](){ + sta_update(); + }); + + web_server.on("/settings/admin_update", [this](){ + admin_update(); + }); + + web_server.on("/settings/is_conn_out", [this](){ + is_conn_out(); + }); + + web_server.on("/settings/set_conn_out", [this](){ + set_conn_out(); + }); + + web_server.on("/user_list", [this](){ + get_user_list(); + }); + + web_server.begin(); +} + +void WebServer::tick() +{ + web_server.handleClient(); +} \ No newline at end of file diff --git a/src/WebServer.h b/src/WebServer.h new file mode 100644 index 0000000..f7f8850 --- /dev/null +++ b/src/WebServer.h @@ -0,0 +1,32 @@ +#pragma once + +#include "Settings.h" +#include + +class WebServer +{ + ESP8266WebServer web_server; + Settings& settings_; + + void root_call(); + void js_root_call(); + void css_root_call(); + + void settings_call(); + void js_settings_call(); + void css_settings_call(); + + void ap_update(); + void sta_update(); + void admin_update(); + + void is_conn_out(); + void set_conn_out(); + + void get_user_list(); + +public: + WebServer(Settings& settings, int port = 80); + + void tick(); +}; \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..8846e88 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,114 @@ +#include +#include +#include +#include +#include "WebServer.h" +#include "Settings.h" + +Settings settings; +WebServer server(settings); + +bool CheckSSID(String ssid) +{ + bool isFind = false; + int cnt = WiFi.scanNetworks(); + for (int i = 0; i < cnt; ++i) + { + Serial.print("SSID: "); + Serial.println(WiFi.SSID(i)); + Serial.print("\tRSSI: "); + Serial.println(WiFi.RSSI(i)); + + if (WiFi.SSID(i) == ssid) + isFind = true; + } + return isFind; +} + +void conn_out() +{ + if (CheckSSID(settings.getModemSSID())) + { + Serial.print("Connecting to "); + Serial.print(settings.getModemSSID()); + WiFi.begin(settings.getModemSSID(), settings.getModemPASS()); + for(unsigned int i = 0; WiFi.status() != WL_CONNECTED && i < settings.getCntRetry(); ++i) + { + delay(settings.getDelay()); + Serial.print("."); + } + Serial.println(""); + + if (WiFi.status() == WL_CONNECTED) + { + Serial.println("[+] STA mode started"); + Serial.print("\tSTA IP: "); + Serial.println(WiFi.localIP()); + } + else + { + Serial.print("[-] STA mode failed "); + Serial.println(settings.getModemSSID()); + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + return; + } + } + else + { + Serial.print("[-] Network not found "); + Serial.println(settings.getModemSSID()); + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + return; + } + + ip_napt_init(256, 64); + ip_napt_enable_no(SOFTAP_IF, 1); + auto& server = WiFi.softAPDhcpServer(); + server.setDns(WiFi.dnsIP()); +} + +void setup() { + Serial.begin(115200); + Serial.println(); + + if (!LittleFS.begin()) { + Serial.println("An Error has occurred while mounting LittleFS"); + return; + } + + settings.init(); + settings.print(); + + if (settings.getConnToOut()) + WiFi.mode(WIFI_AP_STA); + else + WiFi.mode(WIFI_AP); + + if (WiFi.softAP(settings.getAPSSID(), settings.getAPPASS())) + { + Serial.println("[+] AP mode started"); + Serial.print("\tSSID: "); + Serial.println(settings.getAPSSID()); + Serial.print("\tPASS: "); + Serial.println(settings.getAPPASS()); + Serial.print("\tAP IP: "); + Serial.println(WiFi.softAPIP()); + } + else + { + WiFi.mode(WIFI_OFF); + Serial.println("[-] AP mode failed"); + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + return; + } + + if (settings.getConnToOut()) + conn_out(); +} + +void loop() { + server.tick(); +} diff --git a/test/README b/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html