Global change

This commit is contained in:
Dmitry Borisenko
2020-06-19 22:14:50 +02:00
parent 446809355b
commit 817a3e5898
90 changed files with 3370 additions and 2709 deletions

View File

@@ -1,10 +1,10 @@
{ {
"name": "IoTmanager", "name": "IoTmanager",
"chipID": "", "chipID": "",
"ssidAP": "WiFi2", "apssid": "IoTmanager",
"passwordAP": "", "appass": "",
"ssid": "rise", "routerssid": "rise",
"password": "hostel3333", "routerpass": "hostel3333",
"timezone": 2, "timezone": 2,
"ntp": "pool.ntp.org", "ntp": "pool.ntp.org",
"mqttServer": "91.204.228.124", "mqttServer": "91.204.228.124",
@@ -12,9 +12,10 @@
"mqttPrefix": "/rise", "mqttPrefix": "/rise",
"mqttUser": "test", "mqttUser": "test",
"mqttPass": "test", "mqttPass": "test",
"scenario": "1", "scen": "1",
"pushingbox_id": "v7C133E426B0C69E", "pushingboxid": "v7C133E426B0C69E",
"web_login": "admin", "weblogin": "admin",
"web_pass": "admin", "webpass": "admin",
"udponoff": "1" "udponoff": "1",
"blink":"1"
} }

View File

@@ -0,0 +1,3 @@
button 1 5 Включить#реле Реле 0 1
//это простая кнопка номер 1 управляющая пином 5 имеющая начальное состояние 0

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,7 @@
dhtT t 2 dht22 Температура#DHT,#t°C Датчики any-data 1
dhtH h 2 dht22 Влажность#DHT,#t°C Датчики any-data 2
dhtComfort Степень#комфорта: Датчики 3
dhtPerception Восприятие: Датчики 4
dhtDewpoint Точка#росы: Датчики 5
logging t 1 50 Температура Датчики 6
logging h 1 50 Влажность Датчики 7

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,8 @@
analog adc 0 Аналоговый#вход,#% Датчики progress-round 310 620 1 100 1
logging adc 5 100 Аналоговый#вход Датчики 2
//если датчик углекислого газа выдает напряжение от 1 вольта до 2 вольт, то значит
//значение чтения аналогового входа будут примерно равным
//при 1 вольте - 310, а при 2 вольтах - 620 (считаем по пропорции)
//данная строка переведет диапазон 310-620 в диапазон 1-100 и отобразит в приложении
//варианты отображения: any-data, progress-round, progress-line, fill-gauge

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,6 @@
bmp280T temp1 0x76 Температура#bmp280 Датчики any-data 1
bmp280P press1 0x76 Давление#bmp280 Датчики any-data 2
logging temp1 1 100 Температура Датчики 3
logging press1 1 100 Давление Датчики 4
//Чтение и логгирование датчика bmp280. Датчик подключается к шине i2c (esp8266 - gpio 5, 4)

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,9 @@
bme280T temp1 0x76 Температура#bmp280 Датчики any-data 1
bme280P pres1 0x76 Давление#bmp280 Датчики any-data 2
bme280H hum1 0x76 Влажность#bmp280 Датчики any-data 3
bme280A altit1 0x76 Высота#bmp280 Датчики any-data 4
logging temp1 1 100 Температура Датчики 5
logging press1 1 100 Давление Датчики 6
logging hum1 1 100 Влажность Датчики 7
//Чтение и логгирование датчика bme280. Датчик подключается к шине i2c (esp8266 - gpio 5, 4)

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,5 @@
dallas 2 Водонагреватель,#t°C Датчики any-data 1
logging dallas 1 100 Температура Датчики 2
//2 - номер пина датчика
//варианты отображения: any-data, progress-round, progress-line, fill-gauge

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,12 @@
dallas 2 Водонагреватель,#t°C Термостат any-data 1
logging dallas 5 100 Температура Термостат 2
inputDigit digit1 При#скольки#выключить? Термостат 40 3
inputDigit digit2 При#скольки#включить? Термостат 20 4
button 1 5 Нагреватель Термостат 0 5
button 2 line1,line2, Автоматический#режим Термостат 1 6
//2 - номер пина датчика
//5 - номер пина реле
//это термостат который будет держать температуру между двумя
//установленными в приложении значениями, так же можно выключить
//автоматический режим, и тогда нагреватель будет управляться в ручную

View File

@@ -0,0 +1,6 @@
dallas > digit1
buttonSet 1 0
end
dallas < digit2
buttonSet 1 1
end

View File

@@ -0,0 +1,12 @@
ultrasonicPr p 14 12 Уровень#в#баке,#% Датчики fill-gauge 125 25 1
ultrasonicCm cm 14 12 Дистанция,#см Датчики any-data 2
inputDigit digit1 При#скольки#выключить? Датчики 95 3
inputDigit digit2 При#скольки#включить? Датчики 10 4
button 1 5 Насос Датчики 0 5
logging p 1 100 Вода#в#баке Датчики 6
//125 - это расстояние от датчика до дна бака в сантиметрах
//25 - это расстояние от датчика до поверхности воды когда бак полный в сантиметрах
//distancePr - эта строка выводит процент заполнения бака
//distanceCm - эта строка выводит расстояние в сантиметрах
//варианты отображения: any-data, progress-round, progress-line, fill-gauge

View File

@@ -0,0 +1,6 @@
p > digit1
buttonSet 1 0
end
p < digit2
buttonSet 1 1
end

View File

@@ -0,0 +1,11 @@
button 1 5 Прихожая Освещение 0 1
inputDigit digit1 Задержка#выключения Освещение 30 2
switch 1 0 10
//0 - номер пина датчика движения
//5 - номер пина реле
//при срабатывании датчика движения включится реле и обратный таймер на 30 сек
//если движение не будет обнаружено повтороно в течении 30 секунд - свет выключится
//если движение повторится в течении 30 секунд то таймер продлится опять на 30 сек
//свет выключится только в том случае если в комнате все замрет на 30 сек
//задержку выключения можно будет настраивать в приложении

View File

@@ -0,0 +1,7 @@
switch1 = 1
timerStart 1 digit1 sec
buttonSet 1 1
end
timer1 = 0
buttonSet 1 0
end

View File

@@ -0,0 +1,12 @@
switch 1 0 20
text 1 Вход: Охрана 1
textSet 1 не#обнаружено-time
button 1 na Сбросить Охрана 0 2
button 2 line3, Включить#push Охрана 1 3
//0 - номер пина датчика
//при срабатывании датчика движения устройство пошлет пуш и в приложении будет
//написано в текстовом поле, что движение было обнаружено
//так же будет зафиксирован момент времени срабатывания датчика
//в приложении можно отключать отправку пуш сообщений на тот случай если дома хозяин
//перевести датчик снова в режим ожидания движения можно нажав кнопку сброса в приложении

View File

@@ -0,0 +1,10 @@
switch1 = 1
textSet 1 обнаружено#движение-time
end
button1 = 1
textSet 1 не#обнаружено-time
buttonSet 1 0
end
switch1 = 1
push Внимание обнаружено#движение!
end

View File

@@ -0,0 +1,17 @@
stepper 1 12 4
stepper 2 13 5
button 1 na Открыть#штору#1 Шторы 0 1
button 2 na Открыть#штору#2 Шторы 0 2
//для подключения необходим драйвер шагового двигателя A4988
//stepper 1 12 4 шаговый двигатель с параметрами: 1 - номер шагового двигателя,
//12 - номер пина количества шагов, 4 - номер пина направления
//stepper 2 13 5 шаговый двигатель с параметрами: 2 - номер шагового двигателя,
//13 - номер пина количества шагов, 5 - номер пина направления
//stepperSet 1 200 5 - прокрутить шаговик номер 1 на 200 шагов по часовой стрелке
//с задержкой между шагами 5 милисекунд (чем меньше задержка тем больше скорость)
//если поставить -200 то будет вращаться против часовой стрелки
//можно подключить не более двух шаговиков

View File

@@ -0,0 +1,12 @@
button1 = 1
stepperSet 1 200 1
end
button1 = 0
stepperSet 1 -200 1
end
button2 = 1
stepperSet 2 200 1
end
button2 = 0
stepperSet 2 -200 1
end

View File

@@ -0,0 +1,6 @@
inputTime time1 Во#сколько#включить? Таймеры 20-30-00 1
inputTime time2 Во#сколько#выключить? Таймеры 20-35-00 2
button 1 5 Кнопка#(по#таймеру) Таймеры 0 3
//время в приложение необходимо вводить в строгом формате: ЧЧ-ММ-СС
//можно создавать любое количество таймеров, копируя строку inputTime...

View File

@@ -0,0 +1,6 @@
timenow = time1
buttonSet 1 1
end
timenow = time2
buttonSet 1 0
end

View File

@@ -0,0 +1,17 @@
servo 1 12 50 Мой#сервопривод Сервоприводы 0 100 0 180 1
servo 2 13 50 Мой#сервопривод Сервоприводы 0 100 0 180 2
button 1 na Открыть1 Сервоприводы 0 3
button 2 na Открыть2 Сервоприводы 0 4
//Можно создавать не более двух сервоприводов на одном устройстве.
//1 - номер привода
//12 - номер пина
//50 - начальное значение в процентах
//0 - 100 диапазон ползунка
//0 - 180 диапазон угла
//Представим ситуацию когда есть некая заслонка и при угле в 30 градусов она закрыта,
//а при угле в 90 градусов открыта. В этом случае необходимо написать
//0 100 30 90 и тогда поставив ползунок в 0 % серва встанет в положение 30 градусов,
//а если поставить ползунок в 100 % серва встанет в положение 90 градусов.

View File

@@ -0,0 +1,12 @@
button1 = 1
servoSet 1 100
end
button1 = 0
servoSet 1 0
end
button2 = 1
servoSet 2 100
end
button2 = 0
servoSet 2 0
end

View File

@@ -0,0 +1,4 @@
button 1 5 Вкл#на#время Таймеры 0 1
inputDigit digit1 Через#сколько#секунд#выключить? Таймеры 5 2
//в сценариях можно поменять на sec, min или hours если нужны другие размерности времени

View File

@@ -0,0 +1,6 @@
button1 = 1
timerStart 1 digit1 sec
end
timer1 = 0
buttonSet 1 0
end

View File

@@ -0,0 +1,3 @@
button 1 na Включить#все Освещение 0 1
//при нажатии на эту кнопку пины номер 5 и 13 поведут себя как установленно в сценариях

View File

@@ -0,0 +1,8 @@
button1 = 1
pinSet 5 1
pinSet 13 0
end
button1 = 0
pinSet 5 0
pinSet 13 1
end

View File

@@ -0,0 +1,4 @@
button 1 13 Включить#реле Реле 0 1
switch 1 0 10
//можно управлять реле на пине 13 кнопкой на пине 0 или кнопкой в приложении

View File

@@ -0,0 +1,3 @@
switch1 = 1
buttonChange 1
end

View File

@@ -0,0 +1,6 @@
button 1 5 Включить#все Реле 0 1
//что бы использовать эту конфигурацию на другой esp необходимо активировать пресет
//"Вкл. выкл. локального реле", затем в сценарии данного модуля подставить Device ID
//того esp, кнопка на этом девайсе будет выключать другие устройства по воздуху

View File

@@ -0,0 +1,8 @@
button1 = 1
mqtt 3233662-1589485 buttonSet_1_1
mqtt 2233662-1589486 buttonSet_1_1
end
button1 = 0
mqtt 3233662-1589485 buttonSet_1_0
mqtt 2233662-1589486 buttonSet_1_0
end

View File

@@ -0,0 +1,6 @@
switch 1 0 10
//что бы использовать эту конфигурацию на другой esp необходимо активировать пресет
//"Вкл. выкл. локального реле", затем в сценарии данного модуля подставить Device ID
//того esp, к данному модулю нужно подключить кнопку к пину 0 и тогда
//один девайс будет управлять другим по воздуху

View File

@@ -0,0 +1,4 @@
switch1 = 1
mqtt 3233662-1589485 buttonChange_1
mqtt 2233662-1589486 buttonChange_1
end

6
data/configs/8-pwm.c.txt Normal file
View File

@@ -0,0 +1,6 @@
pwm 1 3 Яркость#коредор: Реле 1023 1
pwm 2 4 Яркость#ванная: Реле 510 2
//в приложении появятся ползунки, соответствующее значение pwm
//будет установленно на пинах 3 и 4
//1023 и 510 это начальные значения после загрузки модуля

1
data/configs/8-pwm.s.txt Normal file
View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,7 @@
dhtT t 2 dht11 Температура#DHT,#t°C Датчики any-data 1
dhtH h 2 dht11 Влажность#DHT,#t°C Датчики any-data 2
dhtComfort Степень#комфорта: Датчики 3
dhtPerception Восприятие: Датчики 4
dhtDewpoint Точка#росы: Датчики 5
logging t 1 50 Температура Датчики 6
logging h 1 50 Влажность Датчики 7

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,12 @@
button 1 na Включить#все Реле 0 1
button 2 13 Прихожая Реле 0 2
button 3 14 Кухня Реле 0 3
pwm 1 3 Яркость#коредор: Реле 1023 4
pwm 2 4 Яркость#ванная: Реле 510 5
analog adc 0 Аналоговый#вход Датчики fill-gauge 1 1023 1 1023 6
logging adc 1 100 Аналоговый#вход Датчики 7
//Это демо конфигурация. В ней показано как связать кнопки c помощью сценариев
//Кнопка номер 1 связана с кнопкой 2, 3 и с pwm 2
//Так же продемонстрированна система логгирования данных строкой logging
//1 - это интервал между точками в минутах, 100 это количество точек

View File

@@ -0,0 +1,13 @@
button1 = 1
buttonSet 2 1
buttonSet 3 1
pwmSet 2 1024
end
button1 = 0
buttonSet 2 0
buttonSet 3 0
pwmSet 2 0
end
adc > 50
buttonSet 2 1
end

View File

@@ -1,118 +0,0 @@
{
"configs": [
"/config.live.json",
"/config.setup.json",
"/config.option.json"
],
"class": "col-sm-offset-1 col-sm-10",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-warning"
},
{
"type": "h4",
"title": "Device ID: {{chipID}}"
},
{
"type": "h4",
"title": "IP address: {{ip}}"
},
{
"type": "h4",
"title": "Uptime: {{uptime}}"
},
{
"type": "h4",
"title": "Time: {{time}}"
},
{
"type": "hr"
},
{
"type": "dropdown",
"name": "help-url",
"class": "btn btn-warning btn-lg",
"style": "display:inline",
"title": {
"#": "Выбирите то, во что Вы хотите превратить это устройство <span class=\"caret\"></span>",
"/preset?arg=1": "1.Вкл. выкл. локального реле",
"/preset?arg=2": "2.Вкл. выкл. локального реле в определенное время",
"/preset?arg=3": "3.Вкл. выкл. локального реле на определенный период времени",
"/preset?arg=4": "4.Вкл. выкл. нескольких локальных реле кнопкой в приложении",
"/preset?arg=5": "5.Вкл. выкл. локального реле физической кнопкой и кнопкой в приложении параллельно (для выключателя света)",
"/preset?arg=6": "6.Вкл. выкл. нескольких удаленных реле кнопкой в приложении (нужно указать Device ID)",
"/preset?arg=7": "7.Вкл. выкл. нескольких удаленных реле физической кнопкой (нужно указать Device ID)",
"/preset?arg=8": "8.Широтно импульсная модуляция",
"/preset?arg=9": "9.Сенсор DHT11 и логгирование",
"/preset?arg=10": "10.Сенсор DHT22, DHT33, DHT44, AM2302, RHT03 и логгирование",
"/preset?arg=11": "11.Аналоговый сенсор и логгирование",
"/preset?arg=12": "12.Сенсор DS18B20 и логгирование",
"/preset?arg=13": "13.Термостат на DS18B20 с переключением в ручной режим и логгированием",
"/preset?arg=14": "14.Контроль уровня в баке на сенсорах: JSN-SR04T, HC-SR04, HY-SRF05 и логгирование (управление насосом)",
"/preset?arg=15": "15.Датчик движения включающий свет",
"/preset?arg=16": "16.Охранный датчик движения",
"/preset?arg=17": "17.Система управления шаговыми двигателями на основе драйвера A4988 (открытие закрытие штор)",
"/preset?arg=18": "18.Система управления сервоприводами",
"/preset?arg=19": "Настройки по умолчанию"
}
},
{
"type": "h2",
"title": "Конфигурация устройства"
},
{
"type": "file",
"state": "firmware.c.txt",
"style": "width:100%;height:400px",
"title": "Сохранить",
"action": "/init?arg=2",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Подробная инструкция",
"action": "https://github.com/DmitryBorisenko33/esp32-esp8266_iot-manager_modules_firmware/wiki/Instruction",
"class": "btn btn-block btn-primary"
},
{
"type": "h2",
"title": "Сценарии"
},
{
"type": "checkbox",
"name": "scenario",
"title": "Включить сценарии",
"action": "/init?arg=[[scenario]]",
"state": "{{scenario}}"
},
{
"type": "h6",
"title": ""
},
{
"type": "file",
"state": "firmware.s.txt",
"style": "width:100%;height:400px",
"title": "Сохранить",
"action": "/init?arg=4",
"class": "btn btn-block btn-success"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Очистить логи сенсоров",
"action": "/init?arg=3",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Главная",
"action": "/",
"class": "btn btn-block btn-danger btn-sm"
}
]
}

Binary file not shown.

View File

@@ -1,92 +0,0 @@
{
"configs": [
"/config.live.json",
"/config.setup.json"
],
"title": "Главная",
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-warning"
},
{
"type": "h3",
"title": "Список других устройств в сети:"
},
{
"type": "hr"
},
{
"type": "csv",
"title": [
"html",
"html",
"html"
],
"state": "dev.csv",
"style": "width:100%;",
"class": "nan"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Переформировать список устройств",
"action": "udp?arg=3",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Обновить страницу",
"action": "udp?arg=4",
"class": "btn btn-block btn-success"
},
{
"type": "hr"
},
{
"type": "text",
"class": "alert alert-warning",
"title": "После нажатия на кнопку 'Переформировать список устройств' ждите примерно минуту, а затем обновите страницу и список появится вновь"
},
{
"type": "h3",
"title": "Имя этого устройства:"
},
{
"type": "input",
"title": "Имя устройства",
"name": "dev_name",
"state": "{{name}}",
"pattern": "[A-Za-z0-9]{6,12}"
},
{
"type": "button",
"title": "Сохранить",
"action": "name?arg=[[dev_name]]",
"class": "btn btn-block btn-success"
},
{
"type": "hr"
},
{
"type": "checkbox",
"name": "udponoff",
"title": "Включить обмен данными между устройствами",
"action": "/udp?arg=[[udponoff]]",
"state": "{{udponoff}}"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Главная",
"action": "/",
"class": "btn btn-block btn-danger"
}
]
}

BIN
data/icon.jpeg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

View File

@@ -1,7 +1,8 @@
{ {
"configs": [ "configs": [
"/config.live.json", "/config.live.json",
"/config.setup.json" "/config.setup.json",
"/lang/lang.ru.json"
], ],
"title": "Главная", "title": "Главная",
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
@@ -9,104 +10,60 @@
{ {
"type": "h5", "type": "h5",
"title": "{{name}}", "title": "{{name}}",
"class": "alert-warning" "class": "alert-default"
}, },
{ {
"type": "h4", "type": "text",
"title": "Device ID: {{chipID}}" "class": "alert alert-light",
}, "title": "<center><img src='/icon.jpeg' alt='IoT Manager'></center>"
{ },
"type": "h4",
"title": "IP address: {{ip}}"
},
{
"type": "h4",
"title": "Uptime: {{uptime}}"
},
{
"type": "h4",
"title": "Time: {{time}}"
},
{
"type": "h4",
"title": "Build version: {{firmware_version}}"
},
{
"type": "h4",
"title": "SPIFFS version: 2.3.3"
},
{
"type": "hr"
},
{ {
"type": "link", "type": "link",
"title": "Конфигурация устройства", "title": "Конфигурация устройства",
"action": "/?configuration", "action": "/?set.device",
"class": "btn btn-block btn-primary" "class": "btn btn-block btn-default"
},
{
"type": "hr"
}, },
{ {
"type": "link", "type": "link",
"title": "Список других устройств в сети", "title": "Список других устройств в сети",
"action": "/?dev", "action": "/?set.udp",
"class": "btn btn-block btn-success" "class": "btn btn-block btn-default"
}, },
{ {
"type": "link", "type": "link",
"title": "Конфигурация WIFI", "title": "Конфигурация WIFI",
"action": "/?setup", "action": "/?set.wifi",
"class": "btn btn-block btn-success" "class": "btn btn-block btn-default"
}, },
{ {
"type": "link", "type": "link",
"title": "Конфигурация MQTT", "title": "Конфигурация MQTT",
"action": "/?mqtt", "action": "/?set.mqtt",
"class": "btn btn-block btn-success" "class": "btn btn-block btn-default"
}, },
{ {
"type": "link", "type": "link",
"title": "Конфигурация push", "title": "Конфигурация push",
"action": "/?pushingbox", "action": "/?set.push",
"class": "btn btn-block btn-success" "class": "btn btn-block btn-default"
}, },
{ {
"type": "link", "type": "link",
"title": "Утилиты", "title": "Утилиты",
"action": "/?utilities", "action": "/?set.utilities",
"class": "btn btn-block btn-success" "class": "btn btn-block btn-default"
},
{
"type": "h3",
"name": "my-block",
"style": "position:fixed;top:50%;left:50%;width:400px;margin-left:-200px;text-align:center;",
"class": "hidden"
},
{
"type": "hr"
},
{
"type": "button",
"title": "Обновить прошивку",
"action": "/check",
"response": "[[my-block]]",
"class": "btn btn-block btn-danger"
},
{
"type": "hr"
}, },
{ {
"type": "link", "type": "link",
"title": "Скачать приложение IoT Manager для android", "title": "Скачать приложение IoT Manager для android",
"action": "https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager", "action": "https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager",
"class": "btn btn-block btn-warning" "class": "btn btn-block btn-default"
}, },
{ {
"type": "link", "type": "link",
"title": "Скачать приложение IoT Manager для iphone", "title": "Скачать приложение IoT Manager для iphone",
"action": "https://apps.apple.com/ru/app/iot-manager/id1155934877", "action": "https://apps.apple.com/ru/app/iot-manager/id1155934877",
"class": "btn btn-block btn-warning" "class": "btn btn-block btn-default"
} }
] ]
} }

Binary file not shown.

Binary file not shown.

39
data/lang/lang.ru.json Normal file
View File

