Files
ADSL_wifi_tester/ADSL_wifi_tester.ino

414 lines
13 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#define _LCD_TYPE 1
#include <LiquidCrystal_I2C.h>
#include <LCD_1602_RUS_ALL.h>
LCD_1602_RUS lcd(0x3F, 16, 2);
const char* ssid = "TP-LINK_904E";
const char* password = "30923805";
const char* server = "192.168.1.1"; // IP роутера
const int port = 23; // Порт Telnet
const char* telnetUser = "admin";
const char* telnetPass = "admin";
const char* cmdadsl = "adsl info --show";
WiFiClient client;
String readResponse() {
String response = "";
unsigned long startTime = millis();
while (millis() - startTime < 2000) { // Читаем 2 секунды
if (client.available()) {
char c = client.read();
response += c;
}
}
return response;
}
void sendCommand(String command) {
if (client.connected()) {
client.print(command);
client.print("\r\n");
Serial.println("Команда отправлена: " + command);
// Ждем и читаем ответ
delay(1000);
String response = readResponse();
Serial.println("Ответ:");
Serial.println(response);
} else {
Serial.println("Нет подключения к роутеру!");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Не удаётся");
lcd.setCursor(0,1);
lcd.print("подкл. к telnet");
}
}
String extractMode(String response) {
// Ищем позицию начала Mode данных
int ModeIndex = response.indexOf("Mode:");
if (ModeIndex == -1) {
Serial.println("Mode data not found");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Нет данных");
lcd.setCursor(0,1);
lcd.print("о режиме передачи");
return "null";
}
int dataStart = ModeIndex + 5; // 5 символов в "Mode:"
// Извлекаем подстроку с данными
String dataLine = response.substring(dataStart);
int endOfLine = dataLine.indexOf("\n");
if (endOfLine != -1) {
dataLine = dataLine.substring(0, endOfLine);
}
dataLine.trim(); // Убираем пробелы в начале и конце
Serial.print("Mode: ");
Serial.println(dataLine);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Стандарт ADSL:");
lcd.setCursor(0,1);
lcd.print(dataLine);
return dataLine;
}
void extractSpeed(String response) {
// Ищем позицию начала Speed данных
int SpeedIndex = response.indexOf("Max:");
if (SpeedIndex == -1) {
Serial.println("Speed data not found");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Нет данных");
lcd.setCursor(0,1);
lcd.print("о скорости");
return;
}
int dataStart = SpeedIndex + 4; // 4 символа в "Max:"
// Извлекаем подстроку с данными
String dataLine = response.substring(dataStart);
// Ищем конец строки (до следующей метки или конца)
int endOfLine = dataLine.indexOf("\n");
if (endOfLine != -1) {
dataLine = dataLine.substring(0, endOfLine);
}
// Теперь у нас строка типа: " Upstream rate = 1307 Kbps, Downstream rate = 27992 Kbps"
// Разделяем ее на два значения
dataLine.trim(); // Убираем пробелы в начале и конце
String Upstream = dataLine;
Upstream=Upstream.substring(16,dataLine.indexOf(", "));
String Downstream = dataLine;
Downstream=Downstream.substring(dataLine.indexOf(", ")+20,dataLine.indexOf("\n"));
Serial.print("Speed Down: ");
Serial.println(Downstream);
Serial.print("Speed Up: ");
Serial.println(Upstream);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Ск. И " + String(Upstream));
lcd.setCursor(0,1);
lcd.print("Ск. В " + String(Downstream));
}
void extractSNR(String response) {
// Ищем позицию начала SNR данных
int snrIndex = response.indexOf("SNR (dB):");
if (snrIndex == -1) {
Serial.println("SNR data not found");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Нет данных");
lcd.setCursor(0,1);
lcd.print("об уровне шума");
return;
}
int dataStart = snrIndex + 9; // 9 символов в "SNR (dB):"
// Извлекаем подстроку с данными
String dataLine = response.substring(dataStart);
// Ищем конец строки (до следующей метки или конца)
int endOfLine = dataLine.indexOf("\n");
if (endOfLine != -1) {
dataLine = dataLine.substring(0, endOfLine);
}
// Теперь у нас строка типа: " 20.5 27.3"
// Разделяем ее на два значения
dataLine.trim(); // Убираем пробелы в начале и конце
// Первое число закончится, когда начнутся пробелы перед вторым числом
int spaceBetween = dataLine.indexOf(" ");
if (spaceBetween == -1) {
// Если нет двойного пробела, ищем одинарный
spaceBetween = dataLine.indexOf(' ', dataLine.indexOf(' ') + 1);
}
if (spaceBetween != -1) {
String snrDown = dataLine.substring(0, spaceBetween);
String snrUp = dataLine.substring(spaceBetween);
snrUp.trim();
float downSNR = snrDown.toFloat();
float upSNR = snrUp.toFloat();
Serial.print("SNR Down: ");
Serial.println(downSNR);
Serial.print("SNR Up: ");
Serial.println(upSNR);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Шум. И " + String(upSNR) + "dB");
lcd.setCursor(0,1);
lcd.print("Шум. В " + String(downSNR) + "dB");
}
}
void extractAttn(String response) {
// Ищем позицию начала Attn данных
int AttnIndex = response.indexOf("Attn(dB):");
if (AttnIndex == -1) {
Serial.println("Attn data not found");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Нет данных");
lcd.setCursor(0,1);
lcd.print("о затухании");
return;
}
int dataStart = AttnIndex + 9; // 9 символов в "Attn(dB):"
// Извлекаем подстроку с данными
String dataLine = response.substring(dataStart);
// Ищем конец строки (до следующей метки или конца)
int endOfLine = dataLine.indexOf("\n");
if (endOfLine != -1) {
dataLine = dataLine.substring(0, endOfLine);
}
// Теперь у нас строка типа: " 0.0 0.8"
// Разделяем ее на два значения
dataLine.trim(); // Убираем пробелы в начале и конце
// Первое число закончится, когда начнутся пробелы перед вторым числом
int spaceBetween = dataLine.indexOf(" ");
if (spaceBetween == -1) {
// Если нет двойного пробела, ищем одинарный
spaceBetween = dataLine.indexOf(' ', dataLine.indexOf(' ') + 1);
}
if (spaceBetween != -1) {
String AttnDown = dataLine.substring(0, spaceBetween);
String AttnUp = dataLine.substring(spaceBetween);
AttnUp.trim();
float downAttn = AttnDown.toFloat();
float upAttn = AttnUp.toFloat();
Serial.print("Attn Down: ");
Serial.println(downAttn);
Serial.print("Attn Up: ");
Serial.println(upAttn);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Зат. И " + String(upAttn) + "dB");
lcd.setCursor(0,1);
lcd.print("Зат. В " + String(downAttn) + "dB");
}
}
void extractPwr(String response) {
// Ищем позицию начала Pwr данных
int PwrIndex = response.indexOf("Pwr(dBm):");
if (PwrIndex == -1) {
Serial.println("Pwr data not found");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Нет данных");
lcd.setCursor(0,1);
lcd.print("о мощности");
return;
}
int dataStart = PwrIndex + 9; // 9 символов в "Pwr (dBm):"
// Извлекаем подстроку с данными
String dataLine = response.substring(dataStart);
// Ищем конец строки (до следующей метки или конца)
int endOfLine = dataLine.indexOf("\n");
if (endOfLine != -1) {
dataLine = dataLine.substring(0, endOfLine);
}
// Теперь у нас строка типа: " 7.5 9.3"
// Разделяем ее на два значения
dataLine.trim(); // Убираем пробелы в начале и конце
// Первое число закончится, когда начнутся пробелы перед вторым числом
int spaceBetween = dataLine.indexOf(" ");
if (spaceBetween == -1) {
// Если нет двойного пробела, ищем одинарный
spaceBetween = dataLine.indexOf(' ', dataLine.indexOf(' ') + 1);
}
if (spaceBetween != -1) {
String PwrDown = dataLine.substring(0, spaceBetween);
String PwrUp = dataLine.substring(spaceBetween);
PwrUp.trim();
float downPwr = PwrDown.toFloat();
float upPwr = PwrUp.toFloat();
Serial.print("Pwr Down: ");
Serial.println(downPwr);
Serial.print("Pwr Up: ");
Serial.println(upPwr);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Мощн. И " + String(upPwr) + "dBm");
lcd.setCursor(0,1);
lcd.print("Мощн. В " + String(downPwr) + "dBm");
}
}
float mapf(float value, float fromLow, float fromHigh, float toLow, float toHigh)
{
float result;
result = (value - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
return result;
}
void setup() {
pinMode(A0, INPUT);
int percentv = ((mapf(analogRead(A0),0,1024,0,4.2) - 3.3) / (4.2 - 3.3)) * 100.0;
if(percentv<0)percentv=0;
if(percentv>100)percentv=100;
lcd.init();
lcd.backlight();
Serial.begin(115200);
WiFi.begin(ssid, password);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Инициализация");
lcd.setCursor(0,1);
lcd.print("тестера");
delay(1000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Заряд батареи");
lcd.setCursor(0,1);
lcd.print(String(percentv) + "%");
delay(2000);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Инициализация");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
lcd.setCursor(0,1);
lcd.print("WiFi");
}
Serial.println("\nПодключено к WiFi");
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Подключен к WiFi");
delay(1000);
if (client.connect(server, port)) {
Serial.println("Подключен к Telnet-серверу");
lcd.setCursor(0,1);
lcd.print("Подкл. к Telnet");
} else {
Serial.println("Ошибка подключения");
lcd.setCursor(0,1);
lcd.print("Ошибка подключ.");
}
if (client.connected()) {
// Читаем приветственное сообщение
String response = readResponse();
Serial.println("Ответ от роутера:");
Serial.println(response);
// Отправляем логин
client.print(telnetUser);
client.print("\r\n");
Serial.println("Отправлен логин: " + String(telnetUser));
delay(1000);
// Читаем ответ и отправляем пароль
response = readResponse();
Serial.println("Ответ от роутера:");
Serial.println(response);
client.print(telnetPass);
client.print("\r\n");
Serial.println("Отправлен пароль: " + String(telnetPass));
delay(1000);
// Читаем финальный ответ
response = readResponse();
Serial.println("Ответ от роутера:");
Serial.println(response);
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Подкл. " + String(ssid));
lcd.setCursor(0,1);
lcd.print("Прием данных");
}
delay(1000);
}
void loop() {
delay(1000);
if (client.connected()) {
client.print(cmdadsl);
client.print("\r\n");
Serial.println("Отправил: " + String(cmdadsl));
delay(1000);
String response = readResponse();
// Serial.println("Ответ от роутера:");
// Serial.println(response);
extractMode(response);
delay(4000);
extractSpeed(response);
delay(4000);
extractSNR(response);
delay(4000);
extractAttn(response);
delay(4000);
extractPwr(response);
delay(4000);
}
}