10 Commits

Author SHA1 Message Date
Dmitry Borisenko
cb2361c248 pic 2020-03-22 23:24:53 +01:00
Dmitry Borisenko
b799a48c8a fix many bugs 2020-03-22 22:41:52 +01:00
Dmitry Borisenko
9a775cd9d4 fix mqtt bug 2020-03-22 01:50:31 +01:00
Dmitry Borisenko
96e207676f add prefix 2020-03-21 18:14:38 +01:00
Dmitry Borisenko
ef92865886 some fix 2020-03-20 21:00:11 +01:00
Dmitry Borisenko
857177b5b7 some fix 2020-03-18 09:57:46 +01:00
Dmitry Borisenko
5fcb68ac65 some change 2020-03-17 17:54:57 +01:00
Dmitry Borisenko
8138893210 stepper motor support 2020-03-17 00:54:27 +01:00
Dmitry Borisenko
e1ef489706 add web socket and stepper control 2020-03-16 00:00:59 +01:00
Dmitry Borisenko
e2f8aaf505 bug with small file size 2020-03-04 22:10:59 +03:00
52 changed files with 1174 additions and 1208 deletions

68
Cmd.ino
View File

@@ -4,6 +4,8 @@ void CMD_init() {
sCmd.addCommand("buttonSet", buttonSet);
sCmd.addCommand("buttonChange", buttonChange);
//sCmd.addCommand("button_touch", button_touch);
sCmd.addCommand("pinSet", pinSet);
sCmd.addCommand("pinChange", pinChange);
@@ -22,6 +24,9 @@ void CMD_init() {
sCmd.addCommand("dhtComfort", dhtComfort);
sCmd.addCommand("dhtDewpoint", dhtDewpoint);
sCmd.addCommand("stepper", stepper);
sCmd.addCommand("stepperSet", stepperSet);
sCmd.addCommand("logging", logging);
sCmd.addCommand("inputDigit", inputDigit);
@@ -184,6 +189,7 @@ void pwm() {
jsonWrite(optionJson, "pwm_pin" + pwm_number, pwm_pin);
pinMode(pwm_pin_int, INPUT);
analogWrite(pwm_pin_int, start_state.toInt());
//analogWriteFreq(32000);
jsonWrite(configJson, "pwmSet" + pwm_number, start_state);
createViget (viget_name, page_name, page_number, "vigets/viget.range.json", "pwmSet" + pwm_number);
@@ -322,6 +328,62 @@ void textSet() {
sendSTATUS("textSet" + number, text);
}
//=====================================================================================================================================
//=========================================Модуль шагового мотора======================================================================
//stepper 1 12 13
void stepper() {
String stepper_number = sCmd.next();
String pin_step = sCmd.next();
String pin_dir = sCmd.next();
jsonWrite(optionJson, "stepper" + stepper_number, pin_step + " " + pin_dir);
pinMode(pin_step.toInt(), OUTPUT);
pinMode(pin_dir.toInt(), OUTPUT);
}
//stepperSet 1 100 5
void stepperSet() {
String stepper_number = sCmd.next();
String steps = sCmd.next();
jsonWrite(optionJson, "steps" + stepper_number, steps);
String stepper_speed = sCmd.next();
String pin_step = selectToMarker (jsonRead(optionJson, "stepper" + stepper_number), " ");
String pin_dir = deleteBeforeDelimiter (jsonRead(optionJson, "stepper" + stepper_number), " ");
Serial.println(pin_step);
Serial.println(pin_dir);
if (steps.toInt() > 0) digitalWrite(pin_dir.toInt(), HIGH);
if (steps.toInt() < 0) digitalWrite(pin_dir.toInt(), LOW);
if (stepper_number == "1") {
ts.add(STEPPER1, stepper_speed.toInt(), [&](void*) {
int steps_int = abs(jsonReadtoInt(optionJson, "steps1") * 2);
static int count;
count++;
String pin_step = selectToMarker (jsonRead(optionJson, "stepper1"), " ");
digitalWrite(pin_step.toInt(), !digitalRead(pin_step.toInt()));
if (count > steps_int) {
digitalWrite(pin_step.toInt(), LOW);
ts.remove(STEPPER1);
count = 0;
}
}, nullptr, true);
}
if (stepper_number == "2") {
ts.add(STEPPER2, stepper_speed.toInt(), [&](void*) {
int steps_int = abs(jsonReadtoInt(optionJson, "steps2") * 2);
static int count;
count++;
String pin_step = selectToMarker (jsonRead(optionJson, "stepper2"), " ");
digitalWrite(pin_step.toInt(), !digitalRead(pin_step.toInt()));
if (count > steps_int) {
digitalWrite(pin_step.toInt(), LOW);
ts.remove(STEPPER2);
count = 0;
}
}, nullptr, true);
}
}
//====================================================================================================================================================
/*
@@ -389,7 +451,7 @@ void mqttOrderSend() {
String id = sCmd.next();
String order = sCmd.next();
String all_line = prefix + "/" + id + "/order";
String all_line = jsonRead(configSetup, "mqttPrefix") + "/" + id + "/order";
//Serial.print(all_line);
//Serial.print("->");
//Serial.println(order);
@@ -542,7 +604,7 @@ void createViget (String viget_name, String page_name, String page_number, Stri
all_vigets += viget + "\r\n";
viget = "";
}
*/
String vidgetConfigWrite(String viget, String key, String value) {
if (viget == "") return "";
@@ -561,7 +623,7 @@ String vidgetConfigWrite(String viget, String key, String value) {
}
}
}
*/

View File

@@ -32,13 +32,16 @@ void All_init() {
void Device_init() {
//SENSORS-SECTION
ts.remove(ANALOG_);
ts.remove(LEVEL);
ts.remove(DALLAS);
ts.remove(DHTT);
ts.remove(DHTH);
//================
ts.remove(DHTC);
ts.remove(DHTP);
ts.remove(DHTD);
ts.remove(STEPPER1);
ts.remove(STEPPER2);
all_vigets = "";
txtExecution("firmware.config.txt");
@@ -187,6 +190,13 @@ void prsets_init() {
request->redirect("/page.htm?configuration");
});
server.on("/stepper", HTTP_GET, [](AsyncWebServerRequest * request) {
writeFile("firmware.config.txt", readFile("configs/stepper.config.txt", 2048));
writeFile("firmware.scenario.txt", readFile("configs/stepper.scenario.txt", 2048));
Device_init();
Scenario_init();
request->redirect("/page.htm?configuration");
});
//default===============================================================================
@@ -226,12 +236,20 @@ void up_time() {
Serial.println(out + ", mqtt_lost_error: " + String(mqtt_lost_error) + ", wifi_lost_error: " + String(wifi_lost_error));
}
void statistics_init() {
ts.add(STATISTICS, statistics_update, [&](void*) {
statistics();
}, nullptr, true);
}
void statistics() {
String urls = "http://backup.privet.lv/visitors/?";
//-----------------------------------------------------------------
urls += WiFi.macAddress().c_str();
urls += "&";
//-----------------------------------------------------------------
#ifdef ESP8266
urls += "iot-manager_esp8266";
#endif
@@ -239,15 +257,17 @@ void statistics() {
urls += "iot-manager_esp32";
#endif
urls += "&";
//-----------------------------------------------------------------
#ifdef ESP8266
urls += ESP.getResetReason();
#endif
#ifdef ESP32
urls += "unknow";
urls += "Unknown";
#endif
urls += "&";
urls += DATE_COMPILING;
//-----------------------------------------------------------------
urls += "firm version: " + firmware_version + " " + DATE_COMPILING + " " + TIME_COMPILING;
//-----------------------------------------------------------------
String stat = getURL(urls);
//Serial.println(stat);
}

40
SSDP.ino Normal file
View File

@@ -0,0 +1,40 @@
/*
void SSDP_init() {
// --------------------Получаем ssdp со страницы
server.on("/ssdp", HTTP_GET, [](AsyncWebServerRequest * request) {
if (request->hasArg("ssdp")) {
jsonWrite(configSetup, "SSDP", request->getParam("ssdp")->value());
jsonWrite(configJson, "SSDP", request->getParam("ssdp")->value());
SSDP.setName(jsonRead(configSetup, "SSDP"));
}
saveConfig();
request->send(200, "text/text", "OK");
});
// SSDP дескриптор
server.on("/description.xml", [](AsyncWebServerRequest * request) {
//SSDP.schema(http.client());
request->send(200, "text/text", "OK");
});
if (WiFi.status() == WL_CONNECTED) {
//Если версия 2.0.0 закаментируйте следующую строчку
SSDP.setDeviceType("upnp:rootdevice");
SSDP.setSchemaURL("description.xml");
SSDP.setHTTPPort(80);
SSDP.setName(jsonRead(configSetup, "SSDP"));
SSDP.setSerialNumber(chipID);
SSDP.setURL("/");
SSDP.setModelName("tech");
SSDP.setModelNumber(chipID + "/" + jsonRead(configSetup, "SSDP"));
SSDP.setModelURL("https://github.com/DmitryBorisenko33/esp32-esp8266_iot-manager_modules_firmware");
SSDP.setManufacturer("Borisenko Dmitry");
SSDP.setManufacturerURL("https://www.instagram.com/rriissee3");
SSDP.begin();
}
}
*/

View File

@@ -19,7 +19,7 @@ void analog() {
static int analog_old;
#ifdef ESP32
//int pin_int = pin.toInt();
int analog_in;// = analogRead(pin_int);
int analog_in = analogRead(34);
#endif
#ifdef ESP8266
int analog_in = analogRead(A0);
@@ -365,14 +365,6 @@ void logging() {
deleteOldDate("log.dallas.txt", jsonReadtoInt(optionJson, "dallas_logging_count"), jsonRead(configJson, "dallas"), false);
}, nullptr, true);
}
if (sensor_name == "ph") {
flagLoggingPh = true;
ts.remove(PH_LOG);
ts.add(PH_LOG, period_min.toInt() * 1000 * 60, [&](void*) {
deleteOldDate("log.ph.txt", jsonReadtoInt(optionJson, "ph_logging_count"), jsonRead(configJson, "ph"), false);
}, nullptr, true);
}
}
void deleteOldDate(String file, int seted_number_of_lines, String date_to_add, boolean date_time) {

View File

@@ -0,0 +1,87 @@
/*
Ticker.cpp - esp8266 library that calls functions periodically
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stddef.h>
#include <stdint.h>
#include "c_types.h"
#include "eagle_soc.h"
#include "ets_sys.h"
#include "osapi.h"
static const int ONCE = 0;
static const int REPEAT = 1;
#include "Ticker.h"
Ticker::Ticker()
: _timer(nullptr)
{
}
Ticker::~Ticker()
{
detach();
}
void Ticker::_attach_ms(uint32_t milliseconds, bool repeat, callback_with_arg_t callback, uint32_t arg)
{
if (_timer)
{
os_timer_disarm(_timer);
}
else
{
_timer = new ETSTimer;
}
os_timer_setfn(_timer, reinterpret_cast<ETSTimerFunc*>(callback), reinterpret_cast<void*>(arg));
os_timer_arm(_timer, milliseconds, (repeat)?REPEAT:ONCE);
}
void Ticker::detach()
{
if (!_timer)
return;
os_timer_disarm(_timer);
delete _timer;
_timer = nullptr;
_callback_function = nullptr;
}
bool Ticker::active() const
{
return (bool)_timer;
}
void Ticker::_static_callback(void* arg)
{
Ticker* _this = (Ticker*)arg;
if (_this == nullptr)
{
return;
}
if (_this->_callback_function)
{
_this->_callback_function();
}
}

View File

@@ -0,0 +1,136 @@
/*
Ticker.h - esp8266 library that calls functions periodically
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef TICKER_H
#define TICKER_H
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include <functional>
#include <Schedule.h>
extern "C" {
typedef struct _ETSTIMER_ ETSTimer;
}
class Ticker
{
public:
Ticker();
~Ticker();
typedef void (*callback_t)(void);
typedef void (*callback_with_arg_t)(void*);
typedef std::function<void(void)> callback_function_t;
void attach_scheduled(float seconds, callback_function_t callback)
{
attach(seconds,std::bind(schedule_function, callback));
}
void attach(float seconds, callback_function_t callback)
{
_callback_function = callback;
attach(seconds, _static_callback, (void*)this);
}
void attach_ms_scheduled(uint32_t milliseconds, callback_function_t callback)
{
attach_ms(milliseconds, std::bind(schedule_function, callback));
}
void attach_ms(uint32_t milliseconds, callback_function_t callback)
{
_callback_function = callback;
attach_ms(milliseconds, _static_callback, (void*)this);
}
template<typename TArg>
void attach(float seconds, void (*callback)(TArg), TArg arg)
{
static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach() callback argument size must be <= 4 bytes");
// C-cast serves two purposes:
// static_cast for smaller integer types,
// reinterpret_cast + const_cast for pointer types
uint32_t arg32 = (uint32_t)arg;
_attach_ms(seconds * 1000, true, reinterpret_cast<callback_with_arg_t>(callback), arg32);
}
template<typename TArg>
void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)
{
static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach_ms() callback argument size must be <= 4 bytes");
uint32_t arg32 = (uint32_t)arg;
_attach_ms(milliseconds, true, reinterpret_cast<callback_with_arg_t>(callback), arg32);
}
void once_scheduled(float seconds, callback_function_t callback)
{
once(seconds, std::bind(schedule_function, callback));
}
void once(float seconds, callback_function_t callback)
{
_callback_function = callback;
once(seconds, _static_callback, (void*)this);
}
void once_ms_scheduled(uint32_t milliseconds, callback_function_t callback)
{
once_ms(milliseconds, std::bind(schedule_function, callback));
}
void once_ms(uint32_t milliseconds, callback_function_t callback)
{
_callback_function = callback;
once_ms(milliseconds, _static_callback, (void*)this);
}
template<typename TArg>
void once(float seconds, void (*callback)(TArg), TArg arg)
{
static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach() callback argument size must be <= 4 bytes");
uint32_t arg32 = (uint32_t)(arg);
_attach_ms(seconds * 1000, false, reinterpret_cast<callback_with_arg_t>(callback), arg32);
}
template<typename TArg>
void once_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg)
{
static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach_ms() callback argument size must be <= 4 bytes");
uint32_t arg32 = (uint32_t)(arg);
_attach_ms(milliseconds, false, reinterpret_cast<callback_with_arg_t>(callback), arg32);
}
void detach();
bool active() const;
protected:
void _attach_ms(uint32_t milliseconds, bool repeat, callback_with_arg_t callback, uint32_t arg);
static void _static_callback (void* arg);
protected:
ETSTimer* _timer;
callback_function_t _callback_function = nullptr;
};
#endif//TICKER_H

View File

@@ -0,0 +1,45 @@
/*
Basic Ticker usage
Ticker is an object that will call a given function with a certain period.
Each Ticker calls one function. You can have as many Tickers as you like,
memory being the only limitation.
A function may be attached to a ticker and detached from the ticker.
There are two variants of the attach function: attach and attach_ms.
The first one takes period in seconds, the second one in milliseconds.
The built-in LED will be blinking.
*/
#include <Ticker.h>
Ticker flipper;
int count = 0;
void flip() {
int state = digitalRead(LED_BUILTIN); // get the current state of GPIO1 pin
digitalWrite(LED_BUILTIN, !state); // set pin to the opposite state
++count;
// when the counter reaches a certain value, start blinking like crazy
if (count == 20) {
flipper.attach(0.1, flip);
}
// when the counter reaches yet another value, stop blinking
else if (count == 120) {
flipper.detach();
}
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
// flip the pin every 0.3s
flipper.attach(0.3, flip);
}
void loop() {
}

View File

@@ -0,0 +1,64 @@
#include "Arduino.h"
#include "Ticker.h"
#define LED1 2
#define LED2 4
#define LED3 12
#define LED4 14
#define LED5 15
class ExampleClass {
public:
ExampleClass(int pin, int duration) : _pin(pin), _duration(duration) {
pinMode(_pin, OUTPUT);
_myTicker.attach_ms(_duration, std::bind(&ExampleClass::classBlink, this));
}
~ExampleClass() {};
int _pin, _duration;
Ticker _myTicker;
void classBlink() {
digitalWrite(_pin, !digitalRead(_pin));
}
};
void staticBlink() {
digitalWrite(LED2, !digitalRead(LED2));
}
void scheduledBlink() {
digitalWrite(LED3, !digitalRead(LED2));
}
void parameterBlink(int p) {
digitalWrite(p, !digitalRead(p));
}
Ticker staticTicker;
Ticker scheduledTicker;
Ticker parameterTicker;
Ticker lambdaTicker;
ExampleClass example(LED1, 100);
void setup() {
pinMode(LED2, OUTPUT);
staticTicker.attach_ms(100, staticBlink);
pinMode(LED3, OUTPUT);
scheduledTicker.attach_ms_scheduled(100, scheduledBlink);
pinMode(LED4, OUTPUT);
parameterTicker.attach_ms(100, std::bind(parameterBlink, LED4));
pinMode(LED5, OUTPUT);
lambdaTicker.attach_ms(100, []() {
digitalWrite(LED5, !digitalRead(LED5));
});
}
void loop() {
}

View File

@@ -0,0 +1,35 @@
/*
Passing paramters to Ticker callbacks
Apart from void(void) functions, the Ticker library supports
functions taking one argument. This argument's size has to be less or
equal to 4 bytes (so char, short, int, float, void*, char* types will do).
This sample runs two tickers that both call one callback function,
but with different arguments.
The built-in LED will be pulsing.
*/
#include <Ticker.h>
Ticker tickerSetHigh;
Ticker tickerSetLow;
void setPin(int state) {
digitalWrite(LED_BUILTIN, state);
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(1, LOW);
// every 25 ms, call setPin(0)
tickerSetLow.attach_ms(25, setPin, 0);
// every 26 ms, call setPin(1)
tickerSetHigh.attach_ms(26, setPin, 1);
}
void loop() {
}

View File

@@ -0,0 +1,29 @@
#######################################
# Syntax Coloring Map For Wire
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
#######################################
# Methods and Functions (KEYWORD2)
#######################################
attach KEYWORD2
attach_ms KEYWORD2
once KEYWORD2
once_ms KEYWORD2
detach KEYWORD2
active KEYWORD2
#######################################
# Instances (KEYWORD2)
#######################################
Ticker KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View File

@@ -0,0 +1,10 @@
name=Ticker
version=1.0
author=Ivan Grokhtokov <ivan@esp8266.com>
maintainer=Ivan Grokhtokov <ivan@esp8266.com>
sentence=Allows to call functions with a given interval.
paragraph=
category=Timing
url=
architectures=esp8266
dot_a_linkage=true

View File

@@ -1,46 +1,62 @@
void initUpgrade() {
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest * request) {
#ifdef ESP32
new_version = getURL("http://91.204.228.124:1100/update/esp32/version.txt");
#endif
#ifdef ESP8266
//new_version = getURL("http://91.204.228.124:1100/update/esp8266/version.txt");
#endif
start_check_version = true;
Serial.println("[i] Last firmware version: ");
Serial.print(new_version);
Serial.print("[i] Last firmware version: ");
Serial.println(last_version);
String tmp = "{}";
if (new_version != "error") {
if (new_version == firmware_version) {
if (!flash_1mb) {
if (last_version != "") {
if (last_version != "error") {
if (last_version == firmware_version) {
jsonWrite(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Последняя версия прошивки уже установлена.");
jsonWrite(tmp, "class", "pop-up");
} else {
upgrade_flag = true;
jsonWrite(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Идет обновление прошивки... После завершения устройство перезагрузится.");
jsonWrite(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Идет обновление прошивки... После завершения устройство перезагрузится. Подождите одну минуту!!!");
jsonWrite(tmp, "class", "pop-up");
}
} else {
jsonWrite(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Ошибка... Cервер не найден. Попробуйте позже...");
jsonWrite(tmp, "class", "pop-up");
}
} else {
jsonWrite(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Нажмите на кнопку \"обновить прошивку\" повторно...");
jsonWrite(tmp, "class", "pop-up");
}
} else {
jsonWrite(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>Обновление по воздуху не поддерживается, модуль имеет меньше 4 мб памяти...");
jsonWrite(tmp, "class", "pop-up");
}
request->send(200, "text/text", tmp);
});
}
void handle_get_url() {
if (start_check_version) {
start_check_version = false;
#ifdef ESP32
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
}
}
void upgrade_firmware() {
String scenario_for_update;
String config_for_update;
String configSetup_for_update;
scenario_for_update = readFile("firmware.scenario.txt", 2048);
config_for_update = readFile("firmware.config.txt", 2048);
scenario_for_update = readFile("firmware.scenario.txt", 3072);
config_for_update = readFile("firmware.config.txt", 3072);
configSetup_for_update = configSetup;
Serial.println("Start upgrade SPIFFS, please wait...");
WiFiClient client_for_upgrade;
#ifdef ESP32
@@ -63,19 +79,19 @@ void upgrade_firmware() {
Serial.println("Start upgrade BUILD, please wait...");
#ifdef ESP32
httpUpdate.rebootOnUpdate(true);
//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);
//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) {
Serial.println("BUILD upgrade done!");
Serial.println("Restart ESP....");
} else {
//upgrade_status(t_httpUpdate_return ret);
ESP.restart();
}
}
}

View File

@@ -41,7 +41,7 @@ void Web_server_init() {
server.addHandler(&ws);
events.onConnect([](AsyncEventSourceClient * client) {
client->send("hello!", NULL, millis(), 1000);
//!!!client->send("hello!", NULL, millis(), 1000);
});
server.addHandler(&events);
@@ -144,14 +144,22 @@ void Web_server_init() {
server.on("/config.setup.json", HTTP_GET, [](AsyncWebServerRequest * request) {
request->send(200, "application/json", configSetup);
});
// ------------------Выполнение команды из запроса
server.on("/cmd", HTTP_GET, [](AsyncWebServerRequest * request) { //http://192.168.88.45/cmd?command=rel%201%201
String com = request->getParam("command")->value();
Serial.println(com);
order_loop += com + ",";
request->send(200, "text/text", "OK"); // отправляем ответ о выполнении
});
}
//========================================WS=========================================================================================
#ifdef WS_enable
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) {
Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
client->printf(configJson.c_str(), client->id());
client->ping();
client->printf(json.c_str(), client->id());
//client->ping();
} else if (type == WS_EVT_DISCONNECT) {
Serial.printf("ws[%s][%u] disconnect\n", server->url(), client->id());
} else if (type == WS_EVT_ERROR) {

View File

@@ -47,6 +47,7 @@ void WIFI_init() {
// Попытка подключения к точке доступа
WiFi.mode(WIFI_STA);
// WiFi.mode(WIFI_NONE_SLEEP);
byte tries = 20;
String _ssid = jsonRead(configSetup, "ssid");
@@ -107,6 +108,7 @@ bool StartAPMode() {
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
jsonWrite(configJson, "ip", myIP.toString());
if (jsonReadtoInt(optionJson, "pass_status") != 1) {
ts.add(ROUTER_SEARCHING, 10 * 1000, [&](void*) {
@@ -147,14 +149,14 @@ boolean RouterFind(String ssid) {
} else {
Serial.print(i);
Serial.print(")");
Serial.print(ssid);
Serial.print("<=>");
//Serial.print(ssid);
//Serial.print("<=>");
if (i == n) {
Serial.print(WiFi.SSID(i));
Serial.println("; ");
} else {
Serial.print(WiFi.SSID(i));
Serial.print("; ");
Serial.println("; ");
}
}
}
@@ -162,3 +164,41 @@ boolean RouterFind(String ssid) {
return false;
}
}
/*
String scanWIFI() {
uint8_t n = WiFi.scanNetworks();
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
JsonArray& networks = json.createNestedArray("networks");
for (uint8_t i = 0; i < n; i++) {
JsonObject& data = networks.createNestedObject();
String ssidMy = WiFi.SSID(i);
data["ssid"] = ssidMy;
data["pass"] = (WiFi.encryptionType(i) == ENC_TYPE_NONE) ? "" : "*";
int8_t dbm = WiFi.RSSI(i);
data["dbm"] = dbm;
if (ssidMy == jsonRead(configSetup, "ssid")) {
jsonWrite(configJson, "dbm", dbm);
}
}
String root;
json.printTo(root);
return root;
}
*/
/*
{
"type":"wifi",
"title":"{{LangWiFi1}}",
"name":"ssid",
"state":"{{ssid}}",
"pattern":".{1,}"
},
{
"type":"password",
"title":"{{LangPass}}",
"name":"ssidPass",
"state":"{{ssidPass}}",
"pattern":".{8,}"
},
*/

View File

@@ -1 +0,0 @@
{"SSDP":"MODULES","chipID":"905542-1458415","ssidAP":"WiFi","passwordAP":"","ssid":"rise","password":"hostel3333","timezone":3,"mqttServer":"m12.cloudmqtt.com","mqttPort":14053,"mqttUser":"lbscvzuj","mqttPass":"bLxlveOgaF8F","scenario":"1","timers":"0","pushingbox_id":"v7C133E426B0C69E","web_login":"admin","web_pass":"admin"}

View File

@@ -1 +1,18 @@
{"SSDP":"MODULES","chipID":"905542-1458415","ssidAP":"WiFi","passwordAP":"","ssid":"your_ssid","password":"your_pass","timezone":3,"mqttServer":"","mqttPort":0,"mqttUser":"","mqttPass":"","scenario":"1","timers":"0","pushingbox_id":"","web_login":"admin","web_pass":"admin"}
{
"SSDP": "MODULES",
"chipID": "",
"ssidAP": "WiFi",
"passwordAP": "",
"ssid": "your_ssid",
"password": "your_password",
"timezone": 3,
"mqttServer": "",
"mqttPort": 0,
"mqttPrefix": "/IoTmanager",
"mqttUser": "",
"mqttPass": "",
"scenario": "1",
"pushingbox_id": "",
"web_login": "admin",
"web_pass": "admin"
}

View File

@@ -3,22 +3,4 @@ button 2 13 Прихожая Реле 0 2
button 3 14 Кухня Реле 0 3
pwm 1 3 Яркость#коредор: Реле 1023 4
pwm 2 4 Яркость#ванная: Реле 510 5
//---------------------------------------------------------------------
analog 0 Аналоговый#вход,#% Датчики progress-round 1 1024 1 1024 6
inputDigit digit1 При#скольки#включить? Датчики 10 7
inputDigit digit2 При#скольки#выключить? Датчики 0 8
button 4 na Нагреватель Датчики 0 9
//---------------------------------------------------------------------
button 5 na Вкл#обратный#таймер Таймеры 0 16
inputDigit digit3 Через#сколько#секунд#включить? Таймеры 5 17
button 6 na Включится#по#таймеру Таймеры 0 18
inputTime time1 Во#сколько#включить? Таймеры 20-30-00 19
button 7 5 Включится#по#таймеру Таймеры 0 20
//---------------------------------------------------------------------
switch 1 0 20
text 1 Вход: Охрана 20
textSet 1 не#обнаружено-time
button 8 na Сбросить Охрана 0 21
//---------------------------------------------------------------------
button 9 scenario Вкл#выкл#все#сценарии Сценарии 1 23
button 10 line1,line2, Вкл#выкл#выбранные#сценарии Сценарии 1 24

View File

@@ -8,26 +8,3 @@ buttonSet 2 0
buttonSet 3 0
pwmSet 2 0
end
analog > digit1
buttonSet 4 1
end
analog < digit2
buttonSet 4 0
end
button5 = 1
timerStart 1 digit3 sec
end
timer1 = 0
buttonSet 6 1
end
timenow = time1
buttonSet 7 1
end
switch1 = 1
textSet 1 обнаружено#движение-time
push Внимание обнаружено#движение!
end
button8 = 1
textSet 1 не#обнаружено-time
buttonSet 8 0
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

@@ -1,10 +1,8 @@
{
"configs": [
"/config.live.json",
"/config.setup.json",
"/config.option.json"
],
"class": "col-sm-offset-1 col-sm-10",
"content": [
@@ -28,7 +26,6 @@
{
"type": "hr"
},
{
"type": "dropdown",
"name": "help-url",
@@ -36,22 +33,23 @@
"style": "display:inline",
"title": {
"#": "Выбирите то, во что Вы хотите превратить ESP <span class=\"caret\"></span>",
"/relay":"Вкл. выкл. локального реле",
"/relay_timer":"Вкл. выкл. локального реле в определенное время",
"/relay_countdown":"Вкл. выкл. локального реле на определенный период времени",
"/relay_several":"Вкл. выкл. нескольких локальных реле кнопкой в приложении",
"/relay_switch":"Вкл. выкл. локального реле физической кнопкой (кнопка так же дублируется в приложении)",
"/relay_button_remote":"Вкл. выкл. нескольких удаленных реле кнопкой в приложении (нужно указать Device ID)",
"/relay_switch_remote":"Вкл. выкл. нескольких удаленных реле физической кнопкой (нужно указать Device ID)",
"/pwm":"Широтно импульсная модуляция",
"/dht11":"Сенсор DHT11",
"/dht22":"Сенсор DHT22, DHT33, DHT44, AM2302, RHT03",
"/analog":"Аналоговый сенсор",
"/dallas":"Сенсор DS18B20",
"/termostat":"Термостат на DS18B20 с переключением в ручной режим",
"/level":"Контроль уровня в баке на сенсорах: JSN-SR04T, HC-SR04, HY-SRF05 (управление насосом)",
"/moution_relay":"Датчик движения включающий свет",
"/moution_security":"Охранный датчик движения",
"/relay": "1.Вкл. выкл. локального реле",
"/relay_timer": "2.Вкл. выкл. локального реле в определенное время",
"/relay_countdown": "3.Вкл. выкл. локального реле на определенный период времени",
"/relay_several": "4.Вкл. выкл. нескольких локальных реле кнопкой в приложении",
"/relay_switch": "5.Вкл. выкл. локального реле физической кнопкой (кнопка так же дублируется в приложении)",
"/relay_button_remote": "6.Вкл. выкл. нескольких удаленных реле кнопкой в приложении (нужно указать Device ID)",
"/relay_switch_remote": "7.Вкл. выкл. нескольких удаленных реле физической кнопкой (нужно указать Device ID)",
"/pwm": "8.Широтно импульсная модуляция",
"/dht11": "9.Сенсор DHT11",
"/dht22": "10.Сенсор DHT22, DHT33, DHT44, AM2302, RHT03",
"/analog": "11.Аналоговый сенсор",
"/dallas": "12.Сенсор DS18B20",
"/termostat": "13.Термостат на DS18B20 с переключением в ручной режим",
"/level": "14.Контроль уровня в баке на сенсорах: JSN-SR04T, HC-SR04, HY-SRF05 (управление насосом)",
"/moution_relay": "15.Датчик движения включающий свет",
"/moution_security": "16.Охранный датчик движения",
"/stepper": "17.Система управления шаговыми двигателями на основе драйвера A4988 (открытие закрытие штор)",
"/default": "Настройки по умолчанию"
}
},
@@ -69,8 +67,8 @@
},
{
"type": "link",
"title": "Инструкция",
"action": "https://github.com/DmitryBorisenko33/esp8266_iot-manager_modules_firmware/wiki/Instruction",
"title": "Подробная инструкция",
"action": "https://github.com/DmitryBorisenko33/esp32-esp8266_iot-manager_modules_firmware/wiki/Instruction",
"class": "btn btn-block btn-primary"
},
{

Binary file not shown.

View File

@@ -1,572 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>ESP Editor</title>
<style type="text/css" media="screen">
.contextMenu{z-index:300;position:absolute;left:5px;border:1px solid #444;background-color:#f5f5f5;display:none;box-shadow:0 0 10px rgba(0,0,0,.4);font-size:12px;font-family:sans-serif;font-weight:bold}
.contextMenu ul{list-style:none;top:0;left:0;margin:0;padding:0}
.contextMenu li{position:relative;min-width:60px;cursor:pointer}
.contextMenu span{color:#444;display:inline-block;padding:6px}
.contextMenu li:hover{background:#444}
.contextMenu li:hover span{color:#EEE}
.css-treeview ul,.css-treeview li{padding:0;margin:0;list-style:none}
.css-treeview input{position:absolute;opacity:0}
.css-treeview{font:normal 11px Verdana,Arial,Sans-serif;-moz-user-select:none;-webkit-user-select:none;user-select:none}
.css-treeview span{color:#00f;cursor:pointer}
.css-treeview span:hover{text-decoration:underline}
.css-treeview input+label+ul{margin:0 0 0 22px}
.css-treeview input ~ ul{display:none}
.css-treeview label,.css-treeview label::before{cursor:pointer}
.css-treeview input:disabled+label{cursor:default;opacity:.6}
.css-treeview input:checked:not(:disabled) ~ ul{display:block}
.css-treeview label,.css-treeview label::before{background:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAACgCAYAAAAFOewUAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAApxJREFUeNrslM1u00AQgGdthyalFFOK+ClIIKQKyqUVQvTEE3DmAhLwAhU8QZoH4A2Q2gMSFace4MCtJ8SPBFwAkRuiHKpA6sRN/Lu7zG5i14kctaUqRGhGXnu9O/Pt7MzsMiklvF+9t2kWTDvyIrAsA0aKRRi1T0C/hJ4LUbt5/8rNpWVlp8RSr9J40b48fxFaTQ9+ft8EZ6MJYb0Ok+dnYGpmPgXwKIAvLx8vYXc5GdMAQJgQEkpjRTh36TS2U+DWW/D17WuYgm8pwJyY1npZsZKOxImOV1I/h4+O6vEg5GCZBpgmA6hX8wHKUHDRBXQYicQ4rlc3Tf0VMs8DHBS864F2YFspjgUYjKX/Az3gsdQd2eeBHwmdGWXHcgBGSkZXOXohcEXebRoQcAgjqediNY+AVyu3Z3sAKqfKoGMsewBeEIOPgQxxPJIjcGH6qtL/0AdADzKGnuuD+2tLK7Q8DhHHbOBW+KEzcHLuYc82MkEUekLiwuvVH+guQBQzOG4XdAb8EOcRcqQvDkY2iCLuxECJ43JobMXoutqGgDa2T7UqLKwt9KRyuxKVByqVXXqIoCCUCAqhUOioTWC7G4TQEOD0APy2/7G2Xpu1J4+lxeQ4TXBbITDpoVelRN/BVFbwu5oMMJUBhoXy5tmdRcMwymP2OLQaLjx9/vnBo6V3K6izATmSnMa0Dq7ferIohJhr1p01zrlz49rZF4OMs8JkX23vVQzYp+wbYGV/KpXKjvspl8tsIKCrMNAYFxj2GKS5ZWxg4ewKsJfaGMIY5KXqPz8LBBj6+yDvVP79+yDp/9F9oIx3OisHWwe7Oal0HxCAAAQgAAEIQAACEIAABCAAAQhAAAIQgAAEIAABCEAAAhCAAAQgwD8E/BZgAP0qhKj3rXO7AAAAAElFTkSuQmCC") no-repeat}
.css-treeview label,.css-treeview span,.css-treeview label::before{display:inline-block;height:16px;line-height:16px;vertical-align:middle}
.css-treeview label{background-position:18px 0}
.css-treeview label::before{content:"";width:16px;margin:0 22px 0 0;vertical-align:middle;background-position:0 -32px}
.css-treeview input:checked+label::before{background-position:0 -16px}
@media screen and (-webkit-min-device-pixel-ratio:0){.css-treeview{-webkit-animation:webkit-adjacent-element-selector-bugfix infinite 1s}@-webkit-keyframes webkit-adjacent-element-selector-bugfix{from{padding:0}to{padding:0}}}
#uploader{position:absolute;top:0;right:0;left:0;height:28px;line-height:24px;padding-left:10px;background-color:#444;color:#EEE}#tree{position:absolute;top:28px;bottom:0;left:0;width:200px;padding:8px}
#editor,#preview{position:absolute;top:28px;right:0;bottom:0;left:200px}
#preview{background-color:#EEE;padding:5px}
</style>
<script>
var urlXXX = 'http://192.168.211.181';//bolt
if (window.location.search.substring(1).split("=")[1]) {
urlXXX = 'http://'+window.location.search.substring(1).split("=")[1];
} else {
urlXXX = 'http://'+window.location.hostname;
}
function createFileUploader(element, tree, editor){
var xmlHttp;
var input = document.createElement("input");
input.type = "file";
input.multiple = false;
input.name = "data";
document.getElementById(element).appendChild(input);
var path = document.createElement("input");
path.id = "upload-path";
path.type = "text";
path.name = "path";
path.defaultValue = "/";
document.getElementById(element).appendChild(path);
var button = document.createElement("button");
button.innerHTML = 'Upload';
document.getElementById(element).appendChild(button);
var mkdir = document.createElement("button");
mkdir.innerHTML = 'MkDir';
document.getElementById(element).appendChild(mkdir);
var mkfile = document.createElement("button");
mkfile.innerHTML = 'MkFile';
document.getElementById(element).appendChild(mkfile);
function httpPostProcessRequest(){
if (xmlHttp.readyState == 4){
if(xmlHttp.status != 200) alert("ERROR["+xmlHttp.status+"]: "+xmlHttp.responseText);
else {
tree.refreshPath(path.value);
}
}
}
function createPath(p){
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = httpPostProcessRequest;
var formData = new FormData();
formData.append("path", p);
xmlHttp.open("PUT", urlXXX+"/edit");
xmlHttp.send(formData);
}
mkfile.onclick = function(e){
if(path.value.indexOf(".") === -1) return;
createPath(path.value);
editor.loadUrl(path.value);
};
mkdir.onclick = function(e){
if(path.value.length < 2) return;
var dir = path.value
if(dir.indexOf(".") !== -1){
if(dir.lastIndexOf("/") === 0) return;
dir = dir.substring(0, dir.lastIndexOf("/"));
}
createPath(dir);
};
button.onclick = function(e){
if(input.files.length === 0){
return;
}
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = httpPostProcessRequest;
var formData = new FormData();
formData.append("data", input.files[0], path.value);
xmlHttp.open("POST", urlXXX+"/edit");
xmlHttp.send(formData);
}
input.onchange = function(e){
if(input.files.length === 0) return;
var filename = input.files[0].name;
var ext = /(?:\.([^.]+))?$/.exec(filename)[1];
var name = /(.*)\.[^.]+$/.exec(filename)[1];
if(typeof name !== undefined){
//1197 bolt if(name.length > 8) name = name.substring(0, 8);
filename = name;
}
if(typeof ext !== undefined){
if(ext === "html") ext = "htm";
else if(ext === "jpeg") ext = "jpg";
filename = filename + "." + ext;
}
if(path.value === "/" || path.value.lastIndexOf("/") === 0){
path.value = "/"+filename;
} else {
path.value = path.value.substring(0, path.value.lastIndexOf("/")+1)+filename;
}
}
}
function createTree(element, editor){
var preview = document.getElementById("preview");
var treeRoot = document.createElement("div");
treeRoot.className = "css-treeview";
document.getElementById(element).appendChild(treeRoot);
function loadDownload(path){
document.getElementById('download-frame').src = path+"?download=true";
}
function loadPreview(path){
document.getElementById("editor").style.display = "none";
preview.style.display = "block";
preview.innerHTML = '<img src="'+ urlXXX +path+'" style="max-width:100%; max-height:100%; margin:auto; display:block;" />';
}
function fillFolderMenu(el, path){
var list = document.createElement("ul");
el.appendChild(list);
var action = document.createElement("li");
list.appendChild(action);
var isChecked = document.getElementById(path).checked;
var expnd = document.createElement("li");
list.appendChild(expnd);
if(isChecked){
expnd.innerHTML = "<span>Collapse</span>";
expnd.onclick = function(e){
document.getElementById(path).checked = false;
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
var refrsh = document.createElement("li");
list.appendChild(refrsh);
refrsh.innerHTML = "<span>Refresh</span>";
refrsh.onclick = function(e){
var leaf = document.getElementById(path).parentNode;
if(leaf.childNodes.length == 3) leaf.removeChild(leaf.childNodes[2]);
httpGet(leaf, path);
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
} else {
expnd.innerHTML = "<span>Expand</span>";
expnd.onclick = function(e){
document.getElementById(path).checked = true;
var leaf = document.getElementById(path).parentNode;
if(leaf.childNodes.length == 3) leaf.removeChild(leaf.childNodes[2]);
httpGet(leaf, path);
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
}
var upload = document.createElement("li");
list.appendChild(upload);
upload.innerHTML = "<span>Upload</span>";
upload.onclick = function(e){
var pathEl = document.getElementById("upload-path");
if(pathEl){
var subPath = pathEl.value;
if(subPath.lastIndexOf("/") < 1) pathEl.value = path+subPath;
else pathEl.value = path.substring(subPath.lastIndexOf("/"))+subPath;
}
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
var delFile = document.createElement("li");
list.appendChild(delFile);
delFile.innerHTML = "<span>Delete</span>";
delFile.onclick = function(e){
httpDelete(path);
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
}
function fillFileMenu(el, path){
var list = document.createElement("ul");
el.appendChild(list);
var action = document.createElement("li");
list.appendChild(action);
if(isTextFile(path)){
action.innerHTML = "<span>Edit</span>";
action.onclick = function(e){
editor.loadUrl(path);
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
} else if(isImageFile(path)){
action.innerHTML = "<span>Preview</span>";
action.onclick = function(e){
loadPreview(path);
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
}
var download = document.createElement("li");
list.appendChild(download);
download.innerHTML = "<span>Download</span>";
download.onclick = function(e){
loadDownload(path);
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
var delFile = document.createElement("li");
list.appendChild(delFile);
delFile.innerHTML = "<span>Delete</span>";
delFile.onclick = function(e){
httpDelete(path);
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(el);
};
}
function showContextMenu(e, path, isfile){
var divContext = document.createElement("div");
var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;
var left = e.clientX + scrollLeft;
var top = e.clientY + scrollTop;
divContext.className = 'contextMenu';
divContext.style.display = 'block';
divContext.style.left = left + 'px';
divContext.style.top = top + 'px';
if(isfile) fillFileMenu(divContext, path);
else fillFolderMenu(divContext, path);
document.body.appendChild(divContext);
var width = divContext.offsetWidth;
var height = divContext.offsetHeight;
divContext.onmouseout = function(e){
if(e.clientX < left || e.clientX > (left + width) || e.clientY < top || e.clientY > (top + height)){
if(document.body.getElementsByClassName('contextMenu').length > 0) document.body.removeChild(divContext);
}
};
}
function createTreeLeaf(path, name, size){
var leaf = document.createElement("li");
leaf.id = (((path == "/")?"":path)+"/"+name).toLowerCase();
var label = document.createElement("span");
label.textContent = name.toLowerCase();
leaf.appendChild(label);
leaf.onclick = function(e){
if(isTextFile(leaf.id)){
editor.loadUrl(leaf.id);
} else if(isImageFile(leaf.id)){
loadPreview(leaf.id);
}
};
leaf.oncontextmenu = function(e){
e.preventDefault();
e.stopPropagation();
showContextMenu(e, leaf.id, true);
};
return leaf;
}
function createTreeBranch(path, name, disabled){
var leaf = document.createElement("li");
var check = document.createElement("input");
check.type = "checkbox";
check.id = (((path == "/")?"":path)+"/"+name).toLowerCase();
if(typeof disabled !== "undefined" && disabled) check.disabled = "disabled";
leaf.appendChild(check);
var label = document.createElement("label");
label.for = check.id;
label.textContent = name.toLowerCase();
leaf.appendChild(label);
check.onchange = function(e){
if(check.checked){
if(leaf.childNodes.length == 3) leaf.removeChild(leaf.childNodes[2]);
httpGet(leaf, check.id);
}
};
label.onclick = function(e){
if(!check.checked){
check.checked = true;
if(leaf.childNodes.length == 3) leaf.removeChild(leaf.childNodes[2]);
httpGet(leaf, check.id);
} else {
check.checked = false;
}
};
leaf.oncontextmenu = function(e){
e.preventDefault();
e.stopPropagation();
showContextMenu(e, check.id, false);
}
return leaf;
}
function addList(parent, path, items){
var list = document.createElement("ul");
parent.appendChild(list);
var ll = items.length;
//Сортировка файлов
items.sort(function(a,b){return (a.name < b.name) ? 1 : ((b.name < a.name) ? -1 : 0);});
for(var i = 0; i < ll; i++){
var item = items[i];
var itemEl;
if(item.type === "file"){
itemEl = createTreeLeaf(path, item.name, item.size);
} else {
itemEl = createTreeBranch(path, item.name);
}
list.appendChild(itemEl);
}
}
function isTextFile(path){
var ext = /(?:\.([^.]+))?$/.exec(path)[1];
if(typeof ext !== undefined){
switch(ext){
case "txt":
case "htm":
case "html":
case "js":
case "json":
case "c":
case "h":
case "cpp":
case "css":
case "xml":
return true;
}
}
return false;
}
function isImageFile(path){
var ext = /(?:\.([^.]+))?$/.exec(path)[1];
if(typeof ext !== undefined){
switch(ext){
case "png":
case "jpg":
case "gif":
case "ico":
return true;
}
}
return false;
}
this.refreshPath = function(path){
if(path.lastIndexOf('/') < 1){
path = '/';
treeRoot.removeChild(treeRoot.childNodes[0]);
httpGet(treeRoot, "/");
} else {
path = path.substring(0, path.lastIndexOf('/'));
var leaf = document.getElementById(path).parentNode;
if(leaf.childNodes.length == 3) leaf.removeChild(leaf.childNodes[2]);
httpGet(leaf, path);
}
};
function delCb(path){
return function(){
if (xmlHttp.readyState == 4){
if(xmlHttp.status != 200){
alert("ERROR["+xmlHttp.status+"]: "+xmlHttp.responseText);
} else {
if(path.lastIndexOf('/') < 1){
path = '/';
treeRoot.removeChild(treeRoot.childNodes[0]);
httpGet(treeRoot, "/");
} else {
path = path.substring(0, path.lastIndexOf('/'));
var leaf = document.getElementById(path).parentNode;
if(leaf.childNodes.length == 3) leaf.removeChild(leaf.childNodes[2]);
httpGet(leaf, path);
}
}
}
}
}
function httpDelete(filename){
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = delCb(filename);
var formData = new FormData();
formData.append("path", filename);
xmlHttp.open("DELETE", urlXXX+"/edit");
xmlHttp.send(formData);
}
function getCb(parent, path){
return function(){
if (xmlHttp.readyState == 4){
//clear loading
if(xmlHttp.status == 200) addList(parent, path, JSON.parse(xmlHttp.responseText));
}
}
}
function httpGet(parent, path){
xmlHttp = new XMLHttpRequest(parent, path);
xmlHttp.onreadystatechange = getCb(parent, path);
//Для отключения кэша random() иначе будут старые данные
xmlHttp.open("GET", urlXXX+"/edit?list=" + path +"&rand="+Math.random(), true);
xmlHttp.send(null);
//start loading
}
httpGet(treeRoot, "/");
return this;
}
function createEditor(element, file, lang, theme, type){
function getLangFromFilename(filename){
var lang = "plain";
var ext = /(?:\.([^.]+))?$/.exec(filename)[1];
if(typeof ext !== undefined){
switch(ext){
case "txt": lang = "plain"; break;
case "htm": lang = "html"; break;
case "js": lang = "javascript"; break;
case "c": lang = "c_cpp"; break;
case "cpp": lang = "c_cpp"; break;
case "css":
case "scss":
case "php":
case "html":
case "json":
case "xml":
lang = ext;
}
}
return lang;
}
if(typeof file === "undefined") file = "/index.htm";
if(typeof lang === "undefined"){
lang = getLangFromFilename(file);
}
if(typeof theme === "undefined") theme = "textmate";
if(typeof type === "undefined"){
type = "text/"+lang;
if(lang === "c_cpp") type = "text/plain";
}
var xmlHttp = null;
var editor = ace.edit(element);
//post
function httpPostProcessRequest(){
if (xmlHttp.readyState == 4){
if(xmlHttp.status != 200) alert("ERROR["+xmlHttp.status+"]: "+xmlHttp.responseText);
}
}
function httpPost(filename, data, type){
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = httpPostProcessRequest;
var formData = new FormData();
formData.append("data", new Blob([data], { type: type }), filename);
xmlHttp.open("POST", urlXXX + "/edit");
xmlHttp.send(formData);
}
//get
function httpGetProcessRequest(){
if (xmlHttp.readyState == 4){
document.getElementById("preview").style.display = "none";
document.getElementById("editor").style.display = "block";
if(xmlHttp.status == 200) editor.setValue(xmlHttp.responseText);
else editor.setValue("");
editor.clearSelection();
}
}
function httpGet(theUrl){
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = httpGetProcessRequest;
if (theUrl.indexOf("/") == 0)
theUrl = urlXXX + theUrl;//bolt
xmlHttp.open("GET", theUrl+"?rand="+Math.random(), true);
xmlHttp.send(null);
}
if(lang !== "plain") editor.getSession().setMode("ace/mode/"+lang);
editor.setTheme("ace/theme/"+theme);
editor.$blockScrolling = Infinity;
editor.getSession().setUseSoftTabs(true);
editor.getSession().setTabSize(2);
editor.setHighlightActiveLine(true);
editor.setShowPrintMargin(false);
editor.commands.addCommand({
name: 'saveCommand',
bindKey: {win: 'Ctrl-S', mac: 'Command-S'},
exec: function(editor) {
httpPost(file, editor.getValue()+"", type);
},
readOnly: false
});
editor.commands.addCommand({
name: 'undoCommand',
bindKey: {win: 'Ctrl-Z', mac: 'Command-Z'},
exec: function(editor) {
editor.getSession().getUndoManager().undo(false);
},
readOnly: false
});
editor.commands.addCommand({
name: 'redoCommand',
bindKey: {win: 'Ctrl-Shift-Z', mac: 'Command-Shift-Z'},
exec: function(editor) {
editor.getSession().getUndoManager().redo(false);
},
readOnly: false
});
httpGet(file);
editor.loadUrl = function(filename){
file = filename;
lang = getLangFromFilename(file);
type = "text/"+lang;
if(lang !== "plain") editor.getSession().setMode("ace/mode/"+lang);
httpGet(file);
}
return editor;
}
function onBodyLoad(){
var vars = {};
// var s = "http://192.168.211.180/edit/index.htm";
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
// var parts = s.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
if (typeof vars.url !== "undefined" && vars.url != "")
urlXXX = "http://" + vars.url;/**/
var editor = createEditor("editor", vars.file, vars.lang, vars.theme);
var tree = createTree("tree", editor);
createFileUploader("uploader", tree, editor);
};
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
(function() {
window.require(["ace/ace"], function(a) {
a && a.config.init(true);
if (!window.ace)
window.ace = a;
for (var key in a) if (a.hasOwnProperty(key))
window.ace[key] = a[key];
});
})();
</script>
</head>
<body onload="onBodyLoad();">
<div id="uploader"></div>
<div id="tree"></div>
<div id="editor"></div>
<div id="preview" style="display:none;"></div>
<iframe id=download-frame style='display:none;'></iframe>
</body>
</html>

Binary file not shown.

View File

@@ -3,22 +3,4 @@ button 2 13 Прихожая Реле 0 2
button 3 14 Кухня Реле 0 3
pwm 1 3 Яркость#коредор: Реле 1023 4
pwm 2 4 Яркость#ванная: Реле 510 5
//---------------------------------------------------------------------
analog 0 Аналоговый#вход,#% Датчики progress-round 1 1024 1 1024 6
inputDigit digit1 При#скольки#включить? Датчики 10 7
inputDigit digit2 При#скольки#выключить? Датчики 0 8
button 4 na Нагреватель Датчики 0 9
//---------------------------------------------------------------------
button 5 na Вкл#обратный#таймер Таймеры 0 16
inputDigit digit3 Через#сколько#секунд#включить? Таймеры 5 17
button 6 na Включится#по#таймеру Таймеры 0 18
inputTime time1 Во#сколько#включить? Таймеры 20-30-00 19
button 7 5 Включится#по#таймеру Таймеры 0 20
//---------------------------------------------------------------------
switch 1 0 20
text 1 Вход: Охрана 20
textSet 1 не#обнаружено-time
button 8 na Сбросить Охрана 0 21
//---------------------------------------------------------------------
button 9 scenario Вкл#выкл#все#сценарии Сценарии 1 23
button 10 line1,line2, Вкл#выкл#выбранные#сценарии Сценарии 1 24

View File

@@ -8,26 +8,3 @@ buttonSet 2 0
buttonSet 3 0
pwmSet 2 0
end
analog > digit1
buttonSet 4 1
end
analog < digit2
buttonSet 4 0
end
button5 = 1
timerStart 1 digit3 sec
end
timer1 = 0
buttonSet 6 1
end
timenow = time1
buttonSet 7 1
end
switch1 = 1
textSet 1 обнаружено#движение-time
push Внимание обнаружено#движение!
end
button8 = 1
textSet 1 не#обнаружено-time
buttonSet 8 0
end

View File

@@ -1,75 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<!--
Web Developer: Renats Kevrels (ex. Zozula)
Site: http://www.onclick.lv
Contact: info [at] onclick.lv
Skype: renat2985
Twitter: @Ramzies
Facebook: http://www.facebook.com/renat2985
GitHub: https://github.com/renat2985
From: Latvia, Valmiera
-->
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
<script defer src="js/build.chart.js?v07.04.2018" charset="utf-8"></script>
<!-- <link rel="stylesheet" type="text/css" href="css/chartist.min.css">
<script src="js/chartist.min.js" charset="utf-8"></script>
<script type="text/javascript" src="js/chart.js"></script> -->
<link rel="stylesheet" type="text/css" href="css/build.css?v07.04.2018">
<!-- <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css"> -->
<script defer type="text/javascript" src="js/function.js?v07.04.2018"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script type="text/javascript">
var jsonResponse;
//function selectTextareaLine(tarea,lineNum) {
// lineNum--;
// var lines = tarea.value.split("\n");
// var startPos = 0, endPos = tarea.value.length;
// for(var x = 0; x < lines.length; x++) {
// if(x == lineNum) {break;}
// startPos += (lines[x].length+1);
// }
// var endPos = lines[lineNum].length+startPos;
// if(typeof(tarea.selectionStart) != "undefined") {
// tarea.focus();
// tarea.selectionStart = startPos;
// tarea.selectionEnd = endPos;
// return true;
// }
// return false;
//}
window.onload = function() {
setContent('first');
}
</script>
</head>
<body>
<div class="container loader-bg">
<ul id="url-content" class="hidden" onclick="document.getElementById('content').style.zIndex=0;"></ul>
<div id="headers"></div>
<div class="row hidden" id="container_column">
<h1 id="title"></h1>
<div id="content" onclick="this.style.zIndex=10"></div>
</div>
<div id="footer"></div>
<div id="edit-content" class="hidden" onclick="document.getElementById('content').style.zIndex=0;">
<a target="_blank" style="position:fixed;right:0;color:#000;" href="https://github.com/tretyakovsa/Sonoff_WiFi_switch/wiki/%D0%92%D0%BE%D0%B7%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%D1%81%D1%82%D0%B8-page.htm%3F*" title="Github wiki"><i class="help-img"></i>wiki</a>
<textarea class="form-control" onkeyup="isValidJson(this.value,'edit-json')" spellcheck="false" id="edit-json"></textarea>
<div id="error-json"></div>
<div class="btn-group btn-block">
<input class="btn btn-success" style="width:40%" id="edit-view" onclick="setContent('edit');this.value='Loading...';html('url-content', ' ');" value="View" type="button">
<input class="btn btn-danger" style="width:40%" id="edit-save" onclick="var urlPages=window.location.search.substring(1).split('&')[0];httpDelete('/'+urlPages+'.json.gz');send_request_edit(this, val('edit-json'),(urlPages?urlPages:'index')+'.json');toggle('edit-content');toggle('url-content');" value="Save" type="button">
<a class="btn btn-info" style="width:20%" href="#" id="download-json" download="" title="Save to PC"><i class="download-img"></i></a>
</div>
</div>
</div>
</body>
</html>

Binary file not shown.

View File

@@ -29,7 +29,10 @@
},
{
"type": "h4",
"title": "SPIFFS version: 2.3"
"title": "SPIFFS version: 2.3.1"
},
{
"type": "hr"
},
{
"type": "link",
@@ -64,7 +67,7 @@
{
"type": "h3",
"name": "my-block",
"style":"position:fixed;top:30%;left:50%;width:400px;margin-left:-200px;text-align:center;",
"style": "position:fixed;top:50%;left:50%;width:400px;margin-left:-200px;text-align:center;",
"class": "hidden"
},
{

Binary file not shown.

Binary file not shown.

View File

@@ -31,12 +31,22 @@
},
{
"type": "h4",
"title": "User name:"
"title": "Prefix:"
},
{
"type": "input",
"title": "",
"name":"3",
"state": "{{mqttPrefix}}"
},
{
"type": "h4",
"title": "User name:"
},
{
"type": "input",
"title": "",
"name":"4",
"state": "{{mqttUser}}"
},
{
@@ -46,7 +56,7 @@
{
"type": "input",
"title": "",
"name":"4",
"name":"5",
"state": "{{mqttPass}}"
},
{
@@ -58,7 +68,14 @@
{
"type": "button",
"title":"Сохранить",
"action": "mqttSave?mqttServer=[[1]]&mqttPort=[[2]]&mqttUser=[[3]]&mqttPass=[[4]]",
"action": "mqttSave?mqttServer=[[1]]&mqttPort=[[2]]&mqttPrefix=[[3]]&mqttUser=[[4]]&mqttPass=[[5]]",
"class": "btn btn-block btn-success",
"style": "width:100%;display:inline"
},
{
"type": "button",
"title":"Проверить соединение с MQTT",
"action": "mqttCheck",
"response":"[[my-block]]",
"class": "btn btn-block btn-success",
"style": "width:100%;display:inline"

View File

@@ -1,92 +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": "{{SSDP}}",
"class":"alert-warning"
},
{
"type": "h4",
"title": "Host name:"
},
{
"type": "input",
"title": "",
"name":"1",
"state": "{{pushHost}}"
},
{
"type": "h4",
"title": "Port:"
},
{
"type": "input",
"title": "",
"name":"2",
"state": "{{pushPort}}"
},
{
"type": "h4",
"title": "Fingerprint:"
},
{
"type": "input",
"title": "",
"name":"3",
"state": "{{pushFingerprint}}"
},
{
"type": "h4",
"title": "Access Token:"
},
{
"type": "input",
"title": "",
"name":"4",
"state": "{{pushAccessToken}}"
},
{
"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":"Сохранить и проверить соединение",
"action": "pushDate?pushHost=[[1]]&pushPort=[[2]]&pushFingerprint=[[3]]&pushAccessToken=[[4]]",
"response":"[[my-block]]",
"class": "btn btn-block btn-success",
"style": "width:100%;display:inline"
},
{
"type": "hr"
},
{
"type": "checkbox",
"name":"start-push",
"title": "Отправлять push при включении устройства",
"action": "startPush?status=[[start-push]]",
"state": "{{startPush}}"
},
{
"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": "/page.htm?index",
"class": "btn btn-block btn-danger btn-sm"
}
]
}

2
data/robots.txt Normal file
View File

@@ -0,0 +1,2 @@
User-agent: *
Disallow: *

View File

@@ -53,8 +53,7 @@
"type": "password",
"title": "Введите пароль",
"name":"ssidPass",
"state": "{{password}}",
"pattern": ".{8,20}"
"state": "{{password}}"
},
{
"type": "button",

View File

@@ -0,0 +1,18 @@
{
"SSDP": "MODULES",
"chipID": "",
"ssidAP": "WiFi",
"passwordAP": "",
"ssid": "rise",
"password": "hostel3333",
"timezone": 3,
"mqttServer": "m12.cloudmqtt.com",
"mqttPort": 14053,
"mqttPrefix": "/IoTmanager",
"mqttUser": "lbscvzuj",
"mqttPass": "bLxlveOgaF8F",
"scenario": "1",
"pushingbox_id": "",
"web_login": "admin",
"web_pass": "admin"
}

BIN
date_excess/edit.htm.gz Normal file

Binary file not shown.

View File

@@ -8,6 +8,8 @@ void setup() {
//--------------------------------------------------------------
SPIFFS.begin();
configSetup = readFile("config.json", 4096);
configSetup.replace(" ", "");
configSetup.replace("\r\n", "");
Serial.println(configSetup);
jsonWrite(configJson, "SSDP", jsonRead(configSetup, "SSDP"));
jsonWrite(configJson, "lang", jsonRead(configSetup, "lang"));
@@ -27,7 +29,7 @@ void setup() {
jsonWrite(configSetup, "firmware_version", firmware_version);
prex = prefix + "/" + chipID;
prex = jsonRead(configSetup, "mqttPrefix") + "/" + chipID;
Serial.println(chipID);
//--------------------------------------------------------------
CMD_init();
@@ -39,44 +41,50 @@ void setup() {
WIFI_init();
Serial.println("[V] WIFI_init");
//--------------------------------------------------------------
Web_server_init();
Serial.println("[V] Web_server_init");
//--------------------------------------------------------------
Time_Init();
Serial.println("[V] Time_Init");
//--------------------------------------------------------------
MQTT_init();
Serial.println("[V] MQTT_init");
//--------------------------------------------------------------
Push_init();
Serial.println("[V] Push_init");
//--------------------------------------------------------------
statistics();
Serial.println("[V] statistics");
statistics_init();
Serial.println("[V] statistics_init");
//--------------------------------------------------------------
initUpgrade();
Serial.println("[V] initUpgrade");
//--------------------------------------------------------------
Web_server_init();
Serial.println("[V] Web_server_init");
//--------------------------------------------------------------
MQTT_init();
Serial.println("[V] MQTT_init");
//--------------------------------------------------------------
Time_Init();
Serial.println("[V] Time_Init");
//--------------------------------------------------------------
Push_init();
Serial.println("[V] Push_init");
//--------------------------------------------------------------
//SSDP_init();
//Serial.println("[V] SSDP_init");
//--------------------------------------------------------------
Serial.print("[i] Date compiling: ");
Serial.println(DATE_COMPILING);
getMemoryLoad("[i] After loading");
#ifdef ESP8266
new_version = getURL("http://91.204.228.124:1100/update/esp8266/version.txt");
last_version = getURL("http://91.204.228.124:1100/update/esp8266/version.txt");
#endif
#ifdef ESP32
new_version = getURL("http://91.204.228.124:1100/update/esp32/version.txt");
last_version = getURL("http://91.204.228.124:1100/update/esp32/version.txt");
#endif
jsonWrite(configSetup, "last_version", last_version);
Serial.print("[i] Last firmware version: ");
Serial.println(new_version);
Serial.println(last_version);
ts.add(TEST, statistics_update, [&](void*) {
statistics();
}, nullptr, false);
just_load = false;
}
void loop() {
#ifdef OTA_enable
@@ -89,6 +97,9 @@ void loop() {
handleMQTT();
handle_connection();
handle_get_url();
handleCMD_loop();
handleButton();
handleScenario();

116
main.ino
View File

@@ -229,7 +229,7 @@ String readFileString(String fileName, String found)
void sendCONFIG(String topik, String widgetConfig, String key, String date) {
yield();
topik = prefix + "/" + chipID + "/" + topik + "/status";
topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/status";
String outer = "{\"widgetConfig\":";
String inner = "{\"";
inner = inner + key;
@@ -275,6 +275,118 @@ void getMemoryLoad(String text) {
Serial.println(String(memory_remain) + " k bytes");
}
//esp32 full memory = 362868 k bytes
//esp8266 full memory = 53312 k bytes
//===================================================================
/*
void web_print (String text) {
if (WiFi.status() == WL_CONNECTED) {
jsonWrite(json, "test1", jsonRead(json, "test2"));
jsonWrite(json, "test2", jsonRead(json, "test3"));
jsonWrite(json, "test3", jsonRead(json, "test4"));
jsonWrite(json, "test4", jsonRead(json, "test5"));
jsonWrite(json, "test5", jsonRead(json, "test6"));
jsonWrite(json, "test6", GetTime() + " " + text);
ws.textAll(json);
}
}
*/
//===================================================================
/*
"socket": [
"ws://{{ip}}/ws"
],
*/
//===================================================================
/*
{
"type": "h4",
"title": "('{{build2}}'=='{{firmware_version}}'?'NEW':'OLD')"
},
*/
//===================================================================
/*
{
"type": "hr"
},
{
"type": "h6",
"title": "{{test1}}"
},
{
"type": "h6",
"title": "{{test2}}"
},
{
"type": "h6",
"title": "{{test3}}"
},
{
"type": "h6",
"title": "{{test4}}"
},
{
"type": "h6",
"title": "{{test5}}"
},
{
"type": "h6",
"title": "{{test6}}"
},
{
"type": "hr"
},
*/
//===================================================================
/*
String getResetReason(uint8_t core) {
int reason = rtc_get_reset_reason(core);
switch (reason) {
case 1 : return "Power on"; break; //Vbat power on reset
case 3 : return "Software reset digital core"; break; //Software reset digital core
case 4 : return "Legacy watch dog reset digital core"; break; //Legacy watch dog reset digital core
case 5 : return "Deep Sleep reset digital core"; break; //Deep Sleep reset digital core
case 6 : return "Reset by SLC module, reset digital core"; break; //Reset by SLC module, reset digital core
case 7 : return "Timer Group0 Watch dog reset digital core"; break; //Timer Group0 Watch dog reset digital core
case 8 : return "Timer Group1 Watch dog reset digital core"; break; //Timer Group1 Watch dog reset digital core
case 9 : return "RTC Watch dog Reset digital core"; break; //
case 10 : return "Instrusion tested to reset CPU"; break;
case 11 : return "Time Group reset CPU"; break;
case 12 : return "Software reset CPU"; break;
case 13 : return "RTC Watch dog Reset CPU"; break;
case 14 : return "for APP CPU, reseted by PRO CPU"; break;
case 15 : return "Reset when the vdd voltage is not stable"; break;
case 16 : return "RTC Watch dog reset digital core and rtc module"; break;
default : return "NO_MEAN";
}
}
String EspClass::getResetReason(void) {
char buff[32];
if (resetInfo.reason == REASON_DEFAULT_RST) { // normal startup by power on
strcpy_P(buff, PSTR("Power on"));
} else if (resetInfo.reason == REASON_WDT_RST) { // hardware watch dog reset
strcpy_P(buff, PSTR("Hardware Watchdog"));
} else if (resetInfo.reason == REASON_EXCEPTION_RST) { // exception reset, GPIO status wont change
strcpy_P(buff, PSTR("Exception"));
} else if (resetInfo.reason == REASON_SOFT_WDT_RST) { // software watch dog reset, GPIO status wont change
strcpy_P(buff, PSTR("Software Watchdog"));
} else if (resetInfo.reason == REASON_SOFT_RESTART) { // software restart ,system_restart , GPIO status wont change
strcpy_P(buff, PSTR("Software/System restart"));
} else if (resetInfo.reason == REASON_DEEP_SLEEP_AWAKE) { // wake up from deep-sleep
strcpy_P(buff, PSTR("Deep-Sleep Wake"));
} else if (resetInfo.reason == REASON_EXT_SYS_RST) { // external system reset
strcpy_P(buff, PSTR("External System"));
} else {
strcpy_P(buff, PSTR("Unknown"));
}
return String(buff);
}
*/

119
mqtt.ino
View File

@@ -1,50 +1,6 @@
//===============================================ИНИЦИАЛИЗАЦИЯ================================================
void MQTT_init() {
server.on("/mqttSave", HTTP_GET, [](AsyncWebServerRequest * request) {
if (request->hasArg("mqttServer")) {
jsonWrite(configSetup, "mqttServer", request->getParam("mqttServer")->value());
}
if (request->hasArg("mqttPort")) {
int port = (request->getParam("mqttPort")->value()).toInt();
jsonWrite(configSetup, "mqttPort", port);
}
if (request->hasArg("mqttUser")) {
jsonWrite(configSetup, "mqttUser", request->getParam("mqttUser")->value());
}
if (request->hasArg("mqttPass")) {
jsonWrite(configSetup, "mqttPass", request->getParam("mqttPass")->value());
}
saveConfig();
client.disconnect();
MQTT_Connecting();
/*
int i = 0;
while (!client.connected() && i <= 25) {
delay(1000);
Serial.print(".");
i++;
}
*/
String tmp = "{}";
jsonWrite(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + stateMQTT());
jsonWrite(tmp, "class", "pop-up");
#ifdef ESP8266
request->send(200, "text/text", "ok");
#endif
#ifdef ESP32
request->send(200, "text/text", tmp);
#endif
});
//проверка подключения к серверу
ts.add(WIFI_MQTT_CONNECTION_CHECK, wifi_mqtt_reconnecting, [&](void*) {
up_time();
if (WiFi.status() == WL_CONNECTED) {
@@ -53,7 +9,7 @@ void MQTT_init() {
Serial.println("[V] MQTT-ok");
} else {
MQTT_Connecting();
mqtt_lost_error++;
if (!just_load) mqtt_lost_error++;
}
} else {
Serial.println("[E] Lost WiFi connection");
@@ -62,6 +18,45 @@ void MQTT_init() {
StartAPMode();
}
}, nullptr, true);
server.on("/mqttSave", HTTP_GET, [](AsyncWebServerRequest * request) {
if (request->hasArg("mqttServer")) {
jsonWrite(configSetup, "mqttServer", request->getParam("mqttServer")->value());
}
if (request->hasArg("mqttPort")) {
int port = (request->getParam("mqttPort")->value()).toInt();
jsonWrite(configSetup, "mqttPort", port);
}
if (request->hasArg("mqttPrefix")) {
jsonWrite(configSetup, "mqttPrefix", request->getParam("mqttPrefix")->value());
}
if (request->hasArg("mqttUser")) {
jsonWrite(configSetup, "mqttUser", request->getParam("mqttUser")->value());
}
if (request->hasArg("mqttPass")) {
jsonWrite(configSetup, "mqttPass", request->getParam("mqttPass")->value());
}
saveConfig();
start_connecting_to_mqtt = true;
request->send(200, "text/text", "ok");
});
server.on("/mqttCheck", HTTP_GET, [](AsyncWebServerRequest * request) {
String tmp = "{}";
jsonWrite(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + stateMQTT());
jsonWrite(tmp, "class", "pop-up");
request->send(200, "text/text", tmp);
});
}
void handle_connection() {
if (start_connecting_to_mqtt) {
start_connecting_to_mqtt = false;
client.disconnect();
MQTT_Connecting();
}
}
//================================================ОБНОВЛЕНИЕ====================================================
@@ -77,9 +72,7 @@ void handleMQTT() {
boolean MQTT_Connecting() {
String mqtt_server = jsonRead(configSetup, "mqttServer");
if ((mqtt_server != "")) {
static boolean first = true;
if (!first) Serial.println("[E] Lost MQTT connection, start reconnecting");
first = false;
Serial.println("[E] Lost MQTT connection, start reconnecting");
//ssl//espClient.setCACert(local_root_ca1);
client.setServer(mqtt_server.c_str(), jsonReadtoInt(configSetup, "mqttPort"));
if (WiFi.status() == WL_CONNECTED) {
@@ -88,14 +81,10 @@ boolean MQTT_Connecting() {
if (client.connect(chipID.c_str(), jsonRead(configSetup, "mqttUser").c_str(), jsonRead(configSetup, "mqttPass").c_str())) {
Serial.println("[V] MQTT connected");
client.setCallback(callback);
client.subscribe(prefix.c_str()); // Для приема получения HELLOW и подтверждения связи
client.subscribe((prefix + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control
client.subscribe((prefix + "/" + chipID + "/order").c_str()); // Подписываемся на топики order
//client.subscribe((prefix + "/" + chipID + "/test").c_str()); //Для приема получения work и подтверждения связи (для приложения mqtt IOT MQTT Panel)
client.subscribe((prefix + "/ids").c_str()); // Подписываемся на топики ids
sendMQTT("test", "work");
client.subscribe(jsonRead(configSetup, "mqttPrefix").c_str()); // Для приема получения HELLOW и подтверждения связи
client.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/+/control").c_str()); // Подписываемся на топики control
client.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/order").c_str()); // Подписываемся на топики order
Serial.println("[V] Callback set, subscribe done");
//if (out_date_send) outcoming_date(); //отправляем данные в виджеты
return true;
} else {
Serial.println("[E] try again in " + String(wifi_mqtt_reconnecting / 1000) + " sec");
@@ -146,17 +135,17 @@ void outcoming_date() {
sendAllWigets();
sendAllData();
if (flagLoggingAnalog) sendLogData("log.analog.txt", "loganalog");
if (flagLoggingPh) sendLogData("log.ph.txt", "logph");
if (flagLoggingDallas) sendLogData("log.dallas.txt", "logdallas");
if (flagLoggingLevel) sendLogData("log.level.txt", "loglevel");
// if (flagLoggingAnalog) sendLogData("log.analog.txt", "loganalog");
// if (flagLoggingPh) sendLogData("log.ph.txt", "logph");
// if (flagLoggingDallas) sendLogData("log.dallas.txt", "logdallas");
// if (flagLoggingLevel) sendLogData("log.level.txt", "loglevel");
Serial.println("[V] Sending all date to iot manager completed");
}
//======================================CONFIG==================================================
boolean sendMQTT(String end_of_topik, String data) {
String topik = prefix + "/" + chipID + "/" + end_of_topik;
String topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + end_of_topik;
boolean send_status = client.beginPublish(topik.c_str(), data.length(), false);
client.print(data);
client.endPublish();
@@ -164,14 +153,14 @@ boolean sendMQTT(String end_of_topik, String data) {
}
//======================================STATUS==================================================
void sendSTATUS(String topik, String state) {
topik = prefix + "/" + chipID + "/" + topik + "/" + "status";
topik = jsonRead(configSetup, "mqttPrefix") + "/" + chipID + "/" + topik + "/" + "status";
String json_ = "{}";
jsonWrite(json_, "status", state);
int send_status = client.publish (topik.c_str(), json_.c_str(), false);
}
//======================================CONTROL==================================================
void sendCONTROL(String id, String topik, String state) {
String all_line = prefix + "/" + id + "/" + topik + "/control";
String all_line = jsonRead(configSetup, "mqttPrefix") + "/" + id + "/" + topik + "/control";
int send_status = client.publish (all_line.c_str(), state.c_str(), false);
}
@@ -232,7 +221,7 @@ void sendLogData(String file, String topic) {
while (log_date.length() != 0) {
String tmp = selectToMarker (log_date, "\n");
//sendSTATUS(topic, selectFromMarkerToMarker(tmp, " ", 2));
sendSTATUS(topic, selectFromMarkerToMarker(tmp, " ", 2));
if (tmp != "") sendSTATUS(topic, tmp);
log_date = deleteBeforeDelimiter(log_date, "\n");
@@ -278,7 +267,7 @@ String stateMQTT() {
String line_ = selectToMarker (all_text, "\n");
String id = selectFromMarkerToMarker(line_, " ", 4);
if (id != "not found") {
client.subscribe((prefix + "/" + id + "/+/status").c_str(), 0);
client.subscribe((jsonRead(configSetup, "mqttPrefix") + "/" + id + "/+/status").c_str(), 0);
Serial.println("subscribed to device, id: " + id);
}
all_text = deleteBeforeDelimiter(all_text, "\n");
@@ -298,7 +287,7 @@ String stateMQTT() {
String id = selectFromMarkerToMarker(line_, " ", 4);
if (id != "not found") {
//Serial.println();
Serial.println(client.publish ((prefix + "/" + id).c_str(), "CHECK", true));
Serial.println(client.publish ((jsonRead(configSetup, "mqttPrefix") + "/" + id).c_str(), "CHECK", true));
}
all_text = deleteBeforeDelimiter(all_text, "\n");

BIN
pictures/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

BIN
pictures/esp32_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

BIN
pictures/esp32_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

BIN
pictures/esp8266_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

BIN
pictures/esp8266_1mb_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

BIN
pictures/esp8266_1mb_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

BIN
pictures/esp8266_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

51
set.h
View File

@@ -1,6 +1,7 @@
String firmware_version = "2.3";
String new_version;
String firmware_version = "2.3.1";
boolean flash_1mb = true;
String last_version;
boolean start_check_version = false;
//#define OTA_enable
//#define MDNS_enable
@@ -8,7 +9,7 @@ String new_version;
#define TIME_COMPILING String(__TIME__)
#define DATE_COMPILING String(__DATE__)
//-----------------------------------------------------------------
#define wifi_mqtt_reconnecting 20000
//-----------------------------------------------------------------
#define analog_update_int 5000
@@ -24,7 +25,7 @@ String new_version;
#define dhtT_update_int 10000
#define dhtH_update_int 10000
#define dht_calculation_update_int 10000
#define statistics_update 1000 * 60 * 60 * 12
#define statistics_update 1000 * 60 * 60 * 4
//-----------------------------------------------------------------
@@ -32,9 +33,11 @@ String new_version;
#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESPAsyncTCP.h>
//#include <ESPAsyncTCP.h>
#ifdef MDNS_enable
#include <ESP8266mDNS.h>
#endif
//#include <ESP8266SSDP.h>
#include <ESP8266httpUpdate.h>
#include <ESP8266HTTPUpdateServer.h>
ESP8266HTTPUpdateServer httpUpdater;
@@ -49,15 +52,15 @@ ESP8266HTTPUpdateServer httpUpdater;
#endif
#include <AsyncTCP.h>
#include <analogWrite.h>
//#include <ESP32SSDP.h>
#include <HTTPUpdate.h>
#include <HTTPClient.h>
//HTTPClient http;
//#include <rom/rtc.h>
#endif
//==общие библиотеки и объекты==//
#include <Arduino.h>
#include "time.h"
#ifdef OTA_enable
#include <ArduinoOTA.h>
@@ -71,12 +74,16 @@ AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
#endif
AsyncEventSource events("/events");
//---------------------------------------------------------------
#include "time.h"
//---------------------------------------------------------------
#include <TickerScheduler.h>
TickerScheduler ts(30);
enum {ROUTER_SEARCHING, WIFI_MQTT_CONNECTION_CHECK, LEVEL, ANALOG_, DALLAS, DHTT, DHTH, DHTC, DHTP, DHTD, ANALOG_LOG, LEVEL_LOG, DALLAS_LOG, PH_LOG, CMD , TIMER_COUNTDOWN, TIMERS, TIME, TEST};
enum {ROUTER_SEARCHING, WIFI_MQTT_CONNECTION_CHECK, LEVEL, ANALOG_, DALLAS, DHTT, DHTH, DHTC, DHTP, DHTD, STEPPER1, STEPPER2, ANALOG_LOG, LEVEL_LOG, DALLAS_LOG, CMD, TIMER_COUNTDOWN, TIMERS, TIME, STATISTICS, TEST};
//---------------------------------------------------------------
//ssl//#include "dependencies/WiFiClientSecure/WiFiClientSecure.h" //using older WiFiClientSecure
//#include "Ticker_for_TickerScheduler/Ticker/Ticker.h"
//---------------------------------------------------------------
#include <PubSubClient.h>
WiFiClient espClient;
//ssl//WiFiClientSecure espClient;
@@ -101,21 +108,23 @@ DallasTemperature sensors;
#include "DHTesp.h"
DHTesp dht;
//----------------------------------------------------------------
#include "Adafruit_Si7021.h" //https://github.com/adafruit/Adafruit_Si7021
Adafruit_Si7021 sensor_Si7021 = Adafruit_Si7021();
//#include "Adafruit_Si7021.h" //https://github.com/adafruit/Adafruit_Si7021
//Adafruit_Si7021 sensor_Si7021 = Adafruit_Si7021();
//-----------------------------------------------------------------
boolean just_load = true;
const char* hostName = "IoT Manager";
String configSetup = "{}";
String configJson = "{}";
String configSetup = "{}"; //setup
String configJson = "{}"; //live
String optionJson = "{}";
String json = "{}";
String chipID = "";
String prefix = "/IoTmanager";
String prex;
String ids;
//boolean busy;
String all_vigets = "";
String scenario;
@@ -136,10 +145,10 @@ String current_time;
int scenario_line_status [] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int wifi_lost_error = 0;
int mqtt_lost_error = -1;
int mqtt_lost_error = 0;
String var;
boolean upgrade_flag = false;
boolean get_url_flag = false;
boolean start_connecting_to_mqtt = false;