@@ -0,0 +1,39 @@
{
"SetDevConf": "Конфигурация устройства",
"SetDevPreset": "Выберите из списка подходящий пресет кофигурации",
"ButSave":"Сохранить",
"ButMainPage":"Главная",
"SetUDPList": "Список других устройств в сети:",
"SetUDPWarn1": "После нажатия на кнопку <b>переформировать список устройств</b> ждите примерно минуту, а затем обновите страницу и список появится вновь",
"SetUDPUpdateList":"Переформировать список устройств",
"SetUDPUpdatePage":"Обновить страницу",
"SetUDPNameOfDev":"Имя этого устройства:",
"SetUDPDateExchange":"Включить обмен данными между устройствами",
"SetUDPWarn2":"Если обмен данными включен, то устройства будут обмениваться широковещательными пакетами udp для формирования списка устройств и для осуществления посылки настроек mqtt. Данный обмен создает дополнительную нагрузку на wifi сеть.",
"SetWiFiNameOfDev":"Имя устройства:",
"SetWiFiRouterConnect":"Подключение к WiFi роутеру:",
"SetWiFiAccessPoint":"Точка доступа:",
"SetWiFiWeb":"Логин и пароль web interface:",
"SetWiFiTimeZone":"Временная зона:",
"SetWiFiNTP":"Сервер NTP:",
"SetWiFiWarn1":"Имя устройства должно состоять из английских букв и иметь длинну от 6 до 12 символов",
"SetWiFiWarn2":"После того как вы введете логин пароль от вашего wifi роутера необходимо нажать кнопку сохранить, а затем обязательно нажать кнопку <b>перезагрузить устройство</b> внизу этой страницы",
"SetWiFiWarn3":"Устройство постоянно сканирует сеть на наличие wifi. Если роутер отключен, то устройство автоматически перейдет в режим точки доступа. Когда wifi появится устройство автоматически подключится к роутеру снова, и выключит точку доступа",
"SetWiFiWarn4":"После изменения поля <b>NTP сервер</b> необходимо перезагрузить устройство",
"SetWiFiWarn5":"Светодиод статуса подключения показывает четыре состояния подключения: <br><b>1. мигает редко</b> - идет подключение к wifi <br><b>2. мигает часто</b> - идет подключение к серверу mqtt <br><b>3. горит постоянно</b> - модуль в режиме точки доступа, <br><b>4. не горит</b> - модуль подключен к wifi и к mqtt. <br>Светодиод подключен к gpio2. Если галочка стоит - то использовать этот пин нельзя",
"SetMQTTServerName":"Имя сервера:",
"SetMQTTPort":"Номер порта:",
"SetMQTTPrefix":"Префикс:",
"SetMQTTUserName":"Имя пользователя:",
"SetMQTTPassword":"Пароль:",
"SetMQTTSendSettings":"Отправить настройки MQTT с этого устройства на все остальные",
"SetMQTTWarn1":"Обратите внимание что поле префикс может состоять только из одного слова и одного разделителя: <b>/prefix</b>, вариант вида: <b>/prefix1/prefix2</b> работать не будет. После изменения поля prefix необходимо перезагрузить устройство",
"SetMQTTWarn2":"Прежде чем нажимать на кнопку <b>Отправить настройки MQTT</b> сохрание их, если Вы их меняли. Настройки получат и перезапишут все устройства в локальной сети"
}

View File

@@ -1,111 +0,0 @@
{
"configs": [
"/config.setup.json"
],
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-warning"
},
{
"type": "text",
"class": "alert alert-warning",
"title": "Обратите внимание что поле prefix может состоять только из одного слова и одного разделителя: <b>/prefix</b>, вариант вида: <b>/prefix1/prefix2</b> работать не будет. После изменения поля prefix необходимо перезагрузить устройство"
},
{
"type": "h4",
"title": "Server name:"
},
{
"type": "input",
"title": "",
"name": "1",
"state": "{{mqttServer}}"
},
{
"type": "h4",
"title": "Port:"
},
{
"type": "input",
"title": "",
"name": "2",
"state": "{{mqttPort}}"
},
{
"type": "h4",
"title": "Prefix:"
},
{
"type": "input",
"title": "",
"name": "3",
"state": "{{mqttPrefix}}"
},
{
"type": "h4",
"title": "User name:"
},
{
"type": "input",
"title": "",
"name": "4",
"state": "{{mqttUser}}"
},
{
"type": "h4",
"title": "Password:"
},
{
"type": "input",
"title": "",
"name": "5",
"state": "{{mqttPass}}"
},
{
"type": "h3",
"name": "my-block",
"style": "position:fixed;top:30%;left:50%;width:400px;margin-left:-200px;text-align:center;",
"class": "hidden"
},
{
"type": "text",
"class": "alert alert-warning",
"title": "Прежде чем нажимать на кнопку <b>'Отправить настройки MQTT'</b> сохрание их, если Вы их меняли. Настройки получат и перезапишут все устройства в локальной сети"
},
{
"type": "button",
"title": "Сохранить",
"action": "mqttSave?mqttServer=[[1]]&mqttPort=[[2]]&mqttPrefix=[[3]]&mqttUser=[[4]]&mqttPass=[[5]]",
"class": "btn btn-block btn-success"
},
{
"type": "button",
"title": "Отправить настройки MQTT с этого устройства на все остальные",
"action": "udp?arg=2",
"class": "btn btn-block btn-success"
},
{
"type": "button",
"title": "Проверить соединение с MQTT",
"action": "mqttCheck",
"response": "[[my-block]]",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Перезагрузить устройство",
"action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}",
"class": "btn btn-block btn-success"
},
{
"type": "link",
"title": "Главная",
"action": "/",
"class": "btn btn-block btn-danger btn-sm"
}
]
}

View File

@@ -1,46 +0,0 @@
{
"configs": [
"/config.setup.json"
],
"class":"col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class":"alert-warning"
},
{
"type": "h4",
"title": "Device id:"
},
{
"type": "input",
"title": "",
"name":"1",
"state": "{{pushingbox_id}}"
},
{
"type": "button",
"title":"Сохранить",
"action": "pushingboxDate?pushingbox_id=[[1]]",
"class": "btn btn-block btn-success",
"style": "width:100%;display:inline"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Перезагрузить устройство",
"action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}",
"class": "btn btn-block btn-warning"
},
{
"type": "link",
"title": "Главная",
"action": "/",
"class": "btn btn-block btn-danger btn-sm"
}
]
}

143
data/set.device.json Normal file
View File

@@ -0,0 +1,143 @@
{
"configs": [
"/config.setup.json",
"/config.option.json",
"/config.live.json",
"/lang/lang.ru.json"
],
"class": "col-sm-offset-1 col-sm-10",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-default"
},
{
"type": "link",
"title": "{{ButMainPage}}",
"action": "/",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "h4",
"title": "Device ID: {{chipID}}"
},
{
"type": "h4",
"title": "IP address: {{ip}}"
},
{
"type": "h4",
"title": "Time: {{time}}"
},
{
"type": "h4",
"title": "Uptime: {{uptime}}"
},
{
"type": "h4",
"title": "Build version: {{firmware_version}}"
},
{
"type": "h4",
"title": "SPIFFS version: 2.3.4"
},
{
"type": "hr"
},
{
"type": "dropdown",
"name": "help-url",
"class": "btn btn-default",
"style": "display:inline",
"title": {
"#": "{{SetDevPreset}}<span class=\"caret\"></span>",
"/set?preset=1": "1.Вкл. выкл. локального реле",
"/set?preset=2": "2.Вкл. выкл. локального реле в определенное время",
"/set?preset=3": "3.Вкл. выкл. локального реле на определенный период времени",
"/set?preset=4": "4.Вкл. выкл. нескольких локальных реле кнопкой в приложении",
"/set?preset=5": "5.Вкл. выкл. локального реле физической кнопкой и кнопкой в приложении параллельно (для выключателя света)",
"/set?preset=6": "6.Вкл. выкл. нескольких удаленных реле кнопкой в приложении (нужно указать Device ID)",
"/set?preset=7": "7.Вкл. выкл. нескольких удаленных реле физической кнопкой (нужно указать Device ID)",
"/set?preset=8": "8.Широтно импульсная модуляция",
"/set?preset=9": "9.Сенсор DHT11 (темп, влажность) и логгирование",
"/set?preset=10": "10.Сенсор DHT22, DHT33, DHT44, AM2302, RHT03 (темп, влажность) и логгирование",
"/set?preset=11": "11.Аналоговый сенсор и логгирование",
"/set?preset=12": "12.Cенсор bmp280 (темп, давление) и логгирование",
"/set?preset=13": "13.Cенсор bme280 (темп, давление, влажность, высота) и логгирование",
"/set?preset=14": "12.Сенсор DS18B20 (темп) и логгирование",
"/set?preset=15": "13.Термостат на DS18B20 с переключением в ручной режим и логгированием",
"/set?preset=16": "14.Котроль уровня в баке (датчик расстояния) на сенсорах: JSN-SR04T, HC-SR04, HY-SRF05 и логгирование",
"/set?preset=17": "15.Датчик движения включающий свет",
"/set?preset=18": "16.Охранный датчик движения",
"/set?preset=19": "17.Система управления шаговыми двигателями на основе драйвера A4988 (открытие закрытие штор)",
"/set?preset=20": "18.Система управления сервоприводами",
"/set?preset=21": "Настройки по умолчанию"
}
},
{
"type": "h2",
"title": "{{SetDevConf}}"
},
{
"type": "file",
"state": "firmware.c.txt",
"style": "width:100%;height:350px",
"title": "Сохранить",
"action": "/set?devinit",
"class": "btn btn-block btn-default"
},
{
"type": "h2",
"title": "Сценарии"
},
{
"type": "checkbox",
"name": "scen",
"title": "Включить сценарии",
"action": "/set?scen=[[scen]]",
"state": "{{scen}}"
},
{
"type": "file",
"state": "firmware.s.txt",
"style": "width:100%;height:350px",
"title": "Сохранить",
"action": "/set?sceninit",
"class": "btn btn-block btn-default"
},
{
"type": "link",
"title": "Инструкция к системе автоматизации",
"action": "https://github.com/DmitryBorisenko33/esp32-esp8266_iot-manager_modules_firmware/wiki/Instruction",
"class": "btn btn-block btn-default"
},
{
"type": "link",
"title": "Очистить логи сенсоров",
"action": "/set?cleanlog",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "h3",
"name": "my-block",
"style": "position:fixed;top:50%;left:50%;width:400px;margin-left:-200px;text-align:center;",
"class": "hidden"
},
{
"type": "button",
"title": "Обновить прошивку устройства",
"action": "/check",
"response": "[[my-block]]",
"class": "btn btn-block btn-default"
}
]
}

133
data/set.mqtt.json Normal file
View File

@@ -0,0 +1,133 @@
{
"configs": [
"/config.setup.json",
"/lang/lang.ru.json"
],
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-default"
},
{
"type": "link",
"title": "{{ButMainPage}}",
"action": "/",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "h4",
"title": "{{SetMQTTServerName}}",
"style": "width:60%;float:left;"
},
{
"type": "input",
"title": "",
"name": "mqttServer-arg",
"state": "{{mqttServer}}",
"style": "width:40%;float:right"
},
{
"type": "h4",
"title": "{{SetMQTTPort}}",
"style": "width:60%;float:left;"
},
{
"type": "input",
"title": "",
"name": "mqttPort-arg",
"state": "{{mqttPort}}",
"style": "width:40%;float:right"
},
{
"type": "h4",
"title": "{{SetMQTTPrefix}}",
"style": "width:60%;float:left;"
},
{
"type": "input",
"title": "",
"name": "mqttPrefix-arg",
"state": "{{mqttPrefix}}",
"style": "width:40%;float:right"
},
{
"type": "h4",
"title": "{{SetMQTTUserName}}",
"style": "width:60%;float:left;"
},
{
"type": "input",
"title": "",
"name": "mqttUser-arg",
"state": "{{mqttUser}}",
"style": "width:40%;float:right"
},
{
"type": "h4",
"title": "{{SetMQTTPassword}}",
"style": "width:60%;float:left;"
},
{
"type": "input",
"title": "",
"name": "mqttPass-arg",
"state": "{{mqttPass}}",
"style": "width:40%;float:right"
},
{
"type": "h3",
"name": "my-block",
"style": "position:fixed;top:30%;left:50%;width:400px;margin-left:-200px;text-align:center;",
"class": "hidden"
},
{
"type": "button",
"title": "{{ButSave}}",
"style": "width:100%;float:left;",
"action": "set?mqttServer=[[mqttServer-arg]]&mqttPort=[[mqttPort-arg]]&mqttPrefix=[[mqttPrefix-arg]]&mqttUser=[[mqttUser-arg]]&mqttPass=[[mqttPass-arg]]",
"class": "btn btn-block btn-default"
},
{
"type": "button",
"style": "width:100%;float:left;",
"title": "{{SetMQTTSendSettings}}",
"action": "set?mqttsend",
"class": "btn btn-block btn-default"
},
{
"type": "button",
"style": "width:100%;float:left;",
"title": "Проверить соединение с MQTT",
"action": "set?mqttcheck",
"response": "[[my-block]]",
"class": "btn btn-block btn-default"
},
{
"type": "text",
"style": "width:100%;float:left;",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetMQTTWarn1}}</p></font></div>"
},
{
"type": "text",
"style": "width:100%;float:left;",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetMQTTWarn2}}</p></font></div>"
},
{
"type": "link",
"style": "width:100%;float:left;",
"title": "Перезагрузить устройство",
"action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}",
"class": "btn btn-block btn-danger"
}
]
}

51
data/set.push.json Normal file
View File

@@ -0,0 +1,51 @@
{
"configs": [
"/config.setup.json",
"/lang/lang.ru.json"
],
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-default"
},
{
"type": "link",
"title": "{{ButMainPage}}",
"action": "/",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "h4",
"style": "width:60%;float:left;",
"title": "Device id:"
},
{
"type": "input",
"title": "",
"name": "push-arg",
"style": "width:40%;float:right",
"state": "{{pushingboxid}}"
},
{
"type": "button",
"title": "{{ButSave}}",
"action": "set?pushingboxid=[[push-arg]]",
"class": "btn btn-block btn-default",
"style": "width:100%;display:inline"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Перезагрузить устройство",
"action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}",
"class": "btn btn-block btn-danger"
}
]
}

96
data/set.udp.json Normal file
View File

@@ -0,0 +1,96 @@
{
"configs": [
"/config.setup.json",
"/lang/lang.ru.json"
],
"title": "Главная",
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-default"
},
{
"type": "link",
"title": "{{ButMainPage}}",
"action": "/",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "h3",
"title": "{{SetUDPList}}"
},
{
"type": "hr"
},
{
"type": "csv",
"title": [
"html",
"html",
"html"
],
"state": "dev.csv",
"style": "width:100%;",
"class": "nan"
},
{
"type": "hr"
},
{
"type": "link",
"title": "{{SetUDPUpdateList}}",
"action": "/set?updatelist",
"class": "btn btn-block btn-default"
},
{
"type": "link",
"title": "{{SetUDPUpdatePage}}",
"action": "/set?updatepage",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "text",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetUDPWarn1}}</p></font></div>",
"style": "width:100%;float:left;"
},
{
"type": "h3",
"title": "{{SetUDPNameOfDev}}"
},
{
"type": "input",
"title": "{{SetUDPNameOfDev}}",
"name": "devname-arg",
"state": "{{name}}",
"pattern": "[A-Za-z0-9]{6,12}"
},
{
"type": "button",
"title": "{{ButSave}}",
"action": "/set?devname=[[devname-arg]]",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "checkbox",
"name": "udponoff",
"title": "{{SetUDPDateExchange}}",
"action": "/set?udponoff=[[udponoff]]",
"state": "{{udponoff}}"
},
{
"type": "text",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetUDPWarn2}}</p></font></div>"
}
]
}

View File

@@ -1,7 +1,8 @@
{ {
"configs": [ "configs": [
"/config.live.json", "/config.live.json",
"/config.setup.json" "/config.setup.json",
"/lang/lang.ru.json"
], ],
"title": "Главная", "title": "Главная",
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6", "class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
@@ -9,7 +10,13 @@
{ {
"type": "h5", "type": "h5",
"title": "{{name}}", "title": "{{name}}",
"class": "alert-warning" "class": "alert-default"
},
{
"type": "link",
"title": "{{ButMainPage}}",
"action": "/",
"class": "btn btn-block btn-default"
}, },
{ {
"type": "hr" "type": "hr"
@@ -25,17 +32,8 @@
{ {
"type": "link", "type": "link",
"title": "Сканировать", "title": "Сканировать",
"action": "/init?arg=5", "action": "/set?itoc",
"class": "btn btn-block btn-success" "class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Главная",
"action": "/",
"class": "btn btn-block btn-danger"
} }
] ]
} }

185
data/set.wifi.json Normal file
View File

@@ -0,0 +1,185 @@
{
"configs": [
"/config.setup.json",
"/lang/lang.ru.json"
],
"title": "Конфигурация",
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-default"
},
{
"type": "link",
"title": "{{ButMainPage}}",
"action": "/",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "h3",
"title": "{{SetWiFiNameOfDev}}"
},
{
"type": "input",
"title": "{{SetWiFiNameOfDev}}",
"name": "devname-arg",
"state": "{{name}}",
"pattern": "[A-Za-z0-9]{6,12}"
},
{
"type": "button",
"title": "{{ButSave}}",
"action": "set?devname=[[devname-arg]]",
"class": "btn btn-block btn-default"
},
{
"type": "text",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetWiFiWarn1}}</p></font></div>"
},
{
"type": "hr"
},
{
"type": "h3",
"title": "{{SetWiFiRouterConnect}}"
},
{
"type": "input",
"title": "",
"name": "routerssid-arg",
"state": "{{routerssid}}"
},
{
"type": "password",
"title": "",
"name": "routerpass-arg",
"state": "{{routerpass}}"
},
{
"type": "button",
"title": "{{ButSave}}",
"class": "btn btn-block btn-default",
"action": "set?routerssid=[[routerssid-arg]]&routerpass=[[routerpass-arg]]"
},
{
"type": "text",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetWiFiWarn2}}</p></font></div>"
},
{
"type": "hr"
},
{
"type": "checkbox",
"name": "blink",
"title": "Включить светодиод статуса подключения",
"action": "/set?blink=[[blink]]",
"state": "{{blink}}"
},
{
"type": "text",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetWiFiWarn5}}</p></font></div>"
},
{
"type": "hr"
},
{
"type": "h3",
"title": "{{SetWiFiAccessPoint}}"
},
{
"type": "input",
"title": "",
"name": "apssid-arg",
"state": "{{apssid}}",
"pattern": ".{1,20}"
},
{
"type": "password",
"title": "",
"name": "appass-arg",
"state": "{{appass}}",
"pattern": ".{8,20}"
},
{
"type": "button",
"title": "{{ButSave}}",
"action": "set?apssid=[[apssid-arg]]&appass=[[appass-arg]]",
"class": "btn btn-block btn-default"
},
{
"type": "text",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetWiFiWarn3}}</p></font></div>"
},
{
"type": "hr"
},
{
"type": "h3",
"title": "{{SetWiFiWeb}}"
},
{
"type": "input",
"title": "Логин",
"name": "weblogin-arg",
"state": "{{weblogin}}",
"pattern": ".{1,20}"
},
{
"type": "password",
"title": "Пароль",
"name": "webpass-arg",
"state": "{{webpass}}",
"pattern": ".{1,20}"
},
{
"type": "button",
"title": "{{ButSave}}",
"action": "set?weblogin=[[weblogin-arg]]&webpass=[[webpass-arg]]",
"class": "btn btn-block btn-default"
},
{
"type": "hr"
},
{
"type": "h3",
"title": "{{SetWiFiTimeZone}}"
},
{
"type": "input",
"title": "",
"name": "timezone-arg",
"state": "{{timezone}}",
"pattern": ".{1,20}"
},
{
"type": "input",
"title": "",
"name": "ntp-arg",
"state": "{{ntp}}"
},
{
"type": "button",
"title": "{{ButSave}}",
"action": "set?timezone=[[timezone-arg]]&ntp=[[ntp-arg]]",
"class": "btn btn-block btn-default"
},
{
"type": "text",
"title": "<div style='margin-top:10px;margin-bottom:10px;'><font color='black'><p style='border: 1px solid #DCDCDC; border-radius: 3px; background-color: #F5F5F5; padding: 10px;'>{{SetWiFiWarn4}}</p></font></div>"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Перезагрузить устройство",
"action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/set?device=ok');}",
"class": "btn btn-block btn-danger"
}
]
}

View File

@@ -1,162 +0,0 @@
{
"configs": [
"/config.setup.json"
],
"title": "Конфигурация",
"class": "col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8 col-lg-offset-3 col-lg-6",
"content": [
{
"type": "h5",
"title": "{{name}}",
"class": "alert-warning"
},
{
"type": "link",
"title": "Главная",
"action": "/",
"class": "btn btn-block btn-danger"
},
{
"type": "hr"
},
{
"type": "h2",
"title": "Имя устройства"
},
{
"type": "input",
"title": "Имя устройства",
"name": "dev_name",
"state": "{{name}}",
"pattern": "[A-Za-z0-9]{6,12}"
},
{
"type": "button",
"title": "Сохранить",
"action": "name?arg=[[dev_name]]",
"class": "btn btn-block btn-success"
},
{
"type": "hr"
},
{
"type": "h2",
"title": "Подключение к Wi-Fi роутеру"
},
{
"type": "input",
"title": "Сеть",
"name": "ssid",
"state": "{{ssid}}"
},
{
"type": "password",
"title": "Введите пароль",
"name": "ssidPass",
"state": "{{password}}"
},
{
"type": "button",
"title": "Сохранить",
"class": "btn btn-block btn-success",
"action": "ssid?ssid=[[ssid]]&password=[[ssidPass]]"
},
{
"type": "hr"
},
{
"type": "h2",
"title": "Точка доступа"
},
{
"type": "input",
"title": "Имя WI-FI сети",
"name": "ssidap",
"state": "{{ssidAP}}",
"pattern": ".{1,20}"
},
{
"type": "password",
"title": "Пароль",
"name": "ssidApPass",
"state": "{{passwordAP}}",
"pattern": ".{8,20}"
},
{
"type": "button",
"title": "Сохранить",
"action": "ssidap?ssidAP=[[ssidap]]&passwordAP=[[ssidApPass]]",
"class": "btn btn-block btn-success"
},
{
"type": "hr"
},
{
"type": "h2",
"title": "Логин и пароль web interface"
},
{
"type": "input",
"title": "Логин",
"name": "web-login",
"state": "{{web_login}}",
"pattern": ".{1,20}"
},
{
"type": "password",
"title": "Пароль",
"name": "web-pass",
"state": "{{web_pass}}",
"pattern": ".{1,20}"
},
{
"type": "button",
"title": "Сохранить",
"action": "web?web_login=[[web-login]]&web_pass=[[web-pass]]",
"class": "btn btn-block btn-success"
},
{
"type": "hr"
},
{
"type": "h2",
"title": "Временная зона"
},
{
"type": "input",
"title": "Временная зона",
"name": "1",
"state": "{{timezone}}",
"pattern": ".{1,20}"
},
{
"type": "input",
"title": "Название ntp сервера",
"name": "2",
"state": "{{ntp}}"
},
{
"type": "button",
"title": "Сохранить",
"action": "time?timezone=[[1]]&ntp=[[2]]",
"class": "btn btn-block btn-success"
},
{
"type": "hr"
},
{
"type": "text",
"class": "alert alert-warning",
"title": "После изменения поля <b>'NTP сервер'</b> необходимо перезагрузить устройство"
},
{
"type": "hr"
},
{
"type": "link",
"title": "Перезагрузить устройство",
"action": "javascript:if(confirm(renameBlock(jsonResponse,'Перезагрузить?'))){send_request(this,'/restart?device=ok');}",
"class": "btn btn-block btn-warning"
}
]
}

View File

@@ -0,0 +1,7 @@
{
"widget" : "select",
"size" : "small",
"fill" : "outline",
"options" : "["Zero item", "First item", "Second item"]",
"status" : 2
}

View File

@@ -1,4 +1,5 @@
#pragma once #pragma once
//Здесь хранятся все настройки прошивки
#define firmware_version "2.3.3" #define firmware_version "2.3.3"

View File

@@ -1,21 +1,27 @@
#pragma once #pragma once
//=========ПОДКЛЮЧЕНИЕ ОБЩИХ БИБЛИОТЕК===============
#include <Arduino.h> #include <Arduino.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <Bounce2.h> #include <Bounce2.h>
#include <ESPAsyncWebServer.h> #include <ESPAsyncWebServer.h>
extern AsyncWebServer server;
#include <FS.h> #include <FS.h>
#include <PubSubClient.h> #include <PubSubClient.h>
#include <SPIFFSEditor.h> #include <SPIFFSEditor.h>
#include <StringCommand.h> #include <StringCommand.h>
#include <TickerScheduler.h> #include <TickerScheduler.h>
#include <time.h> #include <time.h>
#include "Consts.h" #include "Consts.h"
#include <UpTime.h>
/* #include "GyverFilters.h"
* ESP8266 #include <DallasTemperature.h>
*/ #include <OneWire.h>
#include <DHTesp.h>
#include <Wire.h>
#include <Adafruit_BMP280.h>
#include <Adafruit_BME280.h>
//==============ESP8266 БИБЛИОТЕКИ===============
#ifdef ESP8266 #ifdef ESP8266
#include <ESP8266HTTPClient.h> #include <ESP8266HTTPClient.h>
#include <ESP8266HTTPUpdateServer.h> #include <ESP8266HTTPUpdateServer.h>
@@ -29,10 +35,7 @@ WiFiUDP Udp;
#include <ESP8266mDNS.h> #include <ESP8266mDNS.h>
#endif #endif
#endif #endif
//==============ESP32 БИБЛИОТЕКИ===============
/*
* ESP32
*/
#ifdef ESP32 #ifdef ESP32
#include <AsyncTCP.h> #include <AsyncTCP.h>
#include <AsyncUDP.h> #include <AsyncUDP.h>
@@ -55,9 +58,63 @@ extern Servo myServo2;
#include <ArduinoOTA.h> #include <ArduinoOTA.h>
#endif #endif
//==============================Objects.h(без данных)==================================
#ifdef WS_enable
extern AsyncWebSocket ws;
#endif
//extern AsyncEventSource events;
extern TickerScheduler ts;
enum {ROUTER_SEARCHING, WIFI_MQTT_CONNECTION_CHECK, SENSORS, STEPPER1, STEPPER2, LOG1, LOG2, LOG3, LOG4, LOG5, TIMER_COUNTDOWN, TIME, TIME_SYNC, STATISTICS, UPTIME, UDP, UDP_DB, TEST };
extern WiFiClient espClient;
extern PubSubClient client_mqtt;
extern StringCommand sCmd;
extern AsyncWebServer server; extern AsyncWebServer server;
// Global vars //AsyncWebSocket ws;
//AsyncEventSource events;
#define NUM_BUTTONS
extern boolean but[NUM_BUTTONS];
extern Bounce * buttons;
extern GMedian<10, int> medianFilter;
extern OneWire *oneWire;
extern DallasTemperature sensors;
extern DHTesp dht;
extern Adafruit_BMP280 bmp;
extern Adafruit_Sensor *bmp_temp;
extern Adafruit_Sensor *bmp_pressure;
extern Adafruit_BME280 bme;
extern Adafruit_Sensor *bme_temp;
extern Adafruit_Sensor *bme_pressure;
extern Adafruit_Sensor *bme_humidity;
uptime_interval myUpTime;
///////////////////////////////////// Global vars ////////////////////////////////////////////////////////////////////
extern boolean udp_busy;
extern unsigned int udp_port;
extern IPAddress udp_multicastIP;
extern String received_ip;
extern String received_udp_line;
extern int udp_period;
extern boolean just_load; extern boolean just_load;
extern const char *hostName; extern const char *hostName;
@@ -107,83 +164,10 @@ extern boolean udp_data_parse;
extern boolean mqtt_send_settings_to_udp; extern boolean mqtt_send_settings_to_udp;
extern boolean i2c_scanning; extern boolean i2c_scanning;
#ifdef WS_enable
extern AsyncWebSocket ws;
#endif
extern AsyncEventSource events;
extern int sensors_reading_map[15]; extern int sensors_reading_map[15];
enum {
ROUTER_SEARCHING,
WIFI_MQTT_CONNECTION_CHECK,
SENSORS,
STEPPER1,
STEPPER2,
LOG1,
LOG2,
LOG3,
LOG4,
LOG5,
TIMER_COUNTDOWN,
TIME,
TIME_SYNC,
STATISTICS,
UDP,
UDP_DB,
TEST
};
extern TickerScheduler ts; ///////////////////////////////////// Functions////////////////////////////////////////////////////////////////////
extern WiFiClient espClient;
extern PubSubClient client_mqtt;
extern StringCommand sCmd;
#define NUM_BUTTONS 6
extern boolean but[NUM_BUTTONS];
extern Bounce *buttons;
extern boolean udp_busy;
extern unsigned int udp_port;
extern IPAddress udp_multicastIP;
extern String received_ip;
extern String received_udp_line;
extern int udp_period;
#ifdef level_enable
#include "GyverFilters.h"
extern GMedian<10, int> medianFilter;
#endif
#include <DallasTemperature.h>
#include <OneWire.h>
extern OneWire *oneWire;
extern DallasTemperature sensors;
#include <DHTesp.h>
extern DHTesp dht;
#include <Wire.h>
#ifdef bmp_enable
#include <Adafruit_BMP280.h>
extern Adafruit_BMP280 bmp;
extern Adafruit_Sensor *bmp_temp;
extern Adafruit_Sensor *bmp_pressure;
#endif
#ifdef bme_enable
#include <Adafruit_BME280.h>
extern Adafruit_BME280 bme;
extern Adafruit_Sensor *bme_temp;
extern Adafruit_Sensor *bme_pressure;
extern Adafruit_Sensor *bme_humidity;
#endif
//#include <SoftwareSerial.h>
//SoftwareSerial mySerial(14, 12);
// StringUtils // StringUtils
extern uint8_t hexStringToUint8(String hex); extern uint8_t hexStringToUint8(String hex);
@@ -381,4 +365,10 @@ extern void handleButton();
extern void handleScenario(); extern void handleScenario();
extern void handleUdp(); extern void handleUdp();
extern void do_upgrade_url(); extern void do_upgrade_url();
extern void do_upgrade(); extern void do_upgrade();
//uptime
extern void handle_uptime();
extern void handle_statistics();
extern void uptime_init();
extern void web_init();

View File

@@ -0,0 +1,2 @@
0.01 2019-01-14
- initial version

View File

@@ -0,0 +1,15 @@
all: README examples/UpTime_tick/README examples/UpTime_synopsis/README
clean:
rm -f README README.bak \
examples/UpTime_tick/README examples/UpTime_tick/README.bak \
examples/UpTime_synopsis/README examples/UpTime_synopsis/README.bak
README: UpTime.h
pod2readme $< $@ && rm -f $@.bak
examples/UpTime_tick/README: examples/UpTime_tick/UpTime_tick.ino
pod2readme $< $@ && rm -f $@.bak
examples/UpTime_synopsis/README: examples/UpTime_synopsis/UpTime_synopsis.ino
pod2readme $< $@ && rm -f $@.bak

99
lib/Arduino-UpTime/README Normal file
View File

@@ -0,0 +1,99 @@
NAME
UpTime.h - Arduino uptime and events in seconds
SYNOPSIS
#include <Arduino.h>
#include <UpTime.h> // https://github.com/jozef/Arduino-UpTime
uptime_interval fire2(2);
uptime_interval fire5(5,UPTIME_RIGHT_AWAY);
void setup () {
Serial.begin(9600);
}
void loop () {
Serial.println("uptime: "+uptime_as_string()+" or "+uptime()+"s");
if (fire2.check()) Serial.println("2s elapsed");
if (fire5.check()) Serial.println("5s elapsed");
delay(1400);
}
will output:
uptime: 00:00:00 or 0s
5s elapsed
uptime: 00:00:01 or 1s
uptime: 00:00:02 or 2s
2s elapsed
uptime: 00:00:04 or 4s
2s elapsed
uptime: 00:00:05 or 5s
5s elapsed
uptime: 00:00:07 or 7s
2s elapsed
uptime: 00:00:08 or 8s
2s elapsed
uptime: 00:00:09 or 9s
uptime: 00:00:11 or 11s
2s elapsed
5s elapsed
uptime: 04:41:23 or 16883s
uptime: 04:41:25 or 16885s
2s elapsed
5s elapsed
uptime: 04:41:26 or 16886s
2s elapsed
uptime: 04:41:28 or 16888s
2s elapsed
uptime: 04:41:29 or 16889s
uptime: 04:41:30 or 16890s
2s elapsed
5s elapsed
DESCRIPTION
Uptime class is made to to track uptime of Arduino in seconds. The
uptime() or check() functions has to be called at least once for 0xFFFF
seconds (once in 18h) to work. Seconds will be counted even after
Arduinos millis() overrun and the seconds of unsigned long are enough
to not overrun sooner then in 136+ years. Once 0xFFFF0000 seconds is
elapsed, will trigger reset so that Arduino program clearly starts all
over again.
METHODS
bool check()
Returns true/false if the interval elapset.
void reset(bool postpone = true)
Will reset the time to count from current moment in until interval. If
postpone is set to false, check() will return true with next call.
INSTALL
git clone https://github.com/jozef/Arduino-UpTime sketchbook/libraries/UpTime
EXAMPLES
examples/UpTime_tick/UpTime_synopsis.ino
synopsis section example
examples/UpTime_tick/UpTime_tick.ino
print formatted and raw uptime in seconds und 4x interval
LICENSE
This is free software, licensed under the MIT License.
AUTHOR
Jozef Kutej

View File

@@ -0,0 +1,65 @@
/* see UpTime.h */
#include <Arduino.h>
#include <UpTime.h>
unsigned long _uptime_seconds = 0;
void (*time_to_die)(void) = 0; // reset Arduino after 136+ years
unsigned long uptime() {
unsigned int cur_second = millis() / 1000;
unsigned int _uptime_seconds_uint = _uptime_seconds;
while (_uptime_seconds_uint != cur_second) {
_uptime_seconds++;
_uptime_seconds_uint++;
if (_uptime_seconds > 0xFFFF0000) time_to_die();
}
return _uptime_seconds;
}
uptime_interval::uptime_interval(unsigned int inte, bool postpone) : interval(inte) {
reset(postpone);
}
bool uptime_interval::check() {
if (next <= uptime()) {
next += interval;
return true;
}
return false;
}
void uptime_interval::reset(bool postpone) {
next = (postpone ? _uptime_seconds + interval : _uptime_seconds);
}
String _uptime_two_dig(uint8_t x) {
if (x > 9) {
return String(x);
}
else {
return "0"+String(x);
}
}
String uptime_as_string() {
unsigned long tmp_uptime = uptime();
unsigned long seconds;
unsigned long minutes;
unsigned long hours;
unsigned long days;
seconds = tmp_uptime % 60;
tmp_uptime = tmp_uptime / 60;
minutes = tmp_uptime % 60;
tmp_uptime = tmp_uptime / 60;
hours = tmp_uptime % 24;
days = tmp_uptime / 24;
return (days ? String(days)+'d'+' ' : "")
+ _uptime_two_dig(hours)
+ ':' + _uptime_two_dig(minutes)
+ ':' + _uptime_two_dig(seconds);
}

124
lib/Arduino-UpTime/UpTime.h Normal file
View File

@@ -0,0 +1,124 @@
/* VERSION 0.01; 14.1.2019; see below for description and documentation */
#ifndef UpTime_h
#define UpTime_h
#define UPTIME_RIGHT_AWAY false
unsigned long uptime();
String uptime_as_string();
class uptime_interval {
private:
unsigned long next;
unsigned int interval;
public:
uptime_interval(unsigned int inte, bool postpone = true);
bool check();
void reset(bool postpone = true);
};
#endif
/*
=head1 NAME
UpTime.h - Arduino uptime and events in seconds
=head1 SYNOPSIS
#include <Arduino.h>
#include <UpTime.h> // https://github.com/jozef/Arduino-UpTime
uptime_interval fire2(2);
uptime_interval fire5(5,UPTIME_RIGHT_AWAY);
void setup () {
Serial.begin(9600);
}
void loop () {
Serial.println("uptime: "+uptime_as_string()+" or "+uptime()+"s");
if (fire2.check()) Serial.println("2s elapsed");
if (fire5.check()) Serial.println("5s elapsed");
delay(1400);
}
will output:
uptime: 00:00:00 or 0s
5s elapsed
uptime: 00:00:01 or 1s
uptime: 00:00:02 or 2s
2s elapsed
uptime: 00:00:04 or 4s
2s elapsed
uptime: 00:00:05 or 5s
5s elapsed
uptime: 00:00:07 or 7s
2s elapsed
uptime: 00:00:08 or 8s
2s elapsed
uptime: 00:00:09 or 9s
uptime: 00:00:11 or 11s
2s elapsed
5s elapsed
uptime: 04:41:23 or 16883s
uptime: 04:41:25 or 16885s
2s elapsed
5s elapsed
uptime: 04:41:26 or 16886s
2s elapsed
uptime: 04:41:28 or 16888s
2s elapsed
uptime: 04:41:29 or 16889s
uptime: 04:41:30 or 16890s
2s elapsed
5s elapsed
=head1 DESCRIPTION
Uptime class is made to to track uptime of Arduino in seconds. The uptime()
or check() functions has to be called at least once for 0xFFFF seconds
(once in 18h) to work. Seconds will be counted even after Arduinos
millis() overrun and the seconds of unsigned long are enough to not overrun
sooner then in 136+ years. Once 0xFFFF0000 seconds is elapsed, will trigger
reset so that Arduino program clearly starts all over again.
=head1 METHODS
=head2 bool check()
Returns true/false if the interval elapset.
=head2 void reset(bool postpone = true)
Will reset the time to count from current moment in until interval. If
C<postpone> is set to false, check() will return true with next call.
=head1 INSTALL
git clone https://github.com/jozef/Arduino-UpTime sketchbook/libraries/UpTime
=head1 EXAMPLES
=head2 examples/UpTime_tick/UpTime_synopsis.ino
synopsis section example
=head2 examples/UpTime_tick/UpTime_tick.ino
print formatted and raw uptime in seconds und 4x interval
=head1 LICENSE
This is free software, licensed under the MIT License.
=head1 AUTHOR
Jozef Kutej
=cut
*/

View File

@@ -0,0 +1,4 @@
DESCRIPTION
synopsis section example from UpTime.h

View File

@@ -0,0 +1,24 @@
/*
=head1 DESCRIPTION
synopsis section example from UpTime.h
=cut
*/
#include <Arduino.h>
#include <UpTime.h> // https://github.com/jozef/Arduino-UpTime
uptime_interval fire2(2);
uptime_interval fire5(5,UPTIME_RIGHT_AWAY);
void setup () {
Serial.begin(9600);
}
void loop () {
Serial.println("uptime: "+uptime_as_string()+" or "+uptime()+"s");
if (fire2.check()) Serial.println("2s elapsed");
if (fire5.check()) Serial.println("5s elapsed");
delay(1400);
}

View File

@@ -0,0 +1,11 @@
NAME
UpTime_tick.ino - print formatted and raw uptime in seconds und 4x
interval
DESCRIPTION
On serial port will print current uptime in seconds with 4 interval
checks. Each loop has random 0-5s delay. Intervals will be printed once
elapsed.

View File

@@ -0,0 +1,52 @@
/*
=head1 NAME
UpTime_tick.ino - print formatted and raw uptime in seconds und 4x interval
=head1 DESCRIPTION
On serial port will print current uptime in seconds with 4 interval checks.
Each loop has random 0-5s delay. Intervals will be printed once elapsed.
=cut
*/
#include <Arduino.h>
#include <UpTime.h> // https://github.com/jozef/Arduino-UpTime
uptime_interval fire2(2);
uptime_interval fire5(5);
uptime_interval fire10(10, UPTIME_RIGHT_AWAY);
uptime_interval fire60(60, UPTIME_RIGHT_AWAY);
void setup () {
Serial.begin(9600);
while (Serial.available()) { Serial.read(); }
randomSeed(analogRead(0));
}
void loop () {
Serial.print("uptime: ");
Serial.println(uptime_as_string());
if (fire2.check()) {
Serial.println("fire 2s");
}
if (fire5.check()) {
Serial.println("fire 5s");
}
if (fire10.check()) {
Serial.println("fire 10s");
}
if (fire60.check()) {
Serial.println("fire 60s");
}
int rand_delay = random(5000);
Serial.print("delay(");
Serial.print(rand_delay);
Serial.println(")");
delay(rand_delay);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,35 +1,40 @@
#include "Global.h" #include "Global.h"
void File_system_init() { void File_system_init() {
Serial.begin(115200);
//Serial.setDebugOutput(true); Serial.begin(115200);
Serial.println("--------------started----------------"); //Serial.setDebugOutput(true);
//-------------------------------------------------------------- Serial.println("--------------started----------------");
SPIFFS.begin(); //--------------------------------------------------------------
configSetupJson = readFile("config.json", 4096); SPIFFS.begin();
configSetupJson.replace(" ", ""); configSetupJson = readFile("config.json", 4096);
configSetupJson.replace("\r\n", ""); configSetupJson.replace(" ", "");
Serial.println(configSetupJson); configSetupJson.replace("\r\n", "");
jsonWriteStr(configLiveJson, "name", jsonReadStr(configSetupJson, "name")); Serial.println(configSetupJson);
jsonWriteStr(configLiveJson, "lang", jsonReadStr(configSetupJson, "lang")); //jsonWriteStr(configLiveJson, "name", jsonReadStr(configSetupJson, "name"));
//jsonWriteStr(configLiveJson, "lang", jsonReadStr(configSetupJson, "lang"));
#ifdef ESP32 #ifdef ESP32
uint32_t chipID_u = ESP.getEfuseMac(); uint32_t chipID_u = ESP.getEfuseMac();
chipID = String(chipID_u); chipID = String(chipID_u);
jsonWriteStr(configSetupJson, "chipID", chipID); jsonWriteStr(configSetupJson, "chipID", chipID);
#endif #endif
#ifdef ESP8266 #ifdef ESP8266
chipID = String(ESP.getChipId()) + "-" + String(ESP.getFlashChipId()); chipID = String( ESP.getChipId() ) + "-" + String(ESP.getFlashChipId());
jsonWriteStr(configSetupJson, "chipID", chipID); jsonWriteStr(configSetupJson, "chipID", chipID);
Serial.setDebugOutput(0); Serial.setDebugOutput(0);
#endif #endif
jsonWriteStr(configSetupJson, "firmware_version", firmware_version); jsonWriteStr(configSetupJson, "firmware_version", firmware_version);
prex = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID; prex = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID;
Serial.println(chipID); Serial.println(chipID);
} }
void get_esp_info() { void get_esp_info() {
} }

View File

@@ -1,23 +1,52 @@
#include "Global.h" #include "Global.h"
#include "JsonUtils.h" #include "JsonUtils.h"
//==============================Objects.cpp(с данными)==================================
#ifdef WS_enable
AsyncWebSocket ws;
#endif
//AsyncEventSource events;
TickerScheduler ts(TEST + 1); TickerScheduler ts(TEST + 1);
WiFiClient espClient; WiFiClient espClient;
PubSubClient client_mqtt(espClient); PubSubClient client_mqtt(espClient);
StringCommand sCmd; StringCommand sCmd;
// Web
AsyncWebServer server(80); AsyncWebServer server(80);
#ifdef WS_enable //AsyncWebSocket ws("/ws");
AsyncWebSocket ws("/ws");
#endif
AsyncEventSource events("/events"); //AsyncEventSource events("/events");
#define NUM_BUTTONS 6
boolean but[NUM_BUTTONS];
Bounce * buttons = new Bounce[NUM_BUTTONS];
GMedian<10, int> medianFilter;
OneWire *oneWire;
DallasTemperature sensors;
DHTesp dht;
Adafruit_BMP280 bmp;
Adafruit_Sensor *bmp_temp;
Adafruit_Sensor *bmp_pressure;
Adafruit_BME280 bme;
Adafruit_Sensor *bme_temp;
Adafruit_Sensor *bme_pressure;
Adafruit_Sensor *bme_humidity;
uptime_interval myUpTime(10);
////////////////////////////////////// Global vars ////////////////////////////////////////////////////////////////////
// Global vars
boolean just_load = true; boolean just_load = true;
const char *hostName = "IoT Manager"; const char *hostName = "IoT Manager";
@@ -77,13 +106,11 @@ boolean udp_data_parse = false;
boolean mqtt_send_settings_to_udp = false; boolean mqtt_send_settings_to_udp = false;
boolean i2c_scanning = false; boolean i2c_scanning = false;
// Servo
Servo myServo1;
Servo myServo2;
//Buttons //Buttons
boolean but[NUM_BUTTONS]; //boolean but[6];
Bounce *buttons = new Bounce[NUM_BUTTONS];
// Udp // Udp
boolean udp_busy = false; boolean udp_busy = false;
@@ -102,24 +129,6 @@ int udp_period;
// i2c // i2c
String i2c_list; String i2c_list;
OneWire *oneWire;
DallasTemperature sensors;
DHTesp dht;
#ifdef level_enable
GMedian<10, int> medianFilter;
#endif
#ifdef bmp_enable
Adafruit_BMP280 bmp;
Adafruit_Sensor *bmp_temp = bmp.getTemperatureSensor();
Adafruit_Sensor *bmp_pressure = bmp.getPressureSensor();
#endif
#ifdef bme_enable
Adafruit_BME280 bme;
Adafruit_Sensor *bme_temp = bme.getTemperatureSensor();
Adafruit_Sensor *bme_pressure = bme.getPressureSensor();
Adafruit_Sensor *bme_humidity = bme.getHumiditySensor();
#endif

View File

@@ -1,241 +1,103 @@
#include "Global.h" #include "Global.h"
void All_init() { void All_init() {
server.on("/init", HTTP_GET, [](AsyncWebServerRequest* request) { Device_init();
String value; Scenario_init();
if (request->hasArg("arg")) { Timer_countdown_init();
value = request->getParam("arg")->value();
}
if (value == "0") { //выкл сценариев
jsonWriteStr(configSetupJson, "scenario", value);
saveConfig();
Scenario_init();
request->send(200, "text/text", "OK");
}
if (value == "1") { //вкл сценариев
jsonWriteStr(configSetupJson, "scenario", value);
saveConfig();
Scenario_init();
request->send(200, "text/text", "OK");
}
if (value == "2") { //инициализация
Device_init();
request->send(200, "text/text", "OK");
}
if (value == "3") {
#ifdef logging_enable
clean_log_date();
#endif
request->send(200, "text/text", "OK");
}
if (value == "4") {
Scenario_init();
request->send(200, "text/text", "OK");
}
if (value == "5") {
i2c_scanning = true;
request->redirect("/?utilities");
}
});
prsets_init();
Device_init();
Scenario_init();
Timer_countdown_init();
} }
void Device_init() { void Device_init() {
logging_value_names_list = "";
enter_to_logging_counter = LOG1 - 1;
analog_value_names_list = ""; logging_value_names_list = "";
enter_to_analog_counter = 0; enter_to_logging_counter = LOG1 - 1;
levelPr_value_name = ""; analog_value_names_list = "";
enter_to_analog_counter = 0;
dhtT_value_name = ""; levelPr_value_name = "";
dhtH_value_name = ""; ultrasonicCm_value_name = "";
bmp280T_value_name = ""; dhtT_value_name = "";
bmp280P_value_name = ""; dhtH_value_name = "";
bme280T_value_name = ""; bmp280T_value_name = "";
bme280P_value_name = ""; bmp280P_value_name = "";
bme280H_value_name = "";
bme280A_value_name = "";
int array_sz = sizeof(sensors_reading_map) / sizeof(sensors_reading_map[0]); bme280T_value_name = "";
bme280P_value_name = "";
bme280H_value_name = "";
bme280A_value_name = "";
for (int i = 0; i < array_sz; i++) { int array_sz = sizeof(sensors_reading_map) / sizeof(sensors_reading_map[0]);
sensors_reading_map[i] = 0;
}
for (int i = LOG1; i <= LOG5; i++) { for (int i = 0; i < array_sz; i++) {
ts.remove(i); sensors_reading_map[i] = 0;
} }
for (int i = LOG1; i <= LOG5; i++) {
ts.remove(i);
}
#ifdef layout_in_ram #ifdef layout_in_ram
all_widgets = ""; all_widgets = "";
#else #else
SPIFFS.remove("/layout.txt"); SPIFFS.remove("/layout.txt");
#endif #endif
txtExecution("firmware.c.txt"); txtExecution("firmware.c.txt");
//outcoming_date(); //outcoming_date();
} }
//-------------------------------сценарии-----------------------------------------------------
void Scenario_init() { void Scenario_init() {
if (jsonReadStr(configSetupJson, "scenario") == "1") { if (jsonReadStr(configSetupJson, "scen") == "1") {
scenario = readFile("firmware.s.txt", 2048); scenario = readFile("firmware.s.txt", 2048);
} }
} }
void prsets_init() { void uptime_init() {
server.on("/preset", HTTP_GET, [](AsyncWebServerRequest* request) { ts.add(UPTIME, 5000, [&](void*) {
String value; handle_uptime();
if (request->hasArg("arg")) { }, nullptr, true);
value = request->getParam("arg")->value(); ts.add(STATISTICS, statistics_update, [&](void*) {
} handle_statistics();
if (value == "1") { }, nullptr, true);
writeFile("firmware.c.txt", readFile("configs/relay.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/relay.s.txt", 2048));
}
if (value == "2") {
writeFile("firmware.c.txt", readFile("configs/relay_t.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/relay_t.s.txt", 2048));
}
if (value == "3") {
writeFile("firmware.c.txt", readFile("configs/relay_c.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/relay_c.s.txt", 2048));
}
if (value == "4") {
writeFile("firmware.c.txt", readFile("configs/relay_s.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/relay_s.s.txt", 2048));
}
if (value == "5") {
writeFile("firmware.c.txt", readFile("configs/relay_sw.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/relay_sw.s.txt", 2048));
}
if (value == "6") {
writeFile("firmware.c.txt", readFile("configs/relay_br.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/relay_br.s.txt", 2048));
}
if (value == "7") {
writeFile("firmware.c.txt", readFile("configs/relay_sr.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/relay_sr.s.txt", 2048));
}
if (value == "8") {
writeFile("firmware.c.txt", readFile("configs/pwm.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/pwm.s.txt", 2048));
}
if (value == "9") {
writeFile("firmware.c.txt", readFile("configs/dht11.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/dht11.s.txt", 2048));
}
if (value == "10") {
writeFile("firmware.c.txt", readFile("configs/dht22.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/dht22.s.txt", 2048));
}
if (value == "11") {
writeFile("firmware.c.txt", readFile("configs/analog.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/analog.s.txt", 2048));
}
if (value == "12") {
writeFile("firmware.c.txt", readFile("configs/dallas.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/dallas.s.txt", 2048));
}
if (value == "13") {
writeFile("firmware.c.txt", readFile("configs/termostat.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/termostat.s.txt", 2048));
}
if (value == "14") {
writeFile("firmware.c.txt", readFile("configs/level.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/level.s.txt", 2048));
}
if (value == "15") {
writeFile("firmware.c.txt", readFile("configs/moution_r.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/moution_r.s.txt", 2048));
}
if (value == "16") {
writeFile("firmware.c.txt", readFile("configs/moution_s.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/moution_s.s.txt", 2048));
}
if (value == "17") {
writeFile("firmware.c.txt", readFile("configs/stepper.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/stepper.s.txt", 2048));
}
if (value == "18") {
writeFile("firmware.c.txt", readFile("configs/servo.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/servo.s.txt", 2048));
}
if (value == "19") {
writeFile("firmware.c.txt", readFile("configs/firmware.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/firmware.s.txt", 2048));
}
Device_init();
Scenario_init();
request->redirect("/?configuration");
});
} }
void up_time() { void handle_uptime() {
uint32_t ss = millis() / 1000; if (myUpTime.check()) {
uint32_t mm = ss / 60; jsonWriteStr(configSetupJson, "uptime", uptime_as_string());
uint32_t hh = mm / 60; }
uint32_t dd = hh / 24;
String out = "";
if (ss != 0) {
out = "[i] uptime = " + String(ss) + " sec";
jsonWriteStr(configLiveJson, "uptime", String(ss) + " sec");
}
if (mm != 0) {
out = "[i] uptime = " + String(mm) + " min";
jsonWriteStr(configLiveJson, "uptime", String(mm) + " min");
}
if (hh != 0) {
out = "[i] uptime = " + String(hh) + " hours";
jsonWriteStr(configLiveJson, "uptime", String(hh) + " hours");
}
if (dd != 0) {
out = "[i] uptime = " + String(dd) + " days";
jsonWriteStr(configLiveJson, "uptime", String(dd) + " days");
}
Serial.println(out + ", mqtt_lost_error: " + String(mqtt_lost_error) + ", wifi_lost_error: " + String(wifi_lost_error));
} }
void statistics() { void handle_statistics() {
if (WiFi.status() == WL_CONNECTED) { if (WiFi.status() == WL_CONNECTED) {
String urls = "http://backup.privet.lv/visitors/?"; String urls = "http://backup.privet.lv/visitors/?";
//----------------------------------------------------------------- //-----------------------------------------------------------------
urls += WiFi.macAddress().c_str(); urls += WiFi.macAddress().c_str();
urls += "&"; urls += "&";
//----------------------------------------------------------------- //-----------------------------------------------------------------
#ifdef ESP8266 #ifdef ESP8266
urls += "iot-manager_esp8266"; urls += "iot-manager_esp8266";
#endif #endif
#ifdef ESP32 #ifdef ESP32
urls += "iot-manager_esp32"; urls += "iot-manager_esp32";
#endif #endif
urls += "&"; urls += "&";
//-----------------------------------------------------------------
#ifdef ESP8266 #ifdef ESP8266
urls += ESP.getResetReason(); urls += ESP.getResetReason();
//Serial.println(ESP.getResetReason());
#endif #endif
#ifdef ESP32 #ifdef ESP32
urls += "Power on"; urls += "Power on";
#endif #endif
urls += "&"; urls += "&";
urls += "ver: "; //-----------------------------------------------------------------
urls += String(firmware_version); urls += "ver: ";
String stat = getURL(urls); urls += String(firmware_version);
} //-----------------------------------------------------------------
} String stat = getURL(urls);
//Serial.println(stat);
void statistics_init() { }
ts.add( }
STATISTICS, statistics_update, [&](void*) {
statistics();
},
nullptr, true);
}

View File

@@ -6,141 +6,125 @@ void sendLogData(String file, String topic);
//===============================================Логирование============================================================ //===============================================Логирование============================================================
//logging temp1 1 10 Температура Датчики 2 //logging temp1 1 10 Температура Датчики 2
void logging() { void logging() {
String value_name = sCmd.next(); String value_name = sCmd.next();
String period_min = sCmd.next(); String period_min = sCmd.next();
String maxCount = sCmd.next(); String maxCount = sCmd.next();
String widget_name = sCmd.next(); String widget_name = sCmd.next();
widget_name.replace("#", " "); widget_name.replace("#", " ");
String page_name = sCmd.next(); String page_name = sCmd.next();
String page_number = sCmd.next(); String page_number = sCmd.next();
logging_value_names_list += value_name + ","; logging_value_names_list += value_name + ",";
// считаем количество входов в эту функцию enter_to_logging_counter++; //считаем количество входов в эту функцию
enter_to_logging_counter++; jsonWriteStr(configOptionJson, value_name + "_c", maxCount); //создаем в файловой системе переменную количества точек на графике с отметкой _c что значит count
//создаем в файловой системе переменную количества точек на графике с отметкой _c что значит count createChart (widget_name, page_name, page_number, "widgets/widget.chart.json", value_name + "_ch", maxCount); //создаем график в приложении с топиком _ch /prefix/3234045-1589487/value_name_ch
jsonWriteStr(configOptionJson, value_name + "_c", maxCount); if (enter_to_logging_counter == LOG1) {
ts.add(LOG1, period_min.toInt() * 1000 * 60, [&](void*) {
//создаем график в приложении с топиком _ch /prefix/3234045-1589487/value_name_ch String tmp_buf_1 = selectFromMarkerToMarker(logging_value_names_list, ",", 0);
createChart(widget_name, page_name, page_number, "widgets/widget.chart.json", value_name + "_ch", maxCount); deleteOldDate("log." + tmp_buf_1 + ".txt", jsonReadInt(configOptionJson, tmp_buf_1 + "_c"), jsonReadStr(configLiveJson, tmp_buf_1));
if (enter_to_logging_counter == LOG1) { Serial.println("[i] LOGGING for sensor '" + tmp_buf_1 + "' done");
ts.add( }, nullptr, false);
LOG1, period_min.toInt() * 1000 * 60, [&](void*) { }
String tmp_buf_1 = selectFromMarkerToMarker(logging_value_names_list, ",", 0); if (enter_to_logging_counter == LOG2) {
deleteOldDate("log." + tmp_buf_1 + ".txt", jsonReadInt(configOptionJson, tmp_buf_1 + "_c"), jsonReadStr(configLiveJson, tmp_buf_1)); ts.add(LOG2, period_min.toInt() * 1000 * 60, [&](void*) {
Serial.println("[i] LOGGING for sensor '" + tmp_buf_1 + "' done"); String tmp_buf_2 = selectFromMarkerToMarker(logging_value_names_list, ",", 1);
}, deleteOldDate("log." + tmp_buf_2 + ".txt", jsonReadInt(configOptionJson, tmp_buf_2 + "_c"), jsonReadStr(configLiveJson, tmp_buf_2));
nullptr, false); Serial.println("[i] LOGGING for sensor '" + tmp_buf_2 + "' done");
} }, nullptr, false);
if (enter_to_logging_counter == LOG2) { }
ts.add( if (enter_to_logging_counter == LOG3) {
LOG2, period_min.toInt() * 1000 * 60, [&](void*) { ts.add(LOG3, period_min.toInt() * 1000 * 60, [&](void*) {
String tmp_buf_2 = selectFromMarkerToMarker(logging_value_names_list, ",", 1); String tmp_buf_3 = selectFromMarkerToMarker(logging_value_names_list, ",", 2);
deleteOldDate("log." + tmp_buf_2 + ".txt", jsonReadInt(configOptionJson, tmp_buf_2 + "_c"), jsonReadStr(configLiveJson, tmp_buf_2)); deleteOldDate("log." + tmp_buf_3 + ".txt", jsonReadInt(configOptionJson, tmp_buf_3 + "_c"), jsonReadStr(configLiveJson, tmp_buf_3));
Serial.println("[i] LOGGING for sensor '" + tmp_buf_2 + "' done"); Serial.println("[i] LOGGING for sensor '" + tmp_buf_3 + "' done");
}, }, nullptr, false);
nullptr, false); }
} if (enter_to_logging_counter == LOG4) {
if (enter_to_logging_counter == LOG3) { ts.add(LOG4, period_min.toInt() * 1000 * 60, [&](void*) {
ts.add( String tmp_buf_4 = selectFromMarkerToMarker(logging_value_names_list, ",", 3);
LOG3, period_min.toInt() * 1000 * 60, [&](void*) { deleteOldDate("log." + tmp_buf_4 + ".txt", jsonReadInt(configOptionJson, tmp_buf_4 + "_c"), jsonReadStr(configLiveJson, tmp_buf_4));
String tmp_buf_3 = selectFromMarkerToMarker(logging_value_names_list, ",", 2); Serial.println("[i] LOGGING for sensor '" + tmp_buf_4 + "' done");
deleteOldDate("log." + tmp_buf_3 + ".txt", jsonReadInt(configOptionJson, tmp_buf_3 + "_c"), jsonReadStr(configLiveJson, tmp_buf_3)); }, nullptr, false);
Serial.println("[i] LOGGING for sensor '" + tmp_buf_3 + "' done"); }
}, if (enter_to_logging_counter == LOG5) {
nullptr, false); ts.add(LOG5, period_min.toInt() * 1000 * 60, [&](void*) {
} String tmp_buf_5 = selectFromMarkerToMarker(logging_value_names_list, ",", 4);
if (enter_to_logging_counter == LOG4) { deleteOldDate("log." + tmp_buf_5 + ".txt", jsonReadInt(configOptionJson, tmp_buf_5 + "_c"), jsonReadStr(configLiveJson, tmp_buf_5));
ts.add( Serial.println("[i] LOGGING for sensor '" + tmp_buf_5 + "' done");
LOG4, period_min.toInt() * 1000 * 60, [&](void*) { }, nullptr, false);
String tmp_buf_4 = selectFromMarkerToMarker(logging_value_names_list, ",", 3); }
deleteOldDate("log." + tmp_buf_4 + ".txt", jsonReadInt(configOptionJson, tmp_buf_4 + "_c"), jsonReadStr(configLiveJson, tmp_buf_4));
Serial.println("[i] LOGGING for sensor '" + tmp_buf_4 + "' done");
},
nullptr, false);
}
if (enter_to_logging_counter == LOG5) {
ts.add(
LOG5, period_min.toInt() * 1000 * 60, [&](void*) {
String tmp_buf_5 = selectFromMarkerToMarker(logging_value_names_list, ",", 4);
deleteOldDate("log." + tmp_buf_5 + ".txt", jsonReadInt(configOptionJson, tmp_buf_5 + "_c"), jsonReadStr(configLiveJson, tmp_buf_5));
Serial.println("[i] LOGGING for sensor '" + tmp_buf_5 + "' done");
},
nullptr, false);
}
} }
//=========================================Удаление стрых данных и запись новых================================================================== //=========================================Удаление стрых данных и запись новых==================================================================
void deleteOldDate(String file, int seted_number_of_lines, String date_to_add) { void deleteOldDate(String file, int seted_number_of_lines, String date_to_add) {
String log_date = readFile(file, 5000); String log_date = readFile(file, 5000);
int current_number_of_lines = count(log_date, "\r\n"); int current_number_of_lines = count(log_date, "\r\n");
Serial.println("=====> [i] in log file " + file + " " + current_number_of_lines + " lines"); Serial.println("=====> [i] in log file " + file + " " + current_number_of_lines + " lines");
if (current_number_of_lines > seted_number_of_lines + 1) { if (current_number_of_lines > seted_number_of_lines + 1) {
SPIFFS.remove("/" + file); SPIFFS.remove("/" + file);
current_number_of_lines = 0; current_number_of_lines = 0;
}
if (current_number_of_lines == 0) {
SPIFFS.remove("/" + file);
current_number_of_lines = 0;
}
if (current_number_of_lines > seted_number_of_lines) {
log_date = deleteBeforeDelimiter(log_date, "\r\n");
if (GetTimeUnix() != "failed") {
log_date += GetTimeUnix() + " " + date_to_add + "\r\n";
writeFile(file, log_date);
} }
if (current_number_of_lines == 0) { } else {
SPIFFS.remove("/" + file); if (GetTimeUnix() != "failed") {
current_number_of_lines = 0; addFile(file, GetTimeUnix() + " " + date_to_add);
} }
if (current_number_of_lines > seted_number_of_lines) { }
log_date = deleteBeforeDelimiter(log_date, "\r\n"); log_date = "";
if (GetTimeUnix() != "failed") {
log_date += GetTimeUnix() + " " + date_to_add + "\r\n";
writeFile(file, log_date);
}
} else {
if (GetTimeUnix() != "failed") {
addFile(file, GetTimeUnix() + " " + date_to_add);
}
}
log_date = "";
} }
//=========================================Выбор какие данные отправлять================================================================== //=========================================Выбор какие данные отправлять==================================================================
void choose_log_date_and_send() { void choose_log_date_and_send() {
String all_line = logging_value_names_list; String all_line = logging_value_names_list;
while (all_line.length() != 0) { while (all_line.length() != 0) {
String tmp = selectToMarker(all_line, ","); String tmp = selectToMarker (all_line, ",");
sendLogData("log." + tmp + ".txt", tmp + "_ch" sendLogData("log." + tmp + ".txt", tmp + "_ch");
); all_line = deleteBeforeDelimiter(all_line, ",");
all_line = deleteBeforeDelimiter(all_line, ","); }
} all_line = "";
all_line = "";
} }
//=========================================Отправка данных=================================================================================== //=========================================Отправка данных===================================================================================
void sendLogData(String file, String topic) { void sendLogData(String file, String topic) {
String log_date = readFile(file, 5000); String log_date = readFile(file, 5000);
if (log_date != "Failed") { if (log_date != "Failed") {
log_date.replace("\r\n", "\n"); log_date.replace("\r\n", "\n");
log_date.replace("\r", "\n"); log_date.replace("\r", "\n");
String buf = "{}"; String buf = "{}";
String json_array; String json_array;
String unix_time; String unix_time;
String value; String value;
while (log_date.length() != 0) { while (log_date.length() != 0) {
String tmp = selectToMarker(log_date, "\n"); String tmp = selectToMarker (log_date, "\n");
log_date = deleteBeforeDelimiter(log_date, "\n"); log_date = deleteBeforeDelimiter(log_date, "\n");
unix_time = selectToMarker(tmp, " "); unix_time = selectToMarker (tmp, " ");
jsonWriteInt(buf, "x", unix_time.toInt()); jsonWriteInt(buf, "x", unix_time.toInt());
value = deleteBeforeDelimiter(tmp, " "); value = deleteBeforeDelimiter(tmp, " ");
jsonWriteFloat(buf, "y1", value.toFloat()); jsonWriteFloat(buf, "y1", value.toFloat());
if (log_date.length() < 3) { if (log_date.length() < 3) {
json_array += buf; json_array += buf;
} else { } else {
json_array += buf + ","; json_array += buf + ",";
} }
buf = "{}"; buf = "{}";
}
unix_time = "";
value = "";
log_date = "";
json_array = "{\"status\":[" + json_array + "]}";
Serial.println(json_array);
sendCHART(topic, json_array);
json_array = "";
getMemoryLoad("[i] after send log date");
} }
unix_time = "";
value = "";
log_date = "";
json_array = "{\"status\":[" + json_array + "]}";
Serial.println(json_array);
sendCHART(topic, json_array);
json_array = "";
getMemoryLoad("[i] after send log date");
}
} }
/* /*
@@ -162,12 +146,12 @@ void sendLogData(String file, String topic) {
*/ */
//=========================================Очистка данных=================================================================================== //=========================================Очистка данных===================================================================================
void clean_log_date() { void clean_log_date() {
String all_line = logging_value_names_list; String all_line = logging_value_names_list;
while (all_line.length() != 0) { while (all_line.length() != 0) {
String tmp = selectToMarker(all_line, ","); String tmp = selectToMarker (all_line, ",");
SPIFFS.remove("/log." + tmp + ".txt"); SPIFFS.remove("/log." + tmp + ".txt");
all_line = deleteBeforeDelimiter(all_line, ","); all_line = deleteBeforeDelimiter(all_line, ",");
} }
all_line = ""; all_line = "";
} }
#endif #endif

View File

@@ -1,6 +1,7 @@
#include "Global.h" #include "Global.h"
void callback(char* topic, byte* payload, unsigned int length); void callback(char* topic, byte* payload, unsigned int length);
String stateMQTT(); String stateMQTT();
void sendAllData(); void sendAllData();
void sendAllWigets(); void sendAllWigets();
@@ -9,74 +10,41 @@ void outcoming_date();
//===============================================ИНИЦИАЛИЗАЦИЯ================================================ //===============================================ИНИЦИАЛИЗАЦИЯ================================================
void MQTT_init() { void MQTT_init() {
ts.add( ts.add(WIFI_MQTT_CONNECTION_CHECK, wifi_mqtt_reconnecting, [&](void*) {
WIFI_MQTT_CONNECTION_CHECK, wifi_mqtt_reconnecting, [&](void*) { if (WiFi.status() == WL_CONNECTED) {
up_time(); Serial.println("[VV] WiFi-ok");
if (WiFi.status() == WL_CONNECTED) { if (client_mqtt.connected()) {
Serial.println("[VV] WiFi-ok"); Serial.println("[VV] MQTT-ok");
if (client_mqtt.connected()) { led_blink("off");
Serial.println("[VV] MQTT-ok"); } else {
led_blink("off"); MQTT_Connecting();
} else { if (!just_load) mqtt_lost_error++;
MQTT_Connecting(); }
if (!just_load) mqtt_lost_error++; } else {
} Serial.println("[E] Lost WiFi connection");
} else { wifi_lost_error++;
Serial.println("[E] Lost WiFi connection"); ts.remove(WIFI_MQTT_CONNECTION_CHECK);
wifi_lost_error++; StartAPMode();
ts.remove(WIFI_MQTT_CONNECTION_CHECK); }
StartAPMode(); }, nullptr, true);
}
},
nullptr, true);
server.on("/mqttSave", HTTP_GET, [](AsyncWebServerRequest* request) {
if (request->hasArg("mqttServer")) {
jsonWriteStr(configSetupJson, "mqttServer", request->getParam("mqttServer")->value());
}
if (request->hasArg("mqttPort")) {
int port = (request->getParam("mqttPort")->value()).toInt();
jsonWriteInt(configSetupJson, "mqttPort", port);
}
if (request->hasArg("mqttPrefix")) {
jsonWriteStr(configSetupJson, "mqttPrefix", request->getParam("mqttPrefix")->value());
}
if (request->hasArg("mqttUser")) {
jsonWriteStr(configSetupJson, "mqttUser", request->getParam("mqttUser")->value());
}
if (request->hasArg("mqttPass")) {
jsonWriteStr(configSetupJson, "mqttPass", request->getParam("mqttPass")->value());
}
saveConfig();
mqtt_connection = true;
request->send(200, "text/text", "ok");
});
server.on("/mqttCheck", HTTP_GET, [](AsyncWebServerRequest* request) {
String tmp = "{}";
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + stateMQTT());
jsonWriteStr(tmp, "class", "pop-up");
request->send(200, "text/text", tmp);
});
} }
void do_mqtt_connection() { void do_mqtt_connection() {
if (mqtt_connection) { if (mqtt_connection) {
mqtt_connection = false; mqtt_connection = false;
client_mqtt.disconnect(); client_mqtt.disconnect();
MQTT_Connecting(); MQTT_Connecting();
} }
} }
void handleMQTT() { //================================================ОБНОВЛЕНИЕ====================================================
if (WiFi.status() == WL_CONNECTED) { void handleMQTT() {
if (client_mqtt.connected()) { if (WiFi.status() == WL_CONNECTED) {
client_mqtt.loop(); if (client_mqtt.connected()) {
} client_mqtt.loop();
} }
}
} }
boolean MQTT_Connecting() { boolean MQTT_Connecting() {
bool res = false; bool res = false;
String mqtt_server = jsonReadStr(configSetupJson, "mqttServer"); String mqtt_server = jsonReadStr(configSetupJson, "mqttServer");
@@ -94,6 +62,9 @@ boolean MQTT_Connecting() {
client_mqtt.subscribe(jsonReadStr(configSetupJson, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи client_mqtt.subscribe(jsonReadStr(configSetupJson, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/update").c_str());
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/devc").c_str());
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/devs").c_str());
Serial.println("[V] Callback set, subscribe done"); Serial.println("[V] Callback set, subscribe done");
res = true; res = true;
} else { } else {
@@ -108,145 +79,168 @@ boolean MQTT_Connecting() {
return res; return res;
} }
//=====================================================ВХОДЯЩИЕ ДАННЫЕ======================================================== //=====================================================ВХОДЯЩИЕ ДАННЫЕ========================================================
void callback(char* topic, byte* payload, unsigned int length) { void callback(char* topic, byte * payload, unsigned int length) {
Serial.print("[MQTT] "); Serial.print("[MQTT] ");
Serial.print(topic); Serial.print(topic);
String topic_str = String(topic); String topic_str = String(topic);
String str; String str;
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
str += (char)payload[i]; str += (char)payload[i];
} }
Serial.println(" => " + str); Serial.println(" => " + str);
if (str == "HELLO") outcoming_date(); if (str == "HELLO") outcoming_date();
//превращает название топика в команду, а значение в параметр команды //превращает название топика в команду, а значение в параметр команды
if (topic_str.indexOf("control") > 0) { //IoTmanager/800324-1458415/button-sw2/control 1 //IoTmanager/800324-1458415/button99/control 1 if (topic_str.indexOf("control") > 0) { //IoTmanager/800324-1458415/button-sw2/control 1 //IoTmanager/800324-1458415/button99/control 1
String topic = selectFromMarkerToMarker(topic_str, "/", 3); //button1 //button99 String topic = selectFromMarkerToMarker(topic_str, "/", 3); //button1 //button99
topic = add_set(topic); //buttonSet1 //buttonSet99 topic = add_set(topic); //buttonSet1 //buttonSet99
String number = selectToMarkerLast(topic, "Set"); //1 //99 String number = selectToMarkerLast(topic, "Set"); //1 //99
topic.replace(number, ""); //buttonSet //buttonSet topic.replace(number, ""); //buttonSet //buttonSet
String final_line = topic + " " + number + " " + str; //buttonSet 1 1 //buttonSet 99 1 String final_line = topic + " " + number + " " + str; //buttonSet 1 1 //buttonSet 99 1
order_loop += final_line + ","; order_loop += final_line + ",";
} }
if (topic_str.indexOf("order") > 0) { if (topic_str.indexOf("order") > 0) {
str.replace("_", " "); str.replace("_", " ");
//Serial.println(str); //Serial.println(str);
order_loop += str + ","; order_loop += str + ",";
} }
if (topic_str.indexOf("update") > 0) { if (topic_str.indexOf("update") > 0) {
if (str == "1") { if (str == "1") {
upgrade = true; upgrade = true;
}
} }
}
if (topic_str.indexOf("devc") > 0) {
writeFile("firmware.c.txt", str);
Device_init();
}
if (topic_str.indexOf("devs") > 0) {
writeFile("firmware.s.txt", str);
Scenario_init();
}
} }
//данные которые отправляем при подключении или отбновлении страницы //данные которые отправляем при подключении или отбновлении страницы
void outcoming_date() { void outcoming_date() {
sendAllWigets();
sendAllData(); sendAllWigets();
sendAllData();
#ifdef logging_enable #ifdef logging_enable
choose_log_date_and_send(); choose_log_date_and_send();
#endif #endif
Serial.println("[V] Sending all date to iot manager completed"); Serial.println("[V] Sending all date to iot manager completed");
} }
//======================================CONFIG==================================================
boolean sendMQTT(String end_of_topik, String data) { boolean sendMQTT(String end_of_topik, String data) {
String topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + end_of_topik; String topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + end_of_topik;
boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false); boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false);
client_mqtt.print(data); client_mqtt.print(data);
client_mqtt.endPublish(); client_mqtt.endPublish();
return send_status; return send_status;
} }
boolean sendCHART(String topik, String data) { boolean sendCHART(String topik, String data) {
topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status"; topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false); boolean send_status = client_mqtt.beginPublish(topik.c_str(), data.length(), false);
client_mqtt.print(data); client_mqtt.print(data);
client_mqtt.endPublish(); client_mqtt.endPublish();
return send_status; return send_status;
} }
boolean sendCHART_test(String topik, String data) {
topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
boolean send_status = client_mqtt.publish (topik.c_str(), data.c_str(), false);
return send_status;
}
//======================================STATUS==================================================
void sendSTATUS(String topik, String state) { void sendSTATUS(String topik, String state) {
topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status"; topik = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
String json_ = "{}"; String json_ = "{}";
jsonWriteStr(json_, "status", state); jsonWriteStr(json_, "status", state);
client_mqtt.publish(topik.c_str(), json_.c_str(), false); int send_status = client_mqtt.publish (topik.c_str(), json_.c_str(), false);
} }
//======================================CONTROL==================================================
void sendCONTROL(String id, String topik, String state) { void sendCONTROL(String id, String topik, String state) {
String all_line = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id + "/" + topik + "/control"; String all_line = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id + "/" + topik + "/control";
client_mqtt.publish(all_line.c_str(), state.c_str(), false); int send_status = client_mqtt.publish (all_line.c_str(), state.c_str(), false);
} }
//=====================================================ОТПРАВЛЯЕМ ВИДЖЕТЫ======================================================== //=====================================================ОТПРАВЛЯЕМ ВИДЖЕТЫ========================================================
#ifdef layout_in_ram #ifdef layout_in_ram
void sendAllWigets() { void sendAllWigets() {
if (all_widgets != "") { if (all_widgets != "") {
int counter = 0; int counter = 0;
String line; String line;
int psn_1 = 0; int psn_1 = 0;
int psn_2; int psn_2;
do { do {
psn_2 = all_widgets.indexOf("\r\n", psn_1); //\r\n psn_2 = all_widgets.indexOf("\r\n", psn_1); //\r\n
line = all_widgets.substring(psn_1, psn_2); line = all_widgets.substring(psn_1, psn_2);
line.replace("\n", ""); line.replace("\n", "");
line.replace("\r\n", ""); line.replace("\r\n", "");
//jsonWriteStr(line, "id", String(counter)); //jsonWriteStr(line, "id", String(counter));
//jsonWriteStr(line, "pageId", String(counter)); //jsonWriteStr(line, "pageId", String(counter));
counter++; counter++;
sendMQTT("config", line); sendMQTT("config", line);
Serial.println("[V] " + line); Serial.println("[V] " + line);
psn_1 = psn_2 + 1; psn_1 = psn_2 + 1;
} while (psn_2 + 2 < all_widgets.length()); } while (psn_2 + 2 < all_widgets.length());
getMemoryLoad("[i] after send all widgets"); getMemoryLoad("[i] after send all widgets");
} }
} }
#endif #endif
#ifndef layout_in_ram #ifndef layout_in_ram
void sendAllWigets() { void sendAllWigets() {
File configFile = SPIFFS.open("/layout.txt", "r"); File configFile = SPIFFS.open("/layout.txt", "r");
if (!configFile) { if (!configFile) {
return; return;
} }
configFile.seek(0, SeekSet); //поставим курсор в начало файла configFile.seek(0, SeekSet); //поставим курсор в начало файла
while (configFile.position() != configFile.size()) { while (configFile.position() != configFile.size()) {
String widget_to_send = configFile.readStringUntil('\n'); String widget_to_send = configFile.readStringUntil('\n');
Serial.println("[V] " + widget_to_send); Serial.println("[V] " + widget_to_send);
sendMQTT("config", widget_to_send); sendMQTT("config", widget_to_send);
} }
} }
#endif #endif
//=====================================================ОТПРАВЛЯЕМ ДАННЫЕ В ВИДЖЕТЫ ПРИ ОБНОВЛЕНИИ СТРАНИЦЫ======================================================== //=====================================================ОТПРАВЛЯЕМ ДАННЫЕ В ВИДЖЕТЫ ПРИ ОБНОВЛЕНИИ СТРАНИЦЫ========================================================
void sendAllData() { //берет строку json и ключи превращает в топики а значения колючей в них посылает void sendAllData() { //берет строку json и ключи превращает в топики а значения колючей в них посылает
String current_config = configLiveJson; //{"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"} String current_config = configLiveJson; //{"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"}
getMemoryLoad("[i] after send all date"); getMemoryLoad("[i] after send all date");
current_config.replace("{", ""); current_config.replace("{", "");
current_config.replace("}", ""); //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1" current_config.replace("}", ""); //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"
current_config += ","; //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1", current_config += ","; //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1",
while (current_config.length() != 0) { while (current_config.length() != 0) {
String tmp = selectToMarker(current_config, ",");
String topic = selectToMarker(tmp, ":"); String tmp = selectToMarker (current_config, ",");
topic.replace("\"", ""); String topic = selectToMarker (tmp, ":");
String state = selectToMarkerLast(tmp, ":"); topic.replace("\"", "");
state.replace("\"", ""); String state = selectToMarkerLast (tmp, ":");
if (topic != "name" && topic != "lang" && topic != "ip" && topic.indexOf("_in") < 0) { state.replace("\"", "");
sendSTATUS(topic, state); if (topic != "name" && topic != "lang" && topic != "ip" && topic.indexOf("_in") < 0) {
//Serial.println("-->" + topic + " " + state); sendSTATUS(topic, state);
} //Serial.println("-->" + topic + " " + state);
current_config = deleteBeforeDelimiter(current_config, ",");
} }
current_config = deleteBeforeDelimiter(current_config, ",");
}
} }
String stateMQTT() { String stateMQTT() {
int state = client_mqtt.state(); int state = client_mqtt.state();
switch (state) { switch (state) {
@@ -285,69 +279,3 @@ String stateMQTT() {
break; break;
} }
} }
/*void scenario_devices_topiks_subscribe() {
//SCENARIO ANALOG > 5 800324-1458415 rel1 0
if (jsonReadStr(configSetupJson, "scenario") == "1") {
//String all_text = readFile("firmware.s.txt", 1024) + "\r\n";
String all_text = scenario + "\r\n";
all_text.replace("\r\n", "\n");
all_text.replace("\r", "\n");
while (all_text.length() != 0) {
String line_ = selectToMarker (all_text, "\n");
String id = selectFromMarkerToMarker(line_, " ", 4);
if (id != "not found") {
client_mqtt.subscribe((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id + "/+/status").c_str(), 0);
Serial.println("subscribed to device, id: " + id);
}
all_text = deleteBeforeDelimiter(all_text, "\n");
}
}
}
*/
/*void scenario_devices_test_msg_send() {
if (jsonReadStr(configSetupJson, "scenario") == "1") {
String all_text = scenario + "\r\n";
all_text.replace("\r\n", "\n");
all_text.replace("\r", "\n");
while (all_text.length() != 0) {
String line_ = selectToMarker (all_text, "\n");
String id = selectFromMarkerToMarker(line_, " ", 4);
if (id != "not found") {
//Serial.println();
Serial.println(client_mqtt.publish ((jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id).c_str(), "CHECK", true));
}
all_text = deleteBeforeDelimiter(all_text, "\n");
}
}
}*/
/*
//-----------------------------------------------------------------------------------------------------------------------------------------------
//jsonWriteStr(tmp, "status", "1");
String current_config = configLiveJson; //{"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"}
current_config.replace("{", "");
current_config.replace("}", ""); //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1"
current_config += ","; //"name":"MODULES","lang":"","ip":"192.168.43.60","DS":"34.00","rel1":"1","rel2":"1",
while (current_config.length() != 0) {
String tmp = selectToMarker (current_config, ","); //"rel1":"1"
String topic = selectToMarker (tmp, ":"); //"rel1"
topic.replace("\"", ""); //rel1
Serial.println(topic);
String state = selectToMarkerLast (tmp, ":"); //"1"
state.replace("\"", ""); //1
//if (widget.lastIndexOf(topic) > 0) {
jsonWriteStr(tmp, "status", state);
//}
current_config = deleteBeforeDelimiter(current_config, ",");
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
*/

View File

@@ -1,95 +1,96 @@
#include "Global.h" #include "Global.h"
void handleScenario() { void handleScenario() {
if (jsonReadStr(configSetupJson, "scenario") == "1") {
if ((jsonReadStr(configOptionJson, "scenario_status") != "")) {
int i = 0;
String str = scenario; //читаем переменную с сценариями (то что из файла на странице)
str += "\n";
str.replace("\r\n", "\n");
str.replace("\r", "\n");
while (str.length() != 0) {
//-----------------------------------------------------------------------------------------------------------------------
String tmp = selectToMarker(str, "end"); //выделяем первый сценарий из файла вместе с командами
if (tmp == "") return;
i++;
if (scenario_line_status[i] == 1) { if (jsonReadStr(configSetupJson, "scen") == "1") {
//Serial.println(i); if ((jsonReadStr(configOptionJson, "scenario_status") != "")) {
String condition = selectToMarker(tmp, "\n"); //выделяем первую строку самого сценария button1 = 1 (условие) int i = 0;
String param_name = selectFromMarkerToMarker(condition, " ", 0); String str = scenario; //читаем переменную с сценариями (то что из файла на странице)
String order = jsonReadStr(configOptionJson, "scenario_status"); //читаем весь файл событий str += "\n";
String param = selectToMarker(order, ","); //читаем первое событие из файла событий str.replace("\r\n", "\n");
if (param_name == param) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку str.replace("\r", "\n");
while (str.length() != 0) {
//-----------------------------------------------------------------------------------------------------------------------
String tmp = selectToMarker (str, "end"); //выделяем первый сценарий из файла вместе с командами
if (tmp == "") return;
i++;
String sign = selectFromMarkerToMarker(condition, " ", 1); //читаем знак (=) if (scenario_line_status[i] == 1) {
String value = selectFromMarkerToMarker(condition, " ", 2); //читаем значение (1) //Serial.println(i);
if (value.indexOf("digit") != -1) { String condition = selectToMarker (tmp, "\n"); //выделяем первую строку самого сценария button1 = 1 (условие)
// value = add_set(value); String param_name = selectFromMarkerToMarker(condition, " " , 0);
value = jsonReadStr(configLiveJson, value); String order = jsonReadStr(configOptionJson, "scenario_status"); //читаем весь файл событий
} String param = selectToMarker (order, ","); //читаем первое событие из файла событий
if (value.indexOf("time") != -1) { if (param_name == param) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку
// value = add_set(value);
value = jsonReadStr(configLiveJson, value);
}
boolean flag = false; //если одно из значений совпало то только тогда начинаем выполнять комнады
if (sign == "=") {
if (jsonReadStr(configLiveJson, param_name) == value) flag = true;
}
if (sign == "!=") {
if (jsonReadStr(configLiveJson, param_name) != value) flag = true;
}
if (sign == "<") {
if (jsonReadStr(configLiveJson, param_name).toInt() < value.toInt()) flag = true;
}
if (sign == ">") {
if (jsonReadStr(configLiveJson, param_name).toInt() > value.toInt()) flag = true;
}
if (sign == ">=") {
if (jsonReadStr(configLiveJson, param_name).toInt() >= value.toInt()) flag = true;
}
if (sign == "<=") {
if (jsonReadStr(configLiveJson, param_name).toInt() <= value.toInt()) flag = true;
}
if (flag) { String sign = selectFromMarkerToMarker(condition, " " , 1); //читаем знак (=)
//удаляем строку самого сценария оставляя только команды String value = selectFromMarkerToMarker(condition, " " , 2); //читаем значение (1)
tmp = deleteBeforeDelimiter(tmp, "\n"); if (value.indexOf("digit") != -1) {
//выполняем все команды // value = add_set(value);
stringExecution(tmp); value = jsonReadStr(configLiveJson, value);
Serial.println("[SCENARIO] '" + condition + "'");
}
}
}
str = deleteBeforeDelimiter(str, "end\n"); //удаляем первый сценарий
//-----------------------------------------------------------------------------------------------------------------------
} }
String tmp2 = jsonReadStr(configOptionJson, "scenario_status"); //читаем файл событий if (value.indexOf("time") != -1) {
tmp2 = deleteBeforeDelimiter(tmp2, ","); //удаляем выполненное событие // value = add_set(value);
jsonWriteStr(configOptionJson, "scenario_status", tmp2); //записываем обновленный файл событий value = jsonReadStr(configLiveJson, value);
i = 0; }
boolean flag = false; //если одно из значений совпало то только тогда начинаем выполнять комнады
if (sign == "=") {
if (jsonReadStr(configLiveJson, param_name) == value) flag = true;
}
if (sign == "!=") {
if (jsonReadStr(configLiveJson, param_name) != value) flag = true;
}
if (sign == "<") {
if (jsonReadStr(configLiveJson, param_name).toInt() < value.toInt()) flag = true;
}
if (sign == ">") {
if (jsonReadStr(configLiveJson, param_name).toInt() > value.toInt()) flag = true;
}
if (sign == ">=") {
if (jsonReadStr(configLiveJson, param_name).toInt() >= value.toInt()) flag = true;
}
if (sign == "<=") {
if (jsonReadStr(configLiveJson, param_name).toInt() <= value.toInt()) flag = true;
}
if (flag) {
tmp = deleteBeforeDelimiter(tmp, "\n"); //удаляем строку самого сценария оставляя только команды
stringExecution(tmp); //выполняем все команды
Serial.println("[SCENARIO] '" + condition + "'");
//Serial.println(" " + tmp);
}
}
} }
str = deleteBeforeDelimiter(str, "end\n"); //удаляем первый сценарий
//-----------------------------------------------------------------------------------------------------------------------
}
String tmp2 = jsonReadStr(configOptionJson, "scenario_status"); //читаем файл событий
tmp2 = deleteBeforeDelimiter(tmp2, ","); //удаляем выполненное событие
jsonWriteStr(configOptionJson, "scenario_status", tmp2); //записываем обновленный файл событий
i = 0;
} }
}
} }
//событие выглядит как имя плюс set плюс номер: button+Set+1 void eventGen (String event_name, String number) { //событие выглядит как имя плюс set плюс номер: button+Set+1
void eventGen(String event_name, String number) {
if (jsonReadStr(configSetupJson, "scenario") == "1") { if (jsonReadStr(configSetupJson, "scen") == "1") {
String tmp = jsonReadStr(configOptionJson, "scenario_status"); //генерирование события String tmp = jsonReadStr(configOptionJson, "scenario_status") ; //генерирование события
//Serial.println(event_name); //Serial.println(event_name);
jsonWriteStr(configOptionJson, "scenario_status", tmp + event_name + number + ","); jsonWriteStr(configOptionJson, "scenario_status", tmp + event_name + number + ",");
} }
} }
String add_set(String param_name) { String add_set(String param_name) {
String num1 = param_name.substring(param_name.length() - 1); String num1 = param_name.substring(param_name.length() - 1);
String num2 = param_name.substring(param_name.length() - 2, param_name.length() - 1); String num2 = param_name.substring(param_name.length() - 2, param_name.length() - 1);
if (isDigitStr(num1) && isDigitStr(num2)) { if (isDigitStr(num1) && isDigitStr(num2)) {
param_name = param_name.substring(0, param_name.length() - 2) + "Set" + num2 + num1; param_name = param_name.substring(0, param_name.length() - 2) + "Set" + num2 + num1;
} else { } else {
if (isDigitStr(num1)) { if (isDigitStr(num1)) {
param_name = param_name.substring(0, param_name.length() - 1) + "Set" + num1; param_name = param_name.substring(0, param_name.length() - 1) + "Set" + num1;
}
} }
return param_name; }
} return param_name;
}

View File

@@ -1,146 +1,133 @@
#include "Global.h" #include "Global.h"
void Time_Init() { void Time_Init() {
server.on("/time", HTTP_GET, [](AsyncWebServerRequest* request) { ts.add(TIME_SYNC, 30000, [&](void*) {
if (request->hasArg("timezone")) { time_check();
jsonWriteStr(configSetupJson, "timezone", request->getParam("timezone")->value()); }, nullptr, true);
}
if (request->hasArg("ntp")) {
jsonWriteStr(configSetupJson, "ntp", request->getParam("ntp")->value());
}
saveConfig();
reconfigTime();
request->send(200, "text/text", "OK");
});
ts.add(
TIME_SYNC, 30000, [&](void*) {
time_check();
},
nullptr, true);
} }
void time_check() { void time_check() {
if (GetTimeUnix() == "failed") { if (GetTimeUnix() == "failed") {
Serial.println("[i] Time is not synchronized, start synchronization"); Serial.println("[i] Time is not synchronized, start synchronization");
reconfigTime(); reconfigTime();
} }
} }
void reconfigTime() { void reconfigTime() {
if (WiFi.status() == WL_CONNECTED) { if (WiFi.status() == WL_CONNECTED) {
String ntp = jsonReadStr(configSetupJson, "ntp"); String ntp = jsonReadStr(configSetupJson, "ntp");
configTime(0, 0, ntp.c_str()); configTime(0, 0, ntp.c_str());
int i = 0; int i = 0;
Serial.println("[i] Awaiting for time "); Serial.println("[i] Awaiting for time ");
#ifdef ESP32 #ifdef ESP32
struct tm timeinfo; struct tm timeinfo;
while (!getLocalTime(&timeinfo) && i <= 4) { while (!getLocalTime(&timeinfo) && i <= 4) {
Serial.print("."); Serial.print(".");
i++; i++;
delay(1000); delay(1000);
} }
#endif #endif
#ifdef ESP8266 #ifdef ESP8266
//while (!time(nullptr) && i < 4) { //while (!time(nullptr) && i < 4) {
// Serial.print("."); // Serial.print(".");
// i++; // i++;
delay(2000); delay(2000);
//} //}
#endif #endif
if (GetTimeUnix() != "failed") { if (GetTimeUnix() != "failed") {
Serial.print("[V] Time synchronized = "); Serial.print("[V] Time synchronized = ");
Serial.print(GetDataDigital()); Serial.print(GetDataDigital());
Serial.print(" "); Serial.print(" ");
Serial.println(GetTime()); Serial.println(GetTime());
} else {
Serial.println("[E] Time server or internet connection error, will try again in 30 sec");
}
} else { } else {
Serial.println("[E] Get time impossible, no wifi connection"); Serial.println("[E] Time server or internet connection error, will try again in 30 sec");
} }
} else {
Serial.println("[E] Get time impossible, no wifi connection");
}
} }
//Получаем время в формате linux gmt //Получаем время в формате linux gmt
String GetTimeUnix() { String GetTimeUnix() {
time_t now = time(nullptr); time_t now = time(nullptr);
if (now < 30000) { if (now < 30000) {
return "failed"; return "failed";
} else { } else {
return String(now); return String(now);
} }
} }
// Получение текущего времени // Получение текущего времени
String GetTime() { String GetTime() {
time_t now = time(nullptr); // получаем время с помощью библиотеки time.h time_t now = time(nullptr); // получаем время с помощью библиотеки time.h
int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
now = now + zone; now = now + zone;
String Time = ""; // Строка для результатов времени String Time = ""; // Строка для результатов времени
Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
int i = Time.indexOf(":"); //Ишем позицию первого символа : int i = Time.indexOf(":"); //Ишем позицию первого символа :
Time = Time.substring(i - 2, i + 6); // Выделяем из строки 2 символа перед символом : и 6 символов после Time = Time.substring(i - 2, i + 6); // Выделяем из строки 2 символа перед символом : и 6 символов после
return Time; // Возврашаем полученное время return Time; // Возврашаем полученное время
} }
String GetTimeWOsec() { String GetTimeWOsec() {
time_t now = time(nullptr); // получаем время с помощью библиотеки time.h time_t now = time(nullptr); // получаем время с помощью библиотеки time.h
int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
now = now + zone; now = now + zone;
String Time = ""; // Строка для результатов времени String Time = ""; // Строка для результатов времени
Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
int i = Time.indexOf(":"); //Ишем позицию первого символа : int i = Time.indexOf(":"); //Ишем позицию первого символа :
Time = Time.substring(i - 2, i + 3); // Выделяем из строки 2 символа перед символом : и 6 символов после Time = Time.substring(i - 2, i + 3); // Выделяем из строки 2 символа перед символом : и 6 символов после
return Time; // Возврашаем полученное время return Time; // Возврашаем полученное время
} }
// Получение даты // Получение даты
String GetDate() { String GetDate() {
time_t now = time(nullptr); // получаем время с помощью библиотеки time.h time_t now = time(nullptr); // получаем время с помощью библиотеки time.h
int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
now = now + zone; now = now + zone;
String Data = ""; // Строка для результатов времени String Data = ""; // Строка для результатов времени
Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
Data.replace("\n", ""); Data.replace("\n", "");
uint8_t i = Data.lastIndexOf(" "); //Ишем позицию последнего символа пробел uint8_t i = Data.lastIndexOf(" "); //Ишем позицию последнего символа пробел
String Time = Data.substring(i - 8, i + 1); // Выделяем время и пробел String Time = Data.substring(i - 8, i + 1); // Выделяем время и пробел
Data.replace(Time, ""); // Удаляем из строки 8 символов времени и пробел Data.replace(Time, ""); // Удаляем из строки 8 символов времени и пробел
return Data; // Возврашаем полученную дату return Data; // Возврашаем полученную дату
} }
String GetDataDigital() { String GetDataDigital() {
String date = GetDate(); String date = GetDate();
date = deleteBeforeDelimiter(date, " ");
date.replace("Jan", "01");
date.replace("Feb", "02");
date.replace("Mar", "03");
date.replace("Apr", "04");
date.replace("May", "05");
date.replace("Jun", "06");
date.replace("Jul", "07");
date.replace("Aug", "08");
date.replace("Sep", "09");
date.replace("Oct", "10");
date.replace("Nov", "11");
date.replace("Dec", "12");
String month = date.substring(0, 2); date = deleteBeforeDelimiter(date, " ");
String day = date.substring(3, 5);
String year = date.substring(8, 10);
String out = day; date.replace("Jan", "01");
out += "."; date.replace("Feb", "02");
out += month; date.replace("Mar", "03");
out += "."; date.replace("Apr", "04");
out += year; date.replace("May", "05");
date.replace("Jun", "06");
date.replace("Jul", "07");
date.replace("Aug", "08");
date.replace("Sep", "09");
date.replace("Oct", "10");
date.replace("Nov", "11");
date.replace("Dec", "12");
return out; String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(8, 10);
String out = day;
out += ".";
out += month;
out += ".";
out += year;
return out;
} }
int timeToMin(String Time) { int timeToMin(String Time) {
//"00:00:00" время в секунды //"00:00:00" время в секунды
long min = selectToMarker(Time, ":").toInt() * 60; //общее количество секунд в полных часах long min = selectToMarker(Time, ":").toInt() * 60; //общее количество секунд в полных часах
Time = deleteBeforeDelimiter(Time, ":"); // Теперь здесь минуты секунды Time = deleteBeforeDelimiter (Time, ":"); // Теперь здесь минуты секунды
min += selectToMarker(Time, ":").toInt(); // Добавим секунды из полных минут min += selectToMarker(Time, ":").toInt(); // Добавим секунды из полных минут
return min; return min;
} }

View File

@@ -1,89 +1,91 @@
#include "Global.h" #include "Global.h"
//================================================================================================================
//=========================================Таймеры=================================================================
void Timer_countdown_init() { void Timer_countdown_init() {
ts.add(
TIMER_COUNTDOWN, 1000, [&](void*) { ts.add(TIMER_COUNTDOWN, 1000, [&](void*) {
String old_line = jsonReadStr(configOptionJson, "timers");
if (old_line != "") { String old_line = jsonReadStr(configOptionJson, "timers");
//Serial.println(old_line); if (old_line != "") {
int i = 0; //Serial.println(old_line);
do { int i = 0;
String timer = selectFromMarkerToMarker(old_line, ",", i); do {
Serial.print("timer no " + String(i) + ": "); String timer = selectFromMarkerToMarker(old_line, "," , i);
Serial.println(timer); Serial.print("timer no " + String (i) + ": ");
if (timer == "not found" || timer == "") return; Serial.println(timer);
int number = selectToMarker(timer, ":").toInt(); if (timer == "not found" || timer == "") return;
int time = readTimer(number); int number = selectToMarker (timer, ":").toInt();
if (time == 0) { int time = readTimer(number);
delTimer(String(number)); if (time == 0) {
jsonWriteStr(configLiveJson, "timer" + String(number), "0"); delTimer (String (number));
eventGen("timer", String(number)); jsonWriteStr(configLiveJson, "timer" + String(number), "0");
} else { eventGen ("timer", String(number));
time--; } else {
addTimer(String(number), String(time)); time--;
} addTimer(String (number), String (time));
i++; }
} while (i <= 9); i++;
} } while (i <= 9);
}, }
nullptr, true); }, nullptr, true);
} }
void timerStart_() { void timerStart_() {
String number = sCmd.next(); String number = sCmd.next();
String period_of_time = sCmd.next(); String period_of_time = sCmd.next();
String type = sCmd.next(); String type = sCmd.next();
if (period_of_time.indexOf("digit") != -1) { if (period_of_time.indexOf("digit") != -1) {
period_of_time = jsonReadStr(configLiveJson, period_of_time); //period_of_time = add_set(period_of_time);
} period_of_time = jsonReadStr(configLiveJson, period_of_time);
if (type == "sec") period_of_time = period_of_time; }
if (type == "min") period_of_time = String(period_of_time.toInt() * 60); if (type == "sec") period_of_time = period_of_time;
if (type == "hours") period_of_time = String(period_of_time.toInt() * 60 * 60); if (type == "min") period_of_time = String(period_of_time.toInt() * 60);
addTimer(number, period_of_time); if (type == "hours") period_of_time = String(period_of_time.toInt() * 60 * 60);
jsonWriteStr(configLiveJson, "timer" + number, "1"); addTimer(number, period_of_time);
jsonWriteStr(configLiveJson, "timer" + number, "1");
} }
void addTimer(String number, String time) { void addTimer(String number, String time) {
String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120, String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120,
String new_timer = number + ":" + time; String new_timer = number + ":" + time;
int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо заменить int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо заменить
if (psn1 != -1) { //если он есть if (psn1 != -1) { //если он есть
int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой
String timer = tmp.substring(psn1, psn2); //1:60 выделяем таймер который надо заменить String timer = tmp.substring(psn1, psn2); //1:60 выделяем таймер который надо заменить
///tmp.replace(timer, new_timer); //заменяем таймер на новый (во всей стороке) ///tmp.replace(timer, new_timer); //заменяем таймер на новый (во всей стороке)
tmp.replace(timer + ",", ""); tmp.replace(timer + ",", "");
tmp += new_timer + ","; tmp += new_timer + ",";
} else { //если его нет } else { //если его нет
tmp += new_timer + ","; tmp += new_timer + ",";
} }
jsonWriteStr(configOptionJson, "timers", tmp); jsonWriteStr(configOptionJson, "timers", tmp);
//Serial.println("ura"); //Serial.println("ura");
} }
void timerStop_() { void timerStop_() {
String number = sCmd.next(); String number = sCmd.next();
delTimer(number); delTimer(number);
} }
void delTimer(String number) { void delTimer (String number) {
String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120, String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120,
int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо удалить int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо удалить
if (psn1 != -1) { //если он есть if (psn1 != -1) { //если он есть
int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой
String timer = tmp.substring(psn1, psn2) + ","; //1:60, выделяем таймер который надо удалить String timer = tmp.substring(psn1, psn2) + ","; //1:60, выделяем таймер который надо удалить
tmp.replace(timer, ""); //удаляем таймер tmp.replace(timer, ""); //удаляем таймер
jsonWriteStr(configOptionJson, "timers", tmp); jsonWriteStr(configOptionJson, "timers", tmp);
} }
} }
int readTimer(int number) { int readTimer(int number) {
String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120, String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120,
int psn1 = tmp.indexOf(String(number) + ":"); //0 ищем позицию таймера который надо прочитать int psn1 = tmp.indexOf(String(number) + ":"); //0 ищем позицию таймера который надо прочитать
String timer; String timer;
if (psn1 != -1) { //если он есть if (psn1 != -1) { //если он есть
int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой
timer = tmp.substring(psn1, psn2); //1:60 выделяем таймер который надо прочитать timer = tmp.substring(psn1, psn2); //1:60 выделяем таймер который надо прочитать
timer = deleteBeforeDelimiter(timer, ":"); timer = deleteBeforeDelimiter(timer, ":");
} }
return timer.toInt(); return timer.toInt();
} }

View File

@@ -1,125 +1,89 @@
#include "Global.h" #include "Global.h"
static const char* UPDATE_URL PROGMEM = "http://91.204.228.124:1100/update/%s/%s";
static const char* FIRMWARE_FILE = "esp32-esp8266_iot-manager_modules_firmware.spiffs.bin";
#ifdef ESP32
static const char* MCU = "esp32";
#else
static const char* MCU = "esp8266";
#endif
const String createUrl(const char* qry) {
char buf[128];
sprintf_P(buf, UPDATE_URL, MCU, qry);
return String(buf);
}
const String getVersionUrl() {
return createUrl("version.txt");
}
const String getFirmwareUrl() {
return createUrl(FIRMWARE_FILE);
}
void initUpgrade() { void initUpgrade() {
String last_version = WiFi.status() == WL_CONNECTED ? getURL(getVersionUrl()) : ""; #ifdef ESP8266
jsonWriteStr(configSetupJson, "last_version", last_version); if (WiFi.status() == WL_CONNECTED) last_version = getURL("http://91.204.228.124:1100/update/esp8266/version.txt");
#endif
Serial.printf("[i] Last firmware version: %s\n", last_version.c_str()); #ifdef ESP32
if (WiFi.status() == WL_CONNECTED) last_version = getURL("http://91.204.228.124:1100/update/esp32/version.txt");
server.on("/check", HTTP_GET, [last_version](AsyncWebServerRequest* request) { #endif
upgrade_url = true; jsonWriteStr(configSetupJson, "last_version", last_version);
Serial.printf("[i] Last firmware version: %s\n", last_version.c_str()); Serial.print("[i] Last firmware version: ");
String tmp = "{}"; Serial.println(last_version);
if (WiFi.status() == WL_CONNECTED) {
if (mb_4_of_memory) {
if (last_version != "") {
if (last_version != "error") {
if (last_version == firmware_version) {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Последняя версия прошивки уже установлена.");
jsonWriteStr(tmp, "class", "pop-up");
} else {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Имеется новая версия прошивки<a href=\"#\" class=\"btn btn-block btn-danger\" onclick=\"send_request(this, '/upgrade');setTimeout(function(){ location.href='/'; }, 120000);html('my-block','<span class=loader></span>Идет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить</a>");
jsonWriteStr(tmp, "class", "pop-up");
}
} else {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Ошибка... Cервер не найден. Попробуйте позже...");
jsonWriteStr(tmp, "class", "pop-up");
}
} else {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Нажмите на кнопку \"обновить прошивку\" повторно...");
jsonWriteStr(tmp, "class", "pop-up");
}
} else {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Обновление по воздуху не поддерживается, модуль имеет меньше 4 мб памяти...");
jsonWriteStr(tmp, "class", "pop-up");
}
} else {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Устройство не подключен к роутеру...");
jsonWriteStr(tmp, "class", "pop-up");
}
request->send(200, "text/text", tmp);
});
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest* request) {
upgrade = true;
String tmp = "{}";
request->send(200, "text/text", "ok");
});
} }
void do_upgrade_url() { void do_upgrade_url() {
if (upgrade_url) { if (upgrade_url) {
upgrade_url = false; upgrade_url = false;
last_version = getURL(getVersionUrl()); #ifdef ESP32
jsonWriteStr(configSetupJson, "last_version", last_version); last_version = getURL("http://91.204.228.124:1100/update/esp32/version.txt");
} #endif
#ifdef ESP8266
last_version = getURL("http://91.204.228.124:1100/update/esp8266/version.txt");
#endif
jsonWriteStr(configSetupJson, "last_version", last_version);
}
} }
void upgrade_firmware() { void upgrade_firmware() {
String scenario_for_update;
String config_for_update;
String configSetupJson_for_update;
scenario_for_update = readFile("firmware.s.txt", 4000);
config_for_update = readFile("firmware.c.txt", 4000);
configSetupJson_for_update = configSetupJson;
Serial.println("Start upgrade SPIFFS, please wait..."); String scenario_for_update;
String config_for_update;
String configSetup_for_update;
scenario_for_update = readFile("firmware.s.txt", 4000);
config_for_update = readFile("firmware.c.txt", 4000);
configSetup_for_update = configSetupJson;
WiFiClient client_for_upgrade; Serial.println("Start upgrade SPIFFS, please wait...");
httpUpdate.rebootOnUpdate(false); WiFiClient client_for_upgrade;
t_httpUpdate_return ret = httpUpdate.updateSpiffs(client_for_upgrade, getFirmwareUrl());
#ifdef ESP32
httpUpdate.rebootOnUpdate(false);
t_httpUpdate_return ret = httpUpdate.updateSpiffs(client_for_upgrade, "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin");
#endif
#ifdef ESP8266
ESPhttpUpdate.rebootOnUpdate(false);
t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs(client_for_upgrade, "http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin");
#endif
if (ret == HTTP_UPDATE_OK) {
writeFile("firmware.s.txt", scenario_for_update);
writeFile("firmware.c.txt", config_for_update);
writeFile("config.json", configSetup_for_update);
saveConfig();
Serial.println("SPIFFS upgrade done!");
Serial.println("Start upgrade BUILD, please wait...");
#ifdef ESP32
//httpUpdate.rebootOnUpdate(true);
t_httpUpdate_return ret = httpUpdate.update(client_for_upgrade, "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.ino.bin");
#endif
#ifdef ESP8266
//ESPhttpUpdate.rebootOnUpdate(true);
t_httpUpdate_return ret = ESPhttpUpdate.update(client_for_upgrade, "http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.ino.bin");
#endif
if (ret == HTTP_UPDATE_OK) { if (ret == HTTP_UPDATE_OK) {
writeFile("firmware.s.txt", scenario_for_update);
writeFile("firmware.c.txt", config_for_update);
writeFile("config.json", configSetupJson_for_update);
saveConfig();
Serial.println("SPIFFS upgrade done!"); Serial.println("BUILD upgrade done!");
Serial.println("Start upgrade BUILD, please wait..."); Serial.println("Restart ESP....");
ESP.restart();
t_httpUpdate_return ret = httpUpdate.update(client_for_upgrade, getFirmwareUrl());
if (ret == HTTP_UPDATE_OK) {
Serial.println("BUILD upgrade done!");
Serial.println("Restart ESP....");
ESP.restart();
} else {
Serial.println("!!!!BUILD upgrade ERROR");
}
} else { } else {
Serial.println("!!!!SPIFFS upgrade ERROR"); Serial.println("!!!!BUILD upgrade ERROR");
} }
} else {
Serial.println("!!!!SPIFFS upgrade ERROR");
}
} }
void do_upgrade() { void do_upgrade() {
if (upgrade) { if (upgrade) {
upgrade = false; upgrade = false;
upgrade_firmware(); upgrade_firmware();
} }
} }
/* /*
@@ -128,95 +92,12 @@ void do_upgrade() {
case HTTP_UPDATE_FAILED: case HTTP_UPDATE_FAILED:
Serial.printf("UPDATE_FAILED Error (%d): %s", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); Serial.printf("UPDATE_FAILED Error (%d): %s", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
break; break;
case HTTP_UPDATE_NO_UPDATES: case HTTP_UPDATE_NO_UPDATES:
Serial.println("NO_UPDATES"); Serial.println("NO_UPDATES");
break; break;
case HTTP_UPDATE_OK: case HTTP_UPDATE_OK:
Serial.println("HTTP_UPDATE_OK"); Serial.println("HTTP_UPDATE_OK");
break; break;
} }
} }
*/ */
/*
// ----------------------- Обновление с сайта
void webUpgrade() {
#ifdef ESP8266
String spiffsData = "http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin";
String buildData = "http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.ino.bin";
#endif
#ifdef ESP32
String spiffsData = "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin";
String buildData = "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.ino.bin";
#endif
if (spiffsData != "") { // Если нужно прошить FS
String scenario_for_update;
String config_for_update;
String configSetupJson_for_update;
Serial.println(spiffsData);
scenario_for_update = readFile("firmware.s.txt", 2048);
config_for_update = readFile("config.all.txt", 2048);
configSetupJson_for_update = configSetupJson;
ESPhttpUpdate.rebootOnUpdate(false); // Отключим перезагрузку после обновления
updateHTTP(spiffsData, true);
writeFile("firmware.s.txt", scenario_for_update);
writeFile("config.all.txt", config_for_update);
writeFile("config.json", configSetupJson_for_update);
saveConfig();
}
if (buildData != "") { // Если нужно прошить build
Serial.println(buildData);
ESPhttpUpdate.rebootOnUpdate(true); // Включим перезагрузку после обновления
updateHTTP(buildData, false);
}
}
// ------------------ Обновление по url
void updateHTTP(String url, boolean mode) {
if (url == "") return;
ESPhttpUpdate.setLedPin(LED_BUILTIN, LOW);
if (mode) {
Serial.println("Update Spiffs...");
t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs(url);
UpdateStatus(ret , "Spiffs");
} else {
Serial.println("Update Build...");
t_httpUpdate_return ret = ESPhttpUpdate.update(url);
UpdateStatus(ret , "build");
}
}
void UpdateStatus(t_httpUpdate_return set, String mode) {
switch (set) {
case HTTP_UPDATE_FAILED:
Serial.println(mode + "_FAILED");
var = "{}";
jsonWriteStr(var, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>_FAILED");
jsonWriteStr(var, "class", "pop-up");
//request->send(200, "text/text", var);
break;
case HTTP_UPDATE_NO_UPDATES:
Serial.println(mode + "_NO_UPDATES");
var = "{}";
jsonWriteStr(var, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>_NO_UPDATES");
jsonWriteStr(var, "class", "pop-up");
//request->send(200, "text/text", var);
break;
case HTTP_UPDATE_OK:
Serial.println(mode + "_UPDATE_OK");
var = "{}";
jsonWriteStr(var, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>_UPDATE_OK");
jsonWriteStr(var, "class", "pop-up");
//request->send(200, "text/text", var);
break;
}
}
*/

356
src/Web.cpp Normal file
View File

@@ -0,0 +1,356 @@
#include "Global.h"
String stateMQTT();
void web_init() {
server.on("/set", HTTP_GET, [](AsyncWebServerRequest * request) {
String value;
//============================device settings=====================================
if (request->hasArg("preset")) {
//--------------------------------------------------------------------------------
String value;
value = request->getParam("preset")->value();
if (value == "1") {
writeFile("firmware.c.txt", readFile("configs/1-relay.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/1-relay.s.txt", 2048));
}
if (value == "2") {
writeFile("firmware.c.txt", readFile("configs/2-relay.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/2-relay.s.txt", 2048));
}
if (value == "3") {
writeFile("firmware.c.txt", readFile("configs/3-relay.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/3-relay.s.txt", 2048));
}
if (value == "4") {
writeFile("firmware.c.txt", readFile("configs/4-relay.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/4-relay.s.txt", 2048));
}
if (value == "5") {
writeFile("firmware.c.txt", readFile("configs/5-relay.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/5-relay.s.txt", 2048));
}
if (value == "6") {
writeFile("firmware.c.txt", readFile("configs/6-relay.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/6-relay.s.txt", 2048));
}
if (value == "7") {
writeFile("firmware.c.txt", readFile("configs/7-relay.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/7-relay.s.txt", 2048));
}
if (value == "8") {
writeFile("firmware.c.txt", readFile("configs/8-pwm.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/8-pwm.s.txt", 2048));
}
if (value == "9") {
writeFile("firmware.c.txt", readFile("configs/9-dht11.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/9-dht11.s.txt", 2048));
}
if (value == "10") {
writeFile("firmware.c.txt", readFile("configs/10-dht22.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/10-dht22.s.txt", 2048));
}
if (value == "11") {
writeFile("firmware.c.txt", readFile("configs/11-analog.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/11-analog.s.txt", 2048));
}
if (value == "12") {
writeFile("firmware.c.txt", readFile("configs/12-bmp280.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/12-bmp280.s.txt", 2048));
}
if (value == "13") {
writeFile("firmware.c.txt", readFile("configs/13-bme280.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/13-bme280.s.txt", 2048));
}
if (value == "14") {
writeFile("firmware.c.txt", readFile("configs/14-dallas.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/14-dallas.s.txt", 2048));
}
if (value == "15") {
writeFile("firmware.c.txt", readFile("configs/15-termostat.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/15-termostat.s.txt", 2048));
}
if (value == "16") {
writeFile("firmware.c.txt", readFile("configs/16-ultrasonic.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/16-ultrasonic.s.txt", 2048));
}
if (value == "17") {
writeFile("firmware.c.txt", readFile("configs/17-moution.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/17-moution.s.txt", 2048));
}
if (value == "18") {
writeFile("firmware.c.txt", readFile("configs/18-moution.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/18-moution.s.txt", 2048));
}
if (value == "19") {
writeFile("firmware.c.txt", readFile("configs/19-stepper.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/19-stepper.s.txt", 2048));
}
if (value == "20") {
writeFile("firmware.c.txt", readFile("configs/20-servo.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/20-servo.s.txt", 2048));
}
if (value == "21") {
writeFile("firmware.c.txt", readFile("configs/firmware.c.txt", 2048));
writeFile("firmware.s.txt", readFile("configs/firmware.s.txt", 2048));
}
Device_init();
Scenario_init();
request->redirect("/?set.device");
}
//--------------------------------------------------------------------------------
if (request->hasArg("devinit")) {
Device_init();
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
if (request->hasArg("scen")) {
value = request->getParam("scen")->value();
if (value == "0") {
jsonWriteStr(configSetupJson, "scen", value);
saveConfig();
Scenario_init();
}
if (value == "1") {
jsonWriteStr(configSetupJson, "scen", value);
saveConfig();
Scenario_init();
}
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
if (request->hasArg("sceninit")) {
Scenario_init();
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
#ifdef logging_enable
if (request->hasArg("cleanlog")) {
clean_log_date();
request->send(200, "text/text", "OK");
}
#endif
//==============================udp settings=============================================
if (request->hasArg("udponoff")) {
value = request->getParam("udponoff")->value();
if (value == "0") {
jsonWriteStr(configSetupJson, "udponoff", value);
saveConfig();
Scenario_init();
}
if (value == "1") {
jsonWriteStr(configSetupJson, "udponoff", value);
saveConfig();
Scenario_init();
}
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
if (request->hasArg("updatelist")) {
SPIFFS.remove("/dev.csv");
addFile("dev.csv", "device id;device name;ip address");
request->redirect("/?set.udp");
}
//--------------------------------------------------------------------------------
if (request->hasArg("updatepage")) {
request->redirect("/?set.udp");
}
//--------------------------------------------------------------------------------
if (request->hasArg("devname")) {
jsonWriteStr(configSetupJson, "name", request->getParam("devname")->value());
saveConfig();
request->send(200, "text/text", "OK");
}
//==============================wifi settings=============================================
if (request->hasArg("routerssid")) {
jsonWriteStr(configSetupJson, "routerssid", request->getParam("routerssid")->value());
saveConfig();
request->send(200, "text/text", "OK");
}
if (request->hasArg("routerpass")) {
jsonWriteStr(configSetupJson, "routerpass", request->getParam("routerpass")->value());
saveConfig();
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
if (request->hasArg("apssid")) {
jsonWriteStr(configSetupJson, "apssid", request->getParam("apssid")->value());
saveConfig();
request->send(200, "text/text", "OK");
}
if (request->hasArg("appass")) {
jsonWriteStr(configSetupJson, "appass", request->getParam("appass")->value());
saveConfig();
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
if (request->hasArg("weblogin")) {
jsonWriteStr(configSetupJson, "weblogin", request->getParam("weblogin")->value());
saveConfig();
request->send(200, "text/text", "OK");
}
if (request->hasArg("webpass")) {
jsonWriteStr(configSetupJson, "webpass", request->getParam("webpass")->value());
saveConfig();
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
if (request->hasArg("timezone")) {
jsonWriteStr(configSetupJson, "timezone", request->getParam("timezone")->value());
saveConfig();
reconfigTime();
request->send(200, "text/text", "OK");
}
if (request->hasArg("ntp")) {
jsonWriteStr(configSetupJson, "ntp", request->getParam("ntp")->value());
saveConfig();
reconfigTime();
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
if (request->hasArg("device")) {
if (request->getParam("device")->value() == "ok") ESP.restart();
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------
if (request->hasArg("blink")) {
value = request->getParam("blink")->value();
if (value == "0") {
jsonWriteStr(configSetupJson, "blink", value);
saveConfig();
}
if (value == "1") {
jsonWriteStr(configSetupJson, "blink", value);
saveConfig();
}
request->send(200, "text/text", "OK");
}
//==============================mqtt settings=============================================
if (request->hasArg("mqttServer")) {
jsonWriteStr(configSetupJson, "mqttServer", request->getParam("mqttServer")->value());
saveConfig();
mqtt_connection = true;
request->send(200, "text/text", "ok");
}
if (request->hasArg("mqttPort")) {
int port = (request->getParam("mqttPort")->value()).toInt();
jsonWriteInt(configSetupJson, "mqttPort", port);
saveConfig();
mqtt_connection = true;
request->send(200, "text/text", "ok");
}
if (request->hasArg("mqttPrefix")) {
jsonWriteStr(configSetupJson, "mqttPrefix", request->getParam("mqttPrefix")->value());
saveConfig();
mqtt_connection = true;
request->send(200, "text/text", "ok");
}
if (request->hasArg("mqttUser")) {
jsonWriteStr(configSetupJson, "mqttUser", request->getParam("mqttUser")->value());
saveConfig();
mqtt_connection = true;
request->send(200, "text/text", "ok");
}
if (request->hasArg("mqttPass")) {
jsonWriteStr(configSetupJson, "mqttPass", request->getParam("mqttPass")->value());
saveConfig();
mqtt_connection = true;
request->send(200, "text/text", "ok");
}
//--------------------------------------------------------------------------------
if (request->hasArg("mqttsend")) {
mqtt_send_settings_to_udp = true;
request->send(200, "text/text", "ok");
}
//--------------------------------------------------------------------------------
if (request->hasArg("mqttcheck")) {
String tmp = "{}";
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + stateMQTT());
jsonWriteStr(tmp, "class", "pop-up");
request->send(200, "text/text", tmp);
}
//==============================push settings=============================================
#ifdef push_enable
if (request->hasArg("pushingboxid")) {
jsonWriteStr(configSetupJson, "pushingboxid", request->getParam("pushingboxid")->value());
saveConfig();
request->send(200, "text/text", "ok");
}
#endif
//==============================utilities settings=============================================
if (request->hasArg("itoc")) {
i2c_scanning = true;
request->redirect("/?set.utilities");
}
});
//==============================upgrade settings=============================================
server.on("/check", HTTP_GET, [](AsyncWebServerRequest * request) {
upgrade_url = true;
Serial.print("[i] Last firmware version: ");
Serial.println(last_version);
String tmp = "{}";
int case_of_update;
if (WiFi.status() != WL_CONNECTED) last_version = "nowifi";
if (!mb_4_of_memory) last_version = "less";
if (last_version == firmware_version) case_of_update = 1;
if (last_version != firmware_version) case_of_update = 2;
if (last_version == "error") case_of_update = 3;
if (last_version == "") case_of_update = 4;
if (last_version == "less") case_of_update = 5;
if (last_version == "nowifi") case_of_update = 6;
if (last_version == "notsupported") case_of_update = 7;
switch (case_of_update) {
case 1: {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Последняя версия прошивки уже установлена.");
jsonWriteStr(tmp, "class", "pop-up");
}
break;
case 2: {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Имеется новая версия прошивки<a href=\"#\" class=\"btn btn-block btn-danger\" onclick=\"send_request(this, '/upgrade');setTimeout(function(){ location.href='/'; }, 120000);html('my-block','<span class=loader></span>Идет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить</a>");
jsonWriteStr(tmp, "class", "pop-up");
}
break;
case 3: {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Ошибка... Cервер не найден. Попробуйте позже...");
jsonWriteStr(tmp, "class", "pop-up");
}
break;
case 4: {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Нажмите на кнопку \"обновить прошивку\" повторно...");
jsonWriteStr(tmp, "class", "pop-up");
break;
}
case 5: {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Обновление по воздуху не поддерживается, модуль имеет меньше 4 мб памяти...");
jsonWriteStr(tmp, "class", "pop-up");
break;
}
case 6: {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Устройство не подключено к роутеру...");
jsonWriteStr(tmp, "class", "pop-up");
break;
}
case 7: {
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Обновление на новую версию возможно только через usb...");
jsonWriteStr(tmp, "class", "pop-up");
break;
}
}
request->send(200, "text/text", tmp);
});
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest * request) {
upgrade = true;
String tmp = "{}";
request->send(200, "text/text", "ok");
});
}

View File

@@ -1,230 +1,234 @@
#include "Global.h" #include "Global.h"
void Web_server_init() { void Web_server_init() {
/*********************************************************************************
***************************************OTA****************************************
*********************************************************************************/
#ifdef OTA_enable #ifdef OTA_enable
ArduinoOTA.onStart([]() { ArduinoOTA.onStart([]() {
events.send("Update Start", "ota"); events.send("Update Start", "ota");
}); });
ArduinoOTA.onEnd([]() { ArduinoOTA.onEnd([]() {
events.send("Update End", "ota"); events.send("Update End", "ota");
}); });
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
char p[32]; char p[32];
sprintf(p, "Progress: %u%%\n", (progress / (total / 100))); sprintf(p, "Progress: %u%%\n", (progress / (total / 100)));
events.send(p, "ota"); events.send(p, "ota");
}); });
ArduinoOTA.onError([](ota_error_t error) { ArduinoOTA.onError([](ota_error_t error) {
if (error == OTA_AUTH_ERROR) if (error == OTA_AUTH_ERROR) events.send("Auth Failed", "ota");
events.send("Auth Failed", "ota"); else if (error == OTA_BEGIN_ERROR) events.send("Begin Failed", "ota");
else if (error == OTA_BEGIN_ERROR) else if (error == OTA_CONNECT_ERROR) events.send("Connect Failed", "ota");
events.send("Begin Failed", "ota"); else if (error == OTA_RECEIVE_ERROR) events.send("Recieve Failed", "ota");
else if (error == OTA_CONNECT_ERROR) else if (error == OTA_END_ERROR) events.send("End Failed", "ota");
events.send("Connect Failed", "ota"); });
else if (error == OTA_RECEIVE_ERROR) ArduinoOTA.setHostname(hostName);
events.send("Recieve Failed", "ota"); ArduinoOTA.begin();
else if (error == OTA_END_ERROR)
events.send("End Failed", "ota");
});
ArduinoOTA.setHostname(hostName);
ArduinoOTA.begin();
#endif #endif
/********************************************************************************* /*********************************************************************************
**************************************MDNS**************************************** **************************************MDNS****************************************
*********************************************************************************/ *********************************************************************************/
#ifdef MDNS_enable #ifdef MDNS_enable
MDNS.addService("http", "tcp", 80); MDNS.addService("http", "tcp", 80);
#endif #endif
//SPIFFS.begin(); //SPIFFS.begin();
/********************************************************************************* /*********************************************************************************
**************************************WS****************************************** **************************************WS******************************************
*********************************************************************************/ *********************************************************************************/
#ifdef WS_enable #ifdef WS_enable
ws.onEvent(onWsEvent); ws.onEvent(onWsEvent);
server.addHandler(&ws); server.addHandler(&ws);
events.onConnect([](AsyncEventSourceClient *client) { events.onConnect([](AsyncEventSourceClient * client) {
//!!!client->send("hello!", NULL, millis(), 1000); //!!!client->send("hello!", NULL, millis(), 1000);
}); });
server.addHandler(&events); server.addHandler(&events);
#endif #endif
/*********************************************************************************
**************************************WEB****************************************
*********************************************************************************/
#ifdef ESP32 #ifdef ESP32
server.addHandler(new SPIFFSEditor(SPIFFS, jsonReadStr(configSetupJson, "web_login").c_str(), jsonReadStr(configSetupJson, "web_pass").c_str())); server.addHandler(new SPIFFSEditor(SPIFFS, jsonReadStr(configSetupJson, "weblogin").c_str(), jsonReadStr(configSetupJson, "webpass").c_str()));
#elif defined(ESP8266) #elif defined(ESP8266)
server.addHandler(new SPIFFSEditor(jsonReadStr(configSetupJson, "web_login").c_str(), jsonReadStr(configSetupJson, "web_pass").c_str())); server.addHandler(new SPIFFSEditor(jsonReadStr(configSetupJson, "weblogin").c_str(), jsonReadStr(configSetupJson, "webpass").c_str()));
#endif #endif
/* server.on("/heap", HTTP_GET, [](AsyncWebServerRequest * request) { /* server.on("/heap", HTTP_GET, [](AsyncWebServerRequest * request) {
request->send(200, "text/plain", String(ESP.getFreeHeap())); request->send(200, "text/plain", String(ESP.getFreeHeap()));
});*/ });*/
server.serveStatic("/css/", SPIFFS, "/css/").setCacheControl("max-age=31536000"); server.serveStatic("/css/", SPIFFS, "/css/").setCacheControl("max-age=31536000");
server.serveStatic("/js/", SPIFFS, "/js/").setCacheControl("max-age=31536000"); server.serveStatic("/js/", SPIFFS, "/js/").setCacheControl("max-age=31536000");
server.serveStatic("/favicon.ico", SPIFFS, "/favicon.ico").setCacheControl("max-age=31536000"); server.serveStatic("/favicon.ico", SPIFFS, "/favicon.ico").setCacheControl("max-age=31536000");
server.serveStatic("/icon.jpeg", SPIFFS, "/icon.jpeg").setCacheControl("max-age=31536000");
server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm").setAuthentication(jsonReadStr(configSetupJson, "web_login").c_str(), jsonReadStr(configSetupJson, "web_pass").c_str()); server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm")
.setAuthentication(jsonReadStr(configSetupJson, "weblogin").c_str(), jsonReadStr(configSetupJson, "webpass").c_str());
server.onNotFound([](AsyncWebServerRequest *request) { server.onNotFound([](AsyncWebServerRequest * request) {
Serial.printf("NOT_FOUND: "); Serial.printf("NOT_FOUND: ");
if (request->method() == HTTP_GET) if (request->method() == HTTP_GET)
Serial.printf("GET"); Serial.printf("GET");
else if (request->method() == HTTP_POST) else if (request->method() == HTTP_POST)
Serial.printf("POST"); Serial.printf("POST");
else if (request->method() == HTTP_DELETE) else if (request->method() == HTTP_DELETE)
Serial.printf("DELETE"); Serial.printf("DELETE");
else if (request->method() == HTTP_PUT) else if (request->method() == HTTP_PUT)
Serial.printf("PUT"); Serial.printf("PUT");
else if (request->method() == HTTP_PATCH) else if (request->method() == HTTP_PATCH)
Serial.printf("PATCH"); Serial.printf("PATCH");
else if (request->method() == HTTP_HEAD) else if (request->method() == HTTP_HEAD)
Serial.printf("HEAD"); Serial.printf("HEAD");
else if (request->method() == HTTP_OPTIONS) else if (request->method() == HTTP_OPTIONS)
Serial.printf("OPTIONS"); Serial.printf("OPTIONS");
else else
Serial.printf("UNKNOWN"); Serial.printf("UNKNOWN");
Serial.printf(" http://%s%s\n", request->host().c_str(), request->url().c_str()); Serial.printf(" http://%s%s\n", request->host().c_str(), request->url().c_str());
if (request->contentLength()) { if (request->contentLength()) {
Serial.printf("_CONTENT_TYPE: %s\n", request->contentType().c_str()); Serial.printf("_CONTENT_TYPE: %s\n", request->contentType().c_str());
Serial.printf("_CONTENT_LENGTH: %u\n", request->contentLength()); Serial.printf("_CONTENT_LENGTH: %u\n", request->contentLength());
} }
int headers = request->headers(); int headers = request->headers();
int i; int i;
for (i = 0; i < headers; i++) { for (i = 0; i < headers; i++) {
AsyncWebHeader *h = request->getHeader(i); AsyncWebHeader* h = request->getHeader(i);
Serial.printf("_HEADER[%s]: %s\n", h->name().c_str(), h->value().c_str()); Serial.printf("_HEADER[%s]: %s\n", h->name().c_str(), h->value().c_str());
} }
int params = request->params(); int params = request->params();
for (i = 0; i < params; i++) { for (i = 0; i < params; i++) {
AsyncWebParameter *p = request->getParam(i); AsyncWebParameter* p = request->getParam(i);
if (p->isFile()) { if (p->isFile()) {
Serial.printf("_FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size()); Serial.printf("_FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size());
} else if (p->isPost()) { } else if (p->isPost()) {
Serial.printf("_POST[%s]: %s\n", p->name().c_str(), p->value().c_str()); Serial.printf("_POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
} else { } else {
Serial.printf("_GET[%s]: %s\n", p->name().c_str(), p->value().c_str()); Serial.printf("_GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
} }
} }
request->send(404); request->send(404);
}); });
server.onFileUpload([](AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) {
if (!index)
Serial.printf("UploadStart: %s\n", filename.c_str());
Serial.printf("%s", (const char *)data);
if (final)
Serial.printf("UploadEnd: %s (%u)\n", filename.c_str(), index + len);
});
server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { server.onFileUpload([](AsyncWebServerRequest * request, const String & filename, size_t index, uint8_t *data, size_t len, bool final) {
if (!index) if (!index)
Serial.printf("BodyStart: %u\n", total); Serial.printf("UploadStart: %s\n", filename.c_str());
Serial.printf("%s", (const char *)data); Serial.printf("%s", (const char*)data);
if (index + len == total) if (final)
Serial.printf("BodyEnd: %u\n", total); Serial.printf("UploadEnd: %s (%u)\n", filename.c_str(), index + len);
}); });
server.begin();
// --------------------Выдаем данные configLiveJson //config.live.json - динамические данные server.onRequestBody([](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) {
server.on("/config.live.json", HTTP_GET, [](AsyncWebServerRequest *request) { if (!index)
request->send(200, "application/json", configLiveJson); Serial.printf("BodyStart: %u\n", total);
}); Serial.printf("%s", (const char*)data);
// --------------------Выдаем данные configOptionJson //config.option.json - данные не являющиеся событиями if (index + len == total)
server.on("/config.option.json", HTTP_GET, [](AsyncWebServerRequest *request) { Serial.printf("BodyEnd: %u\n", total);
request->send(200, "application/json", configOptionJson); });
});
// -------------------Выдаем данные configSetupJson //config.setup.json - для хранения постоянных данных
server.on("/config.setup.json", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "application/json", configSetupJson);
});
// ------------------Выполнение команды из запроса server.begin();
//http://192.168.88.45/cmd?command=rel%201%201
server.on("/cmd", HTTP_GET, [](AsyncWebServerRequest *request) { // --------------------Выдаем данные configJson //config.live.json - динамические данные
String com = request->getParam("command")->value(); server.on("/config.live.json", HTTP_GET, [](AsyncWebServerRequest * request) {
Serial.println(com); request->send(200, "application/json", configLiveJson);
order_loop += com + ","; });
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении // --------------------Выдаем данные optionJson //config.option.json - данные не являющиеся событиями
}); server.on("/config.option.json", HTTP_GET, [](AsyncWebServerRequest * request) {
request->send(200, "application/json", configOptionJson);
});
// -------------------Выдаем данные configSetup //config.setup.json - для хранения постоянных данных
server.on("/config.setup.json", HTTP_GET, [](AsyncWebServerRequest * request) {
request->send(200, "application/json", configSetupJson);
});
// ------------------Выполнение команды из запроса
//http://192.168.88.45/cmd?command=rel%201%201
server.on("/cmd", HTTP_GET, [](AsyncWebServerRequest * request) {
String com = request->getParam("command")->value();
Serial.println(com);
order_loop += com + ",";
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
} }
/********************************************************************************************************************************* /*********************************************************************************************************************************
*********************************************************WS********************************************************************** *********************************************************WS**********************************************************************
********************************************************************************************************************************/ ********************************************************************************************************************************/
#ifdef WS_enable #ifdef WS_enable
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) { if (type == WS_EVT_CONNECT) {
Serial.printf("ws[%s][%u] connect\n", server->url(), client->id()); Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
client->printf(json.c_str(), client->id()); client->printf(json.c_str(), client->id());
//client->ping(); //client->ping();
} else if (type == WS_EVT_DISCONNECT) { } else if (type == WS_EVT_DISCONNECT) {
Serial.printf("ws[%s][%u] disconnect\n", server->url(), client->id()); Serial.printf("ws[%s][%u] disconnect\n", server->url(), client->id());
} else if (type == WS_EVT_ERROR) { } else if (type == WS_EVT_ERROR) {
Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t *)arg), (char *)data); Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t*)arg), (char*)data);
} else if (type == WS_EVT_PONG) { } else if (type == WS_EVT_PONG) {
Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len) ? (char *)data : ""); Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len) ? (char*)data : "");
} else if (type == WS_EVT_DATA) { } else if (type == WS_EVT_DATA) {
AwsFrameInfo *info = (AwsFrameInfo *)arg; AwsFrameInfo * info = (AwsFrameInfo*)arg;
String msg = ""; String msg = "";
if (info->final && info->index == 0 && info->len == len) { if (info->final && info->index == 0 && info->len == len) {
//the whole message is in a single frame and we got all of it's data //the whole message is in a single frame and we got all of it's data
Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT) ? "text" : "binary", info->len); Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT) ? "text" : "binary", info->len);
if (info->opcode == WS_TEXT) { if (info->opcode == WS_TEXT) {
for (size_t i = 0; i < info->len; i++) { for (size_t i = 0; i < info->len; i++) {
msg += (char)data[i]; msg += (char) data[i];
}
} else {
char buff[3];
for (size_t i = 0; i < info->len; i++) {
sprintf(buff, "%02x ", (uint8_t)data[i]);
msg += buff;
}
}
Serial.printf("%s\n", msg.c_str());
if (info->opcode == WS_TEXT)
client->text("{}");
else
client->binary("{}");
} else {
//message is comprised of multiple frames or the frame is split into multiple packets
if (info->index == 0) {
if (info->num == 0)
Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT) ? "text" : "binary");
Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len);
}
Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT) ? "text" : "binary", info->index, info->index + len);
if (info->opcode == WS_TEXT) {
for (size_t i = 0; i < len; i++) {
msg += (char)data[i];
}
} else {
char buff[3];
for (size_t i = 0; i < len; i++) {
sprintf(buff, "%02x ", (uint8_t)data[i]);
msg += buff;
}
}
Serial.printf("%s\n", msg.c_str());
if ((info->index + len) == info->len) {
Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len);
if (info->final) {
Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT) ? "text" : "binary");
if (info->message_opcode == WS_TEXT)
client->text("I got your text message");
else
client->binary("I got your binary message");
}
}
} }
} else {
char buff[3];
for (size_t i = 0; i < info->len; i++) {
sprintf(buff, "%02x ", (uint8_t) data[i]);
msg += buff ;
}
}
Serial.printf("%s\n", msg.c_str());
if (info->opcode == WS_TEXT)
client->text("{}");
else
client->binary("{}");
} else {
//message is comprised of multiple frames or the frame is split into multiple packets
if (info->index == 0) {
if (info->num == 0)
Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT) ? "text" : "binary");
Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len);
}
Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT) ? "text" : "binary", info->index, info->index + len);
if (info->opcode == WS_TEXT) {
for (size_t i = 0; i < len; i++) {
msg += (char) data[i];
}
} else {
char buff[3];
for (size_t i = 0; i < len; i++) {
sprintf(buff, "%02x ", (uint8_t) data[i]);
msg += buff ;
}
}
Serial.printf("%s\n", msg.c_str());
if ((info->index + len) == info->len) {
Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len);
if (info->final) {
Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT) ? "text" : "binary");
if (info->message_opcode == WS_TEXT)
client->text("I got your text message");
else
client->binary("I got your binary message");
}
}
} }
}
} }
#endif #endif

View File

@@ -2,146 +2,88 @@
boolean RouterFind(String ssid); boolean RouterFind(String ssid);
void WIFI_init() void ROUTER_Connecting() {
{
// --------------------Получаем ssid password со страницы led_blink("slow");
server.on("/ssid", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request->hasArg("ssid"))
{
jsonWriteStr(configSetupJson, "ssid", request->getParam("ssid")->value());
}
if (request->hasArg("password"))
{
jsonWriteStr(configSetupJson, "password", request->getParam("password")->value());
}
saveConfig(); // Функция сохранения данных во Flash
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
// --------------------Получаем ssidAP passwordAP со страницы
server.on("/ssidap", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request->hasArg("ssidAP"))
{
jsonWriteStr(configSetupJson, "ssidAP", request->getParam("ssidAP")->value());
}
if (request->hasArg("passwordAP"))
{
jsonWriteStr(configSetupJson, "passwordAP", request->getParam("passwordAP")->value());
}
saveConfig(); // Функция сохранения данных во Flash
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
// --------------------Получаем логин и пароль для web со страницы WiFi.mode(WIFI_STA);
server.on("/web", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request->hasArg("web_login"))
{
jsonWriteStr(configSetupJson, "web_login", request->getParam("web_login")->value());
}
if (request->hasArg("web_pass"))
{
jsonWriteStr(configSetupJson, "web_pass", request->getParam("web_pass")->value());
}
saveConfig(); // Функция сохранения данных во Flash
//Web_server_init();
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
server.on("/restart", HTTP_GET, [](AsyncWebServerRequest *request) { byte tries = 20;
if (request->hasArg("device")) String _ssid = jsonReadStr(configSetupJson, "routerssid");
{ String _password = jsonReadStr(configSetupJson, "routerpass");
if (request->getParam("device")->value() == "ok") //WiFi.persistent(false);
ESP.restart();
} if (_ssid == "" && _password == "") {
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении WiFi.begin();
}); }
ROUTER_Connecting(); else {
WiFi.begin(_ssid.c_str(), _password.c_str());
Serial.print("ssid: ");
Serial.println(_ssid);
}
// Делаем проверку подключения до тех пор пока счетчик tries
// не станет равен нулю или не получим подключение
while (--tries && WiFi.status() != WL_CONNECTED) {
if (WiFi.status() == WL_CONNECT_FAILED) {
Serial.println("[E] password is not correct");
tries = 1;
jsonWriteInt(configOptionJson, "pass_status", 1);
}
Serial.print(".");
delay(1000);
}
if (WiFi.status() != WL_CONNECTED)
{
// Если не удалось подключиться запускаем в режиме AP
Serial.println("");
// WiFi.disconnect(true);
StartAPMode();
}
else {
// Иначе удалось подключиться отправляем сообщение
// о подключении и выводим адрес IP
Serial.println("");
Serial.println("[V] WiFi connected");
Serial.print("[V] IP address: http://");
Serial.print(WiFi.localIP());
Serial.println("");
jsonWriteStr(configSetupJson, "ip", WiFi.localIP().toString());
led_blink("off");
//add_dev_in_list("dev.txt", chipID, WiFi.localIP().toString());
MQTT_init();
}
} }
void ROUTER_Connecting() bool StartAPMode() {
{ Serial.println("WiFi up AP");
led_blink("slow"); WiFi.disconnect();
WiFi.mode(WIFI_STA); WiFi.mode(WIFI_AP);
byte tries = 20; String _ssidAP = jsonReadStr(configSetupJson, "apssid");
String _ssid = jsonReadStr(configSetupJson, "ssid"); String _passwordAP = jsonReadStr(configSetupJson, "appass");
String _password = jsonReadStr(configSetupJson, "password"); WiFi.softAP(_ssidAP.c_str(), _passwordAP.c_str());
//WiFi.persistent(false); IPAddress myIP = WiFi.softAPIP();
led_blink("on");
Serial.print("AP IP address: ");
Serial.println(myIP);
jsonWriteStr(configSetupJson, "ip", myIP.toString());
if (_ssid == "" && _password == "") //if (jsonReadInt(configOptionJson, "pass_status") != 1) {
{ ts.add(ROUTER_SEARCHING, 10 * 1000, [&](void*) {
WiFi.begin(); Serial.println("->try find router");
} if (RouterFind(jsonReadStr(configSetupJson, "routerssid"))) {
else ts.remove(ROUTER_SEARCHING);
{ WiFi.scanDelete();
WiFi.begin(_ssid.c_str(), _password.c_str()); ROUTER_Connecting();
Serial.print("ssid: "); }
Serial.println(_ssid); }, nullptr, true);
} //}
// Делаем проверку подключения до тех пор пока счетчик tries return true;
// не станет равен нулю или не получим подключение
while (--tries && WiFi.status() != WL_CONNECTED)
{
if (WiFi.status() == WL_CONNECT_FAILED)
{
Serial.println("[E] password is not correct");
tries = 1;
jsonWriteInt(configOptionJson, "pass_status", 1);
}
Serial.print(".");
delay(1000);
}
Serial.println();
if (WiFi.status() != WL_CONNECTED)
{
StartAPMode();
}
else
{
Serial.println("[V] WiFi connected");
Serial.print("[V] IP address: http://");
Serial.print(WiFi.localIP());
Serial.println();
jsonWriteStr(configLiveJson, "ip", WiFi.localIP().toString());
led_blink("off");
}
} }
bool StartAPMode()
{
Serial.println("WiFi up AP");
WiFi.disconnect();
WiFi.mode(WIFI_AP);
String _ssidAP = jsonReadStr(configSetupJson, "ssidAP");
String _passwordAP = jsonReadStr(configSetupJson, "passwordAP");
WiFi.softAP(_ssidAP.c_str(), _passwordAP.c_str());
IPAddress myIP = WiFi.softAPIP();
led_blink("on");
Serial.print("AP IP address: ");
Serial.println(myIP);
jsonWriteStr(configLiveJson, "ip", myIP.toString());
if (jsonReadInt(configOptionJson, "pass_status") != 1)
{
ts.add(
ROUTER_SEARCHING, 10 * 1000, [&](void *) {
Serial.println("->try find router");
if (RouterFind(jsonReadStr(configSetupJson, "ssid")))
{
ts.remove(ROUTER_SEARCHING);
WiFi.scanDelete();
ROUTER_Connecting();
MQTT_init();
}
},
nullptr, true);
}
return true;
}
boolean RouterFind(String ssid) boolean RouterFind(String ssid)
{ {
@@ -191,4 +133,4 @@ boolean RouterFind(String ssid)
WiFi.scanDelete(); WiFi.scanDelete();
} }
return res; return res;
} }

View File

@@ -1,79 +1,90 @@
#include "Global.h" #include "Global.h"
void createWidget(String widget_name, String page_name, String page_number, String file, String topic) { //======================================================================================================================
String widget; //===============================================Создание виджетов=======================================================
widget = readFile(file, 1024); void createWidget (String widget_name, String page_name, String page_number, String file, String topic) {
if (widget == "Failed") return;
if (widget == "Large") return; String widget;
widget_name.replace("#", " "); widget = readFile(file, 1024);
page_name.replace("#", " ");
jsonWriteStr(widget, "page", page_name); if (widget == "Failed") return;
jsonWriteStr(widget, "order", page_number); if (widget == "Large") return;
jsonWriteStr(widget, "descr", widget_name);
jsonWriteStr(widget, "topic", prex + "/" + topic); widget_name.replace("#", " ");
page_name.replace("#", " ");
jsonWriteStr(widget, "page", page_name);
jsonWriteStr(widget, "order", page_number);
jsonWriteStr(widget, "descr", widget_name);
jsonWriteStr(widget, "topic", prex + "/" + topic);
#ifdef layout_in_ram #ifdef layout_in_ram
all_widgets += widget + "\r\n"; all_widgets += widget + "\r\n";
#else #else
addFile("layout.txt", widget); addFile("layout.txt", widget);
#endif #endif
widget = ""; widget = "";
} }
void createWidgetParam(String widget_name, String page_name, String page_number, String file, String topic, String name1, String param1, String name2, String param2, String name3, String param3) { void createWidgetParam (String widget_name, String page_name, String page_number, String file, String topic, String name1, String param1, String name2, String param2, String name3, String param3) {
String widget;
widget = readFile(file, 1024);
if (widget == "Failed") return; String widget;
if (widget == "Large") return; widget = readFile(file, 1024);
widget_name.replace("#", " "); if (widget == "Failed") return;
page_name.replace("#", " "); if (widget == "Large") return;
jsonWriteStr(widget, "page", page_name); widget_name.replace("#", " ");
jsonWriteStr(widget, "order", page_number); page_name.replace("#", " ");
jsonWriteStr(widget, "descr", widget_name);
jsonWriteStr(widget, "topic", prex + "/" + topic);
if (name1 != "") jsonWriteStr(widget, name1, param1); jsonWriteStr(widget, "page", page_name);
if (name2 != "") jsonWriteStr(widget, name2, param2); jsonWriteStr(widget, "order", page_number);
if (name3 != "") jsonWriteStr(widget, name3, param3); jsonWriteStr(widget, "descr", widget_name);
jsonWriteStr(widget, "topic", prex + "/" + topic);
if (name1 != "") jsonWriteStr(widget, name1, param1);
if (name2 != "") jsonWriteStr(widget, name2, param2);
if (name3 != "") jsonWriteStr(widget, name3, param3);
#ifdef layout_in_ram #ifdef layout_in_ram
all_widgets += widget + "\r\n"; all_widgets += widget + "\r\n";
#else #else
addFile("layout.txt", widget); addFile("layout.txt", widget);
#endif #endif
widget = ""; widget = "";
} }
void createChart(String widget_name, String page_name, String page_number, String file, String topic, String maxCount) { void createChart (String widget_name, String page_name, String page_number, String file, String topic, String maxCount) {
String widget;
widget = readFile(file, 1024);
if (widget == "Failed") return; String widget;
if (widget == "Large") return; widget = readFile(file, 1024);
widget_name.replace("#", " "); if (widget == "Failed") return;
page_name.replace("#", " "); if (widget == "Large") return;
jsonWriteStr(widget, "page", page_name); widget_name.replace("#", " ");
jsonWriteStr(widget, "order", page_number); page_name.replace("#", " ");
//jsonWriteStr(widget, "descr", widget_name);
jsonWriteStr(widget, "series", widget_name); jsonWriteStr(widget, "page", page_name);
jsonWriteStr(widget, "maxCount", maxCount); jsonWriteStr(widget, "order", page_number);
jsonWriteStr(widget, "topic", prex + "/" + topic); //jsonWriteStr(widget, "descr", widget_name);
jsonWriteStr(widget, "series", widget_name);
jsonWriteStr(widget, "maxCount", maxCount);
jsonWriteStr(widget, "topic", prex + "/" + topic);
#ifdef layout_in_ram #ifdef layout_in_ram
all_widgets += widget + "\r\n"; all_widgets += widget + "\r\n";
#else #else
addFile("layout.txt", widget); addFile("layout.txt", widget);
#endif #endif
widget = ""; widget = "";
} }
void choose_widget_and_create(String widget_name, String page_name, String page_number, String type, String topik) { void choose_widget_and_create(String widget_name, String page_name, String page_number, String type, String topik) {
if (type == "any-data") createWidget(widget_name, page_name, page_number, "widgets/widget.anyData.json", topik);
if (type == "progress-line") createWidget(widget_name, page_name, page_number, "widgets/widget.progLine.json", topik); if (type == "any-data") createWidget (widget_name, page_name, page_number, "widgets/widget.anyData.json", topik);
if (type == "progress-round") createWidget(widget_name, page_name, page_number, "widgets/widget.progRound.json", topik); if (type == "progress-line") createWidget (widget_name, page_name, page_number, "widgets/widget.progLine.json", topik);
if (type == "fill-gauge") createWidget(widget_name, page_name, page_number, "widgets/widget.fillGauge.json", topik); if (type == "progress-round") createWidget (widget_name, page_name, page_number, "widgets/widget.progRound.json", topik);
} if (type == "fill-gauge") createWidget (widget_name, page_name, page_number, "widgets/widget.fillGauge.json", topik);
}

View File

@@ -1,35 +1,35 @@
#include "Global.h" #include "Global.h"
void do_i2c_scanning() { void do_i2c_scanning() {
if (i2c_scanning) { if (i2c_scanning) {
i2c_scanning = false; i2c_scanning = false;
String tmp = i2c_scan(); String tmp = i2c_scan();
if (tmp == "error") { if (tmp == "error") {
tmp = i2c_scan(); tmp = i2c_scan();
Serial.println(tmp); Serial.println(tmp);
jsonWriteStr(configLiveJson, "i2c", tmp); jsonWriteStr(configLiveJson, "i2c", tmp);
} else { } else {
Serial.println(tmp); Serial.println(tmp);
jsonWriteStr(configLiveJson, "i2c", tmp); jsonWriteStr(configLiveJson, "i2c", tmp);
}
} }
}
} }
String i2c_scan() { String i2c_scan() {
String out; String out;
byte count = 0; byte count = 0;
Wire.begin(); Wire.begin();
for (byte i = 8; i < 120; i++) { for (byte i = 8; i < 120; i++) {
Wire.beginTransmission(i); Wire.beginTransmission(i);
if (Wire.endTransmission() == 0) { if (Wire.endTransmission() == 0) {
count++; count++;
out += String(count) + ". 0x" + String(i, HEX) + "; "; out += String(count) + ". 0x" + String(i, HEX) + "; ";
delay(1); delay(1);
}
} }
if (count == 0) { }
return "error"; if (count == 0) {
} else { return "error";
return out; } else {
} return out;
} }
}

View File

@@ -1,85 +1,84 @@
#include "Global.h" #include "Global.h"
void setup() { void setup() {
File_system_init(); //--------------------------------------------------------------
Serial.println("SPIFFS_init"); File_system_init();
Serial.println("SPIFFS_init");
CMD_init(); //--------------------------------------------------------------
Serial.println("[V] CMD_init"); CMD_init();
Serial.println("[V] CMD_init");
sensors_init(); //--------------------------------------------------------------
Serial.println("[V] sensors_init"); sensors_init();
Serial.println("[V] sensors_init");
All_init(); //--------------------------------------------------------------
Serial.println("[V] All_init"); All_init();
//-------------------------------------------------------------- Serial.println("[V] All_init");
WIFI_init(); //--------------------------------------------------------------
Serial.println("[V] WIFI_init"); ROUTER_Connecting();
//-------------------------------------------------------------- Serial.println("[V] ROUTER_Connecting");
statistics_init(); //--------------------------------------------------------------
Serial.println("[V] statistics_init"); uptime_init();
//-------------------------------------------------------------- Serial.println("[V] statistics_init");
initUpgrade(); //--------------------------------------------------------------
Serial.println("[V] initUpgrade"); initUpgrade();
//-------------------------------------------------------------- Serial.println("[V] initUpgrade");
Web_server_init(); //--------------------------------------------------------------
Serial.println("[V] Web_server_init"); Web_server_init();
//-------------------------------------------------------------- Serial.println("[V] Web_server_init");
MQTT_init(); //--------------------------------------------------------------
Serial.println("[V] MQTT_init"); web_init();
//-------------------------------------------------------------- Serial.println("[V] web_init");
Time_Init(); //--------------------------------------------------------------
Serial.println("[V] Time_Init"); Time_Init();
//-------------------------------------------------------------- Serial.println("[V] Time_Init");
#ifdef push_enable //--------------------------------------------------------------
Push_init();
Serial.println("[V] Push_init");
#endif
//--------------------------------------------------------------
#ifdef UDP_enable #ifdef UDP_enable
UDP_init(); UDP_init();
Serial.println("[V] UDP_init"); Serial.println("[V] UDP_init");
#endif #endif
//-------------------------------------------------------------- //--------------------------------------------------------------
ts.add(
TEST, 10000, [&](void*) {
getMemoryLoad("[i] periodic check of");
//ws.textAll(json);
},
nullptr, true);
just_load = false;
ts.add(TEST, 10000, [&](void*) {
getMemoryLoad("[i] periodic check of");
//ws.textAll(json);
}, nullptr, true);
just_load = false;
} }
void loop() { void loop() {
#ifdef OTA_enable #ifdef OTA_enable
ArduinoOTA.handle(); ArduinoOTA.handle();
#endif #endif
#ifdef WS_enable #ifdef WS_enable
ws.cleanupClients(); ws.cleanupClients();
#endif #endif
not_async_actions(); not_async_actions();
handleMQTT(); handleMQTT();
handleCMD_loop(); handleCMD_loop();
handleButton(); handleButton();
handleScenario(); handleScenario();
#ifdef UDP_enable #ifdef UDP_enable
handleUdp(); handleUdp();
#endif #endif
ts.update(); ts.update();
} }
void not_async_actions() { void not_async_actions() {
do_mqtt_connection(); do_mqtt_connection();
do_upgrade_url(); do_upgrade_url();
do_upgrade(); do_upgrade();
#ifdef UDP_enable #ifdef UDP_enable
do_udp_data_parse(); do_udp_data_parse();
do_mqtt_send_settings_to_udp(); do_mqtt_send_settings_to_udp();
#endif #endif
do_i2c_scanning(); do_i2c_scanning();
} }

View File

@@ -5,41 +5,7 @@ void add_dev_in_list(String fileName, String id, String dev_name, String ip);
#ifdef UDP_enable #ifdef UDP_enable
void UDP_init() { void UDP_init() {
server.on("/udp", HTTP_GET, [](AsyncWebServerRequest * request) {
String value;
if (request->hasArg("arg")) {
value = request->getParam("arg")->value();
}
if (value == "0") {
jsonWriteStr(configSetupJson, "udponoff", value);
request->send(200, "text/text", "ok");
}
if (value == "1") {
jsonWriteStr(configSetupJson, "udponoff", value);
request->send(200, "text/text", "ok");
}
if (value == "2") {
mqtt_send_settings_to_udp = true;
request->send(200, "text/text", "ok");
}
if (value == "3") {
SPIFFS.remove("/dev.csv");
addFile("dev.csv", "device id;device name;ip address");
request->redirect("/?dev");
}
if (value == "4") {
request->redirect("/?dev");
}
});
server.on("/name", HTTP_GET, [](AsyncWebServerRequest * request) {
if (request->hasArg("arg")) {
jsonWriteStr(configSetupJson, "name", request->getParam("arg")->value());
jsonWriteStr(configLiveJson, "name", request->getParam("arg")->value());
saveConfig();
}
request->send(200, "text/text", "OK");
});
SPIFFS.remove("/dev.csv"); SPIFFS.remove("/dev.csv");
addFile("dev.csv", "device id;device name;ip address"); addFile("dev.csv", "device id;device name;ip address");
@@ -180,4 +146,4 @@ void do_mqtt_send_settings_to_udp() {
send_mqtt_to_udp(); send_mqtt_to_udp();
} }
} }
#endif #endif