Merge pull request #37 from IoTManagerProject/dev

Dev
This commit is contained in:
Dmitry Borisenko
2020-06-27 11:13:10 +02:00
committed by GitHub
18 changed files with 491 additions and 387 deletions

View File

@@ -4,12 +4,46 @@
#include "Utils/PrintMessage.h"
#include "TZ.h"
#include "sntp.h"
class Clock {
const char* MODULE = "Clock";
private:
Time_t _time_local;
Time_t _time_utc;
unsigned long _uptime;
unsigned long _unixtime;
int _timezone;
String _ntp;
bool _hasSynced;
bool _configured;
public:
Clock() : _timezone{0}, _hasSynced{false}, _configured{false} {}
Clock() : _uptime{0}, _timezone{0}, _ntp{""}, _hasSynced{false}, _configured{false} {};
void loop() {
unsigned long passed = millis_since(_uptime);
if (passed < ONE_SECOND_ms) {
return;
}
_uptime += passed;
// world time
time_t now = getSystemTime();
time_t estimated = _unixtime + (passed / ONE_SECOND_ms);
double drift = difftime(now, estimated);
if (drift > 1) {
// Обработать ситуации c дрифтом времени на значительные величины
}
// TODO сохранять время на флеше
_unixtime = now;
breakEpochToTime(_unixtime, _time_utc);
breakEpochToTime(_unixtime + getOffsetInSeconds(_timezone), _time_local);
}
bool hasSync() {
if (!_hasSynced) {
@@ -19,18 +53,26 @@ class Clock {
}
void setNtpPool(String ntp) {
_ntp = ntp;
if (!_ntp.equals(ntp)) {
_ntp = ntp;
_configured = false;
}
}
void setTimezone(int timezone) {
_timezone = timezone;
if (_timezone != timezone) {
_timezone = timezone;
_configured = false;
}
}
void startSync() {
if (!_configured) {
pm.info("sync to: " + _ntp + " time zone: " + String(_timezone));
pm.info("sync to: " + _ntp + " timezone: " + String(_timezone));
setupSntp();
_configured = true;
// лучше не ждать, проверим в следующий раз
return;
}
_hasSynced = hasTimeSynced();
if (_hasSynced) {
@@ -41,44 +83,69 @@ class Clock {
}
void setupSntp() {
int tzs = getOffsetInSeconds(_timezone);
int tzh = tzs / 3600;
tzs -= tzh * 3600;
int tzm = tzs / 60;
tzs -= tzm * 60;
char tzstr[64];
snprintf(tzstr, sizeof tzstr, "ESPUSER<%+d:%02d:%02d>", tzh, tzm, tzs);
pm.info(String(tzstr));
configTime(tzstr, _ntp.c_str());
}
// #ifdef ESP32
// uint8_t i = 0;
// struct tm timeinfo;
// while (!getLocalTime(&timeinfo) && i <= 4) {
// Serial.print(".");
// i++;
// delay(1000);
// }
// #endifr
bool hasTimeSynced() {
return getSystemTime() > 30000;
sntp_setservername(0, _ntp.c_str());
sntp_setservername(1, "ru.pool.ntp.org");
sntp_setservername(2, "pool.ntp.org");
sntp_stop();
sntp_set_timezone(0); // UTC time
sntp_init();
}
time_t getSystemTime() {
bool hasTimeSynced() const {
return _unixtime > MIN_DATETIME;
}
time_t getSystemTime() const {
timeval tv{0, 0};
timezone tz = timezone{getOffsetInMinutes(_timezone), 0};
timezone tz = timezone{0, 0};
time_t epoch = 0;
if (gettimeofday(&tv, &tz) != -1) {
_epoch = tv.tv_sec;
epoch = tv.tv_sec;
}
return _epoch;
return epoch;
}
private:
time_t _epoch;
int _timezone;
String _ntp;
bool _hasSynced;
bool _configured;
const String getTimeUnix() {
return String(_unixtime);
}
/*
* Локальное время "дд.ММ.гг"
*/
const String getDateDigitalFormated() {
char buf[32];
sprintf(buf, "%02d.%02d.%02d", _time_local.day_of_month, _time_local.month, _time_local.year);
return String(buf);
}
/*
* Локальное время "чч:мм:cc"
*/
const String getTime() {
char buf[32];
sprintf(buf, "%02d:%02d:%02d", _time_local.hour, _time_local.minute, _time_local.second);
return String(buf);
}
const String getTimeJson() {
char buf[32];
sprintf(buf, "%02d-%02d-%02d", _time_local.hour, _time_local.minute, _time_local.second);
return String(buf);
}
/*
* Локальное время "чч:мм"
*/
const String getTimeWOsec() {
char buf[32];
sprintf(buf, "%02d:%02d", _time_local.hour, _time_local.minute);
return String(buf);
}
/*
* Время с момента запуска "чч:мм:cc" далее "дд чч:мм"
*/
const String getUptime() {
return prettyMillis(_uptime);
}
};

View File

@@ -1,5 +1,18 @@
#pragma once
struct Time_t {
uint8_t second;
uint8_t minute;
uint8_t hour;
uint8_t day_of_week; // sunday is day 1
uint8_t day_of_month;
uint8_t month;
uint16_t day_of_year;
uint16_t year;
unsigned long days;
unsigned long valid;
};
enum TimerTask_t { WIFI_SCAN,
WIFI_MQTT_CONNECTION_CHECK,
SENSORS,

View File

@@ -14,7 +14,6 @@
#include "Bus/BusScanner.h"
#include "Errors.h"
#include "GyverFilters.h"
#include "UptimeInterval.h"
#include "Upgrade.h"
#include "Clock.h"
@@ -46,7 +45,7 @@ extern AsyncWebSocket ws;
//extern AsyncEventSource events;
#endif
extern Clock* rtc;
extern Clock* timeNow;
extern TickerScheduler ts;
@@ -128,7 +127,7 @@ extern int sensors_reading_map[15];
*/
// Cmd
extern void CMD_init();
extern void cmd_init();
extern void button();
extern void buttonSet();
extern void buttonChange();
@@ -162,12 +161,11 @@ extern void fileExecute(const String& filename);
extern void stringExecute(String& cmdStr);
// Init
extern void loadConfig();
extern void All_init();
extern void all_init();
extern void statistics_init();
extern void loadScenario();
extern void Device_init();
extern void prsets_init();
extern void up_time();
// Logging
extern void logging();
@@ -179,8 +177,10 @@ extern void choose_log_date_and_send();
extern void setChipId();
extern void saveConfig();
extern String getURL(const String& urls);
extern void do_check_fs();
extern void do_scan_bus();
extern void servo_();
extern void clock_init();
extern void setLedStatus(LedStatus_t);
@@ -252,7 +252,6 @@ extern void UDP_init();
extern void do_udp_data_parse();
extern void do_mqtt_send_settings_to_udp();
// iot_firmware
extern void addCommandLoop(const String& cmdStr);
extern void loopSerial();
extern void loopCmd();
@@ -267,5 +266,4 @@ extern void uptime_init();
// Web
extern void web_init();
extern void telemetry_init();
extern void telemetry_init();

View File

@@ -1,32 +0,0 @@
#pragma once
#include <Arduino.h>
class UptimeInterval {
public:
UptimeInterval(unsigned long interval, boolean postpone = true) : _next{0}, _interval{interval} {
reset(postpone);
}
boolean check() {
if (_next <= get()) {
_next += _interval;
return true;
}
return false;
}
void reset(bool postpone = true) {
_next = (postpone ? _uptime_seconds + _interval : _uptime_seconds);
}
static unsigned long get() {
unsigned long _uptime_seconds = millis() / 1000;
return _uptime_seconds;
};
static unsigned long _uptime_seconds;
private:
unsigned long _next, _interval;
};

View File

@@ -6,10 +6,10 @@ String jsonReadStr(String& json, String name);
int jsonReadInt(String& json, String name);
String jsonWriteStr(String& json, String name, String volume);
boolean jsonReadBool(String& json, String name);
String jsonWriteInt(String& json, String name, int volume);
String jsonWriteStr(String& json, String name, String value);
String jsonWriteFloat(String& json, String name, float volume);
String jsonWriteInt(String& json, String name, int value);
boolean jsonReadBool(String& json, String name);
String jsonWriteFloat(String& json, String name, float value);

View File

@@ -24,7 +24,7 @@ class PrintMessage {
private:
void print(const ErrorLevel_t level, const String& str) {
Serial.printf("%s [%s] [%s] %s\n", prettyMillis().c_str(), getErrorLevelStr(level).c_str(), _module, str.c_str());
Serial.printf("%s [%s] [%s] %s\n", prettyMillis(millis()).c_str(), getErrorLevelStr(level).c_str(), _module, str.c_str());
}
private:

View File

@@ -1,37 +1,15 @@
#pragma once
#ifdef ESP8266
#include <time.h>
#endif
#include <Arduino.h>
/*
* Получение текущего времени
*/
String getTime();
#include "CommonTypes.h"
/*
* Получаем время в формате linux gmt
*/
String getTimeUnix();
/*
* Параметр время
* @result результат
*/
boolean getUnixTimeStr(String&);
String getTimeWOsec();
/*
* Получение даты
*/
String getDate();
String getDateDigitalFormated();
int timeToMin(String Time);
const String prettyMillis(unsigned long time_ms = millis());
#define ONE_MINUTE_s 60
#define ONE_HOUR_m 60
#define ONE_HOUR_s 60 * ONE_MINUTE_s
#define LEAP_YEAR(Y) (((1970 + Y) > 0) && !((1970 + Y) % 4) && (((1970 + Y) % 100) || !((1970 + Y) % 400)))
#define MIN_DATETIME 1575158400
#define ONE_SECOND_ms 1000
/*
* Время (мс) прошедщее с @since
@@ -43,6 +21,31 @@ unsigned long millis_since(unsigned long sinse);
*/
unsigned long millis_passed(unsigned long start, unsigned long finish);
/*
* Форматиронное время интервала (мс)
* "чч:мм:cc",
* "дд чч:мм", если > 24 часов
*/
const String prettyMillis(unsigned long time_ms = millis());
/*
* Форматиронное время интервала (c)
* "чч:мм:cc",
* "дд чч:мм", если > 24 часов
*/
const String prettySeconds(unsigned long time_s);
/*
* Тайм зона в секундах
*/
int getOffsetInSeconds(int timezone);
/*
* Тайм зона в минутах
*/
int getOffsetInMinutes(int timezone);
/*
* Разбивает время на составляющие
*/
void breakEpochToTime(unsigned long epoch, Time_t& tm);

View File

@@ -15,7 +15,7 @@ SoftwareSerial *mySerial = nullptr;
void getData();
void CMD_init() {
void cmd_init() {
sCmd.addCommand("button", button);
sCmd.addCommand("buttonSet", buttonSet);
sCmd.addCommand("buttonChange", buttonChange);
@@ -100,8 +100,6 @@ void CMD_init() {
sCmd.addCommand("firmwareUpdate", firmwareUpdate);
sCmd.addCommand("firmwareVersion", firmwareVersion);
handle_time_init();
}
@@ -332,10 +330,8 @@ void timeSet() {
void handle_time_init() {
ts.add(
TIME, 1000, [&](void *) {
String tmp = getTime();
jsonWriteStr(configLiveJson, "time", tmp);
tmp.replace(":", "-");
jsonWriteStr(configLiveJson, "timenow", tmp);
jsonWriteStr(configLiveJson, "time", timeNow->getTime());
jsonWriteStr(configLiveJson, "timenow", timeNow->getTimeJson());
eventGen("timenow", "");
},
nullptr, true);
@@ -360,9 +356,9 @@ void textSet() {
if (text.indexOf("-time") >= 0) {
text.replace("-time", "");
text.replace("#", " ");
String time = getTime();
String time = timeNow->getTime();
time.replace(":", ".");
text = text + " " + getDateDigitalFormated() + " " + time;
text = text + " " + timeNow->getDateDigitalFormated() + " " + time;
}
jsonWriteStr(configLiveJson, "text" + number, text);

View File

@@ -5,7 +5,7 @@ AsyncWebSocket ws;
//AsyncEventSource events;
#endif
Clock* rtc;
Clock* timeNow;
TickerScheduler ts(TEST + 1);

View File

@@ -17,7 +17,7 @@ void loadConfig() {
Serial.println(configSetupJson);
}
void All_init() {
void all_init() {
Device_init();
loadScenario();
Timer_countdown_init();
@@ -90,11 +90,11 @@ void telemetry_init() {
}
void handle_uptime() {
jsonWriteStr(configSetupJson, "uptime", prettyMillis());
jsonWriteStr(configSetupJson, "uptime", timeNow->getUptime());
}
void handle_statistics() {
if (WiFi.status() == WL_CONNECTED) {
if (isNetworkActive()) {
String urls = "http://backup.privet.lv/visitors/?";
//-----------------------------------------------------------------
urls += WiFi.macAddress().c_str();
@@ -114,7 +114,6 @@ void handle_statistics() {
urls += "Power on";
#endif
urls += "&";
urls += "ver: ";
urls += String(FIRMWARE_VERSION);
String stat = getURL(urls);
}

View File

@@ -75,7 +75,7 @@ void logging() {
/*
* Удаление стрых данных и запись новых
*/
void deleteOldDate(const String filename, size_t max_lines_cnt, String date_to_add) {
void deleteOldDate(const String filename, size_t max_lines_cnt, String payload) {
String log_date = readFile(filename, 5120);
size_t lines_cnt = itemsCount(log_date, "\r\n");
@@ -88,13 +88,13 @@ void deleteOldDate(const String filename, size_t max_lines_cnt, String date_to_a
if (lines_cnt > max_lines_cnt) {
log_date = deleteBeforeDelimiter(log_date, "\r\n");
if (getTimeUnix() != "failed") {
log_date += getTimeUnix() + " " + date_to_add + "\r\n";
if (timeNow->hasTimeSynced()) {
log_date += timeNow->getTimeUnix() + " " + payload + "\r\n";
writeFile(filename, log_date);
}
} else {
if (getTimeUnix() != "failed") {
addFile(filename, getTimeUnix() + " " + date_to_add);
if (timeNow->hasTimeSynced()) {
addFile(filename, timeNow->getTimeUnix() + " " + payload);
}
}
}

View File

@@ -260,7 +260,7 @@ void publishState() {
String state = selectToMarkerLast(tmp, ":");
state.replace("\"", "");
if (topic != "name" && topic != "lang" && topic != "ip" && topic.indexOf("_in") < 0) {
if ((topic != "time") && (topic != "name") && (topic != "lang") && (topic != "ip") && (topic.indexOf("_in") < 0)) {
publishStatus(topic, state);
}
str = deleteBeforeDelimiter(str, ",");

View File

@@ -2,31 +2,31 @@
namespace Discovery {
static const char* json_is_defined = "is_defined";
static const char* jsonId = "id";
static const char* jsonBatt = "batt";
static const char* jsonLux = "lux";
static const char* jsonPres = "pres";
static const char* jsonFer = "fer";
static const char* jsonMoi = "moi";
static const char* jsonHum = "hum";
static const char* jsonTemp = "tem";
static const char* jsonStep = "steps";
static const char* jsonWeight = "weight";
static const char* jsonPresence = "presence";
static const char* jsonAltim = "altim";
static const char* jsonAltif = "altift";
static const char* jsonTempf = "tempf";
static const char* jsonMsg = "message";
static const char* jsonVal = "value";
static const char* jsonVolt = "volt";
static const char* jsonCurrent = "current";
static const char* jsonPower = "power";
static const char* jsonGpio = "gpio";
static const char* jsonFtcd = "ftcd";
static const char* jsonWm2 = "wattsm2";
static const char* jsonAdc = "adc";
static const char* jsonPa = "pa";
static const char json_is_defined[] = "is_defined";
static const char jsonId[] = "id";
static const char jsonBatt[] = "batt";
static const char jsonLux[] = "lux";
static const char jsonPres[] = "pres";
static const char jsonFer[] = "fer";
static const char jsonMoi[] = "moi";
static const char jsonHum[] = "hum";
static const char jsonTemp[] = "tem";
static const char jsonStep[] = "steps";
static const char jsonWeight[] = "weight";
static const char jsonPresence[] = "presence";
static const char jsonAltim[] = "altim";
static const char jsonAltif[] = "altift";
static const char jsonTempf[] = "tempf";
static const char jsonMsg[] = "message";
static const char jsonVal[] = "value";
static const char jsonVolt[] = "volt";
static const char jsonCurrent[] = "current";
static const char jsonPower[] = "power";
static const char jsonGpio[] = "gpio";
static const char jsonFtcd[] = "ftcd";
static const char jsonWm2[] = "wattsm2";
static const char jsonAdc[] = "adc";
static const char jsonPa[] = "pa";
const String getValueJson(const char* str) {
char buf[32];
@@ -35,16 +35,15 @@ const String getValueJson(const char* str) {
}
void createDiscovery(
char* unique_id,
const char* type, char* name, char* clazz,
char* value_template, char* payload_on, char* payload_off,
char* maasure_unit, int off_delay, char* has_payload, char* no_payload,
char* avail_topi, char* cmd_topic, char* state_topic, bool child) {
const char* type, const char* name, const char* clazz,
const char* value_template, const char* payload_on, const char* payload_off,
const char* maasure_unit, int off_delay, const char* has_payload, const char* no_payload,
const char* avail_topi, const char* cmd_topic, const char* state_topic, bool child) {
//const char* unique_id = getUniqueId(name).c_str();
}
void createADC(const char* name) {
createDiscovery(
(char*)getUniqueId(name).c_str(),
"Type", "Name", "Clazz",
"Value", "Payload", "NoPayload",
"Measure", 0, "HasPayload", "NoPayload",
@@ -53,7 +52,6 @@ void createADC(const char* name) {
void createSwitch(const char* name) {
createDiscovery(
(char*)getUniqueId(name).c_str(),
"Type", "Name", "Clazz",
"Value", "Payload", "NoPayload",
"Measure", 0, "HasPayload", "NoPayload",
@@ -65,14 +63,13 @@ void createSwitch(const char* name) {
// availability topic,
// device class,
// value template, payload on, payload off, unit of measurement
char* BMEsensor[6][8] = {
const char* BMEsensor[6][8] = {
{"sensor", "tempc", "bme", "temperature", "", "", "°C"}, //jsonTemp
{"sensor", "tempf", "bme", "temperature", "", "", "°F"}, //jsonTempf
{"sensor", "pa", "bme", "", "", "", "hPa"}, //jsonPa
{"sensor", "hum", "bme", "humidity", "", "", "%"}, // jsonHum
{"sensor", "altim", "bme", "", "", "", "m"}, //jsonAltim
{"sensor", "altift", "bme", "", "", "", "ft"} // jsonAltif
};
} // namespace Discovery

View File

@@ -2,86 +2,90 @@
static const char* MODULE = "Scen";
void loopScenario() {
bool enabled = jsonReadBool(configSetupJson, "scen");
if (enabled) {
if ((jsonReadStr(configOptionJson, "scenario_status") != "")) {
String str = scenario;
str += "\n";
str.replace("\r\n", "\n");
str.replace("\r", "\n");
size_t i = 0;
while (str.length()) {
String block = selectToMarker(str, "end");
if (!block.length()) {
return;
}
i++;
if (scenario_line_status[i] == 1) {
//выделяем первую строку самого сценария button1 = 1 (условие)
String condition = selectToMarker(block, "\n");
String param_name = selectFromMarkerToMarker(condition, " ", 0);
String order = jsonReadStr(configOptionJson, "scenario_status"); //читаем весь файл событий
String param = selectToMarker(order, ","); //читаем первое событие из файла событий
if (param_name == param) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку
String sign = selectFromMarkerToMarker(condition, " ", 1); //читаем знак (=)
String value = selectFromMarkerToMarker(condition, " ", 2); //читаем значение (1)
if (value.indexOf("digit") != -1) {
// value = add_set(value);
value = jsonReadStr(configLiveJson, value);
}
if (value.indexOf("time") != -1) {
// 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) {
block = deleteBeforeDelimiter(block, "\n"); //удаляем строку самого сценария оставляя только команды
stringExecute(block); //выполняем все команды
pm.info(condition + "'");
}
}
}
str = deleteBeforeDelimiter(str, "end\n"); //удаляем первый сценарий
//-----------------------------------------------------------------------------------------------------------------------
}
String tmp2 = jsonReadStr(configOptionJson, "scenario_status"); //читаем файл событий
tmp2 = deleteBeforeDelimiter(tmp2, ","); //удаляем выполненное событие
jsonWriteStr(configOptionJson, "scenario_status", tmp2); //записываем обновленный файл событий
i = 0;
}
}
boolean isScenarioEnabled() {
return jsonReadBool(configSetupJson, "scen") && jsonReadStr(configOptionJson, "scenario_status") != "";
}
//событие выглядит как имя плюс set плюс номер: button+Set+1
void eventGen(String event_name, String number) {
if (jsonReadStr(configSetupJson, "scen") == "1") {
String tmp = jsonReadStr(configOptionJson, "scenario_status"); //генерирование события
jsonWriteStr(configOptionJson, "scenario_status", tmp + event_name + number + ",");
void loopScenario() {
if (!isScenarioEnabled()) {
return;
}
String str = scenario;
str += "\n";
str.replace("\r\n", "\n");
str.replace("\r", "\n");
size_t i = 0;
while (str.length()) {
String block = selectToMarker(str, "end");
if (!block.length()) {
return;
}
i++;
if (scenario_line_status[i] == 1) {
//выделяем первую строку самого сценария button1 = 1 (условие)
String condition = selectToMarker(block, "\n");
String param_name = selectFromMarkerToMarker(condition, " ", 0);
String order = jsonReadStr(configOptionJson, "scenario_status"); //читаем весь файл событий
String param = selectToMarker(order, ","); //читаем первое событие из файла событий
if (param_name == param) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку
String sign = selectFromMarkerToMarker(condition, " ", 1); //читаем знак (=)
String value = selectFromMarkerToMarker(condition, " ", 2); //читаем значение (1)
if (value.indexOf("digit") != -1) {
// value = add_set(value);
value = jsonReadStr(configLiveJson, value);
}
if (value.indexOf("time") != -1) {
// 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) {
block = deleteBeforeDelimiter(block, "\n"); //удаляем строку самого сценария оставляя только команды
stringExecute(block); //выполняем все команды
pm.info(condition + "'");
}
}
}
str = deleteBeforeDelimiter(str, "end\n"); //удаляем первый сценарий
//-----------------------------------------------------------------------------------------------------------------------
}
String tmp2 = jsonReadStr(configOptionJson, "scenario_status"); //читаем файл событий
tmp2 = deleteBeforeDelimiter(tmp2, ","); //удаляем выполненное событие
jsonWriteStr(configOptionJson, "scenario_status", tmp2); //записываем обновленный файл событий
}
// событие: имя + Set + номер
// button+Set+1
void eventGen(String event_name, String number) {
if (!jsonReadBool(configSetupJson, "scen")) {
return;
}
// генерирование события
String tmp = jsonReadStr(configOptionJson, "scenario_status");
jsonWriteStr(configOptionJson, "scenario_status", tmp + event_name + number + ",");
}
String add_set(String str) {

View File

@@ -20,28 +20,28 @@ int jsonReadInt(String& json, String name) {
return root[name];
}
String jsonWriteStr(String& json, String name, String volume) {
String jsonWriteStr(String& json, String name, String value) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
root[name] = value;
json = "";
root.printTo(json);
return json;
}
String jsonWriteInt(String& json, String name, int volume) {
String jsonWriteInt(String& json, String name, int value) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
root[name] = value;
json = "";
root.printTo(json);
return json;
}
String jsonWriteFloat(String& json, String name, float volume) {
String jsonWriteFloat(String& json, String name, float value) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
root[name] = volume;
root[name] = value;
json = "";
root.printTo(json);
return json;

View File

@@ -1,114 +1,105 @@
#include "Utils\TimeUtils.h"
#include "Global.h"
#include "Utils\StringUtils.h"
#define ONE_MINUTE_s 60
#define ONE_HOUR_m 60
#define ONE_HOUR_s 60 * ONE_MINUTE_s
static const uint8_t days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static const char* week_days[7] = {"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"};
time_t t;
struct tm* tm;
static const char* wd[7] = {"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"};
String getTimeUnix() {
t = time(NULL);
tm = localtime(&t);
Serial.printf("%04d/%02d/%02d(%s) %02d:%02d:%02d\n",
tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, wd[tm->tm_wday],
tm->tm_hour, tm->tm_min, tm->tm_sec);
delay(1000);
time_t now = time(nullptr);
if (now < 30000) {
return "failed";
}
return String(now);
}
// String getTimeUnix() {
// time_t t;
// struct tm* tm;
boolean getUnixTimeStr(String& res) {
time_t now = time(nullptr);
res = String(now);
return now > 30000;
}
// t = time(NULL);
// tm = localtime(&t);
// Serial.printf("%04d/%02d/%02d(%s) %02d:%02d:%02d\n",
// tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, week_days[tm->tm_wday],
// tm->tm_hour, tm->tm_min, tm->tm_sec);
// delay(1000);
// time_t now = time(nullptr);
// if (now < 30000) {
// return "failed";
// }
// return String(now);
// }
String getTime() {
time_t now = time(nullptr);
int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
now = now + zone;
String Time = ""; // Строка для результатов времени
Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
int i = Time.indexOf(":"); //Ишем позицию первого символа :
Time = Time.substring(i - 2, i + 6); // Выделяем из строки 2 символа перед символом : и 6 символов после
return Time; // Возврашаем полученное время
}
// String getTime() {
// time_t now = time(nullptr);
// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
// now = now + zone;
// String Time = ""; // Строка для результатов времени
// Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
// int i = Time.indexOf(":"); //Ишем позицию первого символа :
// Time = Time.substring(i - 2, i + 6); // Выделяем из строки 2 символа перед символом : и 6 символов после
// return Time; // Возврашаем полученное время
// }
String getTimeWOsec() {
time_t now = time(nullptr);
int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
now = now + zone;
String Time = ""; // Строка для результатов времени
Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
int i = Time.indexOf(":"); //Ишем позицию первого символа :
Time = Time.substring(i - 2, i + 3); // Выделяем из строки 2 символа перед символом : и 6 символов после
return Time; // Возврашаем полученное время
}
// String getTimeWOsec() {
// time_t now = time(nullptr);
// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
// now = now + zone;
// String Time = ""; // Строка для результатов времени
// Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
// int i = Time.indexOf(":"); //Ишем позицию первого символа :
// Time = Time.substring(i - 2, i + 3); // Выделяем из строки 2 символа перед символом : и 6 символов после
// return Time; // Возврашаем полученное время
// }
String getDate() {
time_t now = time(nullptr);
int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
now = now + zone;
String Data = ""; // Строка для результатов времени
Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
Data.replace("\n", "");
uint8_t i = Data.lastIndexOf(" "); //Ишем позицию последнего символа пробел
String Time = Data.substring(i - 8, i + 1); // Выделяем время и пробел
Data.replace(Time, ""); // Удаляем из строки 8 символов времени и пробел
return Data; // Возврашаем полученную дату
}
// String getDate() {
// time_t now = time(nullptr);
// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
// now = now + zone;
// String Data = ""; // Строка для результатов времени
// Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
// Data.replace("\n", "");
// uint8_t i = Data.lastIndexOf(" "); //Ишем позицию последнего символа пробел
// String Time = Data.substring(i - 8, i + 1); // Выделяем время и пробел
// Data.replace(Time, ""); // Удаляем из строки 8 символов времени и пробел
// return Data; // Возврашаем полученную дату
// }
String getDateDigitalFormated() {
String date = getDate();
// String getDateDigitalFormated() {
// String date = getDate();
date = deleteBeforeDelimiter(date, " ");
// 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");
// 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);
String day = date.substring(3, 5);
String year = date.substring(8, 10);
// 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;
// String out = day;
// out += ".";
// out += month;
// out += ".";
// out += year;
return out;
}
// return out;
// }
int timeToMin(String Time) {
//"00:00:00" время в секунды
long min = selectToMarker(Time, ":").toInt() * 60; //общее количество секунд в полных часах
Time = deleteBeforeDelimiter(Time, ":"); // Теперь здесь минуты секунды
min += selectToMarker(Time, ":").toInt(); // Добавим секунды из полных минут
return min;
}
// int timeToMin(String Time) {
// //"00:00:00" время в секунды
// long min = selectToMarker(Time, ":").toInt() * 60; //общее количество секунд в полных часах
// Time = deleteBeforeDelimiter(Time, ":"); // Теперь здесь минуты секунды
// min += selectToMarker(Time, ":").toInt(); // Добавим секунды из полных минут
// return min;
// }
static const char* TIME_FORMAT PROGMEM = "%02d:%02d:%02d";
static const char* TIME_FORMAT_WITH_DAYS PROGMEM = "%dd %02d:%02d";
const String prettyMillis(unsigned long time_ms) {
unsigned long tmp = time_ms / 1000;
const String prettySeconds(unsigned long time_s) {
unsigned long tmp = time_s;
unsigned long seconds;
unsigned long minutes;
unsigned long hours;
@@ -132,6 +123,10 @@ const String prettyMillis(unsigned long time_ms) {
return String(buf);
}
const String prettyMillis(unsigned long time_ms) {
return prettySeconds(time_ms / 1000);
}
unsigned long millis_since(unsigned long sinse) {
return millis_passed(sinse, millis());
}
@@ -165,3 +160,53 @@ int getOffsetInSeconds(int timezone) {
int getOffsetInMinutes(int timezone) {
return timezone * ONE_HOUR_m;
}
void breakEpochToTime(unsigned long epoch, Time_t& tm) {
// break the given time_input into time components
// this is a more compact version of the C library localtime function
unsigned long time = epoch;
tm.second = time % 60;
time /= 60; // now it is minutes
tm.minute = time % 60;
time /= 60; // now it is hours
tm.hour = time % 24;
time /= 24; // now it is days
tm.days = time;
tm.day_of_week = ((time + 4) % 7) + 1; // Sunday is day 1
uint8_t year = 0;
unsigned long days = 0;
while ((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
year++;
}
tm.year = year - 30;
days -= LEAP_YEAR(year) ? 366 : 365;
time -= days; // now it is days in this year, starting at 0
tm.day_of_year = time;
uint8_t month;
uint8_t month_length;
for (month = 0; month < 12; month++) {
if (1 == month) { // february
if (LEAP_YEAR(year)) {
month_length = 29;
} else {
month_length = 28;
}
} else {
month_length = days_in_month[month];
}
if (time >= month_length) {
time -= month_length;
} else {
break;
}
}
tm.month = month + 1; // jan is month 1
tm.day_of_month = time + 1; // day of month
tm.valid = (epoch > MIN_DATETIME);
}

View File

@@ -133,14 +133,14 @@ void web_init() {
String timezoneStr = request->getParam("timezone")->value();
jsonWriteStr(configSetupJson, "timezone", timezoneStr);
saveConfig();
rtc->setTimezone(timezoneStr.toInt());
timeNow->setTimezone(timezoneStr.toInt());
request->send(200, "text/text", "OK");
}
if (request->hasArg("ntp")) {
String ntpStr = request->getParam("ntp")->value();
jsonWriteStr(configSetupJson, "ntp", ntpStr);
saveConfig();
rtc->setNtpPool(ntpStr);
timeNow->setNtpPool(ntpStr);
request->send(200, "text/text", "OK");
}
//--------------------------------------------------------------------------------

View File

@@ -8,8 +8,8 @@ void not_async_actions();
static const char* MODULE = "Main";
void do_fscheck(String& results) {
}
Timings metric;
boolean initialized = false;
void setup() {
WiFi.setAutoConnect(false);
@@ -28,14 +28,17 @@ void setup() {
pm.info("Config");
loadConfig();
pm.info("Clock");
clock_init();
pm.info("Commands");
CMD_init();
cmd_init();
pm.info("Sensors");
sensors_init();
pm.info("Init");
All_init();
all_init();
pm.info("Network");
startSTAMode();
@@ -57,47 +60,35 @@ void setup() {
pm.info("WebAdmin");
web_init();
pm.info("Clock");
rtc = new Clock();
rtc->setNtpPool(jsonReadStr(configSetupJson, "ntp"));
rtc->setTimezone(jsonReadStr(configSetupJson, "timezone").toInt());
ts.add(
TIME_SYNC, 30000, [&](void*) {
rtc->hasSync();
},
nullptr, true);
#ifdef UDP_ENABLED
pm.info("Broadcast UDP");
UDP_init();
pm.info("Broadcast");
#endif
ts.add(
TEST, 10000, [&](void*) {
TEST, 1000 * 60, [&](void*) {
pm.info(printMemoryStatus());
},
nullptr, true);
just_load = false;
}
void saveConfig() {
writeFile(String("config.json"), configSetupJson);
initialized = true;
}
Timings metric;
void loop() {
if (!initialized) {
return;
}
timeNow->loop();
#ifdef OTA_UPDATES_ENABLED
ArduinoOTA.handle();
#endif
#ifdef WS_enable
ws.cleanupClients();
#endif
metric.add(MT_ONE);
not_async_actions();
metric.add(MT_TWO);
MqttClient::loop();
loopCmd();
@@ -113,12 +104,6 @@ void loop() {
loopSerial();
ts.update();
if (metric._counter > 100000) {
metric.print();
} else {
metric.count();
}
}
void not_async_actions() {
@@ -126,7 +111,9 @@ void not_async_actions() {
MqttClient::reconnect();
mqttParamsChanged = false;
}
getLastVersion();
flashUpgrade();
#ifdef UDP_ENABLED
@@ -134,20 +121,9 @@ void not_async_actions() {
do_mqtt_send_settings_to_udp();
#endif
if (busScanFlag) {
String res = "";
BusScanner* scanner = BusScannerFactory::get(res, busToScan);
scanner->scan();
jsonWriteStr(configLiveJson, BusScannerFactory::label(busToScan), res);
busScanFlag = false;
}
do_scan_bus();
if (fsCheckFlag) {
String buf;
do_fscheck(buf);
jsonWriteStr(configLiveJson, "fscheck", buf);
fsCheckFlag = false;
}
do_check_fs();
}
String getURL(const String& urls) {
@@ -194,6 +170,10 @@ void setChipId() {
Serial.println(chipId);
}
void saveConfig() {
writeFile(String("config.json"), configSetupJson);
}
#ifdef ESP8266
#ifdef LED_PIN
void setLedStatus(LedStatus_t status) {
@@ -219,3 +199,37 @@ void setLedStatus(LedStatus_t status) {
}
#endif
#endif
void do_fscheck(String& results) {
// TODO Проверка наличие важных файлов, возможно версии ФС
}
void clock_init() {
timeNow = new Clock();
timeNow->setNtpPool(jsonReadStr(configSetupJson, "ntp"));
timeNow->setTimezone(jsonReadStr(configSetupJson, "timezone").toInt());
ts.add(
TIME_SYNC, 30000, [&](void*) {
timeNow->hasSync();
},
nullptr, true);
}
void do_scan_bus() {
if (busScanFlag) {
String res = "";
BusScanner* scanner = BusScannerFactory::get(res, busToScan);
scanner->scan();
jsonWriteStr(configLiveJson, BusScannerFactory::label(busToScan), res);
busScanFlag = false;
}
}
void do_check_fs() {
if (fsCheckFlag) {
String buf;
do_fscheck(buf);
jsonWriteStr(configLiveJson, "fscheck", buf);
fsCheckFlag = false;
}
}