анемостат - почти финал
parent
f0918088e5
commit
9fa3fb43e1
|
@ -0,0 +1,213 @@
|
|||
2575;98
|
||||
2571;97
|
||||
2573;98
|
||||
2575;98
|
||||
2567;97
|
||||
2574;98
|
||||
2575;98
|
||||
2576;98
|
||||
2576;98
|
||||
2576;98
|
||||
2575;98
|
||||
2576;98
|
||||
2576;98
|
||||
2577;98
|
||||
2576;98
|
||||
2576;98
|
||||
2576;98
|
||||
2576;98
|
||||
2576;98
|
||||
2575;98
|
||||
2576;98
|
||||
2575;98
|
||||
2576;98
|
||||
2575;98
|
||||
2576;98
|
||||
2576;98
|
||||
2577;98
|
||||
2578;98
|
||||
2576;98
|
||||
2576;98
|
||||
2574;98
|
||||
2575;98
|
||||
2577;98
|
||||
2575;98
|
||||
2576;98
|
||||
2576;98
|
||||
2578;98
|
||||
2576;98
|
||||
2573;98
|
||||
2576;98
|
||||
2575;98
|
||||
2576;98
|
||||
2578;98
|
||||
2575;98
|
||||
2525;93
|
||||
2525;93
|
||||
2515;93
|
||||
2519;93
|
||||
2523;93
|
||||
2527;94
|
||||
2530;94
|
||||
2527;94
|
||||
2516;93
|
||||
2510;92
|
||||
2508;92
|
||||
2503;91
|
||||
2497;91
|
||||
2489;90
|
||||
2480;89
|
||||
2474;89
|
||||
2467;88
|
||||
2468;88
|
||||
2464;88
|
||||
2451;87
|
||||
2446;86
|
||||
2442;86
|
||||
2433;85
|
||||
2434;85
|
||||
2433;85
|
||||
2422;84
|
||||
2415;84
|
||||
2407;83
|
||||
2409;83
|
||||
2401;83
|
||||
2401;83
|
||||
2393;82
|
||||
2382;81
|
||||
2380;81
|
||||
2377;80
|
||||
2369;80
|
||||
2365;79
|
||||
2352;78
|
||||
2351;78
|
||||
2346;78
|
||||
2347;78
|
||||
2341;77
|
||||
2333;77
|
||||
2323;76
|
||||
2320;75
|
||||
2320;75
|
||||
2315;75
|
||||
2310;75
|
||||
2300;74
|
||||
2293;73
|
||||
2282;72
|
||||
2278;72
|
||||
2266;71
|
||||
2262;70
|
||||
2250;69
|
||||
2224;67
|
||||
2209;66
|
||||
2206;65
|
||||
2202;65
|
||||
2196;65
|
||||
2182;63
|
||||
2178;63
|
||||
2175;63
|
||||
2171;62
|
||||
2167;62
|
||||
2159;61
|
||||
2154;61
|
||||
2149;60
|
||||
2143;60
|
||||
2139;60
|
||||
2137;59
|
||||
2128;59
|
||||
2119;58
|
||||
2117;58
|
||||
2115;57
|
||||
2109;57
|
||||
2105;57
|
||||
2093;56
|
||||
2087;55
|
||||
2083;55
|
||||
2077;54
|
||||
2071;54
|
||||
2064;53
|
||||
2054;52
|
||||
2046;51
|
||||
2042;51
|
||||
2032;50
|
||||
2026;50
|
||||
2018;49
|
||||
2014;49
|
||||
2003;48
|
||||
2000;47
|
||||
1997;47
|
||||
1986;46
|
||||
1982;46
|
||||
1975;45
|
||||
1967;44
|
||||
1959;44
|
||||
1954;43
|
||||
1937;42
|
||||
1937;42
|
||||
1933;41
|
||||
1925;41
|
||||
1920;40
|
||||
1906;39
|
||||
1903;39
|
||||
1899;39
|
||||
1891;38
|
||||
1885;37
|
||||
1875;36
|
||||
1865;36
|
||||
1862;35
|
||||
1855;35
|
||||
1846;34
|
||||
1840;33
|
||||
1835;33
|
||||
1819;31
|
||||
1822;32
|
||||
1809;31
|
||||
1800;30
|
||||
1793;29
|
||||
1788;29
|
||||
1776;28
|
||||
1773;27
|
||||
1763;27
|
||||
1754;26
|
||||
1748;25
|
||||
1735;24
|
||||
1731;24
|
||||
1725;23
|
||||
1714;22
|
||||
1712;22
|
||||
1699;21
|
||||
1687;20
|
||||
1686;20
|
||||
1678;19
|
||||
1670;18
|
||||
1664;18
|
||||
1655;17
|
||||
1645;16
|
||||
1640;16
|
||||
1632;15
|
||||
1616;14
|
||||
1612;13
|
||||
1606;13
|
||||
1596;12
|
||||
1588;11
|
||||
1581;11
|
||||
1570;10
|
||||
1558;9
|
||||
1550;8
|
||||
1533;6
|
||||
1530;6
|
||||
1517;5
|
||||
1510;4
|
||||
1503;4
|
||||
1494;3
|
||||
1488;2
|
||||
1477;1
|
||||
1472;1
|
||||
1460;0
|
||||
1450;0
|
||||
1456;0
|
||||
1456;0
|
||||
1456;0
|
||||
1456;0
|
||||
1456;0
|
||||
1456;0
|
||||
1456;0
|
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,5 @@
|
|||
.pio
|
||||
.vscode/.browse.c_cpp.db*
|
||||
.vscode/c_cpp_properties.json
|
||||
.vscode/launch.json
|
||||
.vscode/ipch
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
// See http://go.microsoft.com/fwlink/?LinkId=827846
|
||||
// for the documentation about the extensions.json format
|
||||
"recommendations": [
|
||||
"platformio.platformio-ide"
|
||||
]
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
|
||||
This directory is intended for project header files.
|
||||
|
||||
A header file is a file containing C declarations and macro definitions
|
||||
to be shared between several project source files. You request the use of a
|
||||
header file in your project source file (C, C++, etc) located in `src` folder
|
||||
by including it, with the C preprocessing directive `#include'.
|
||||
|
||||
```src/main.c
|
||||
|
||||
#include "header.h"
|
||||
|
||||
int main (void)
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Including a header file produces the same results as copying the header file
|
||||
into each source file that needs it. Such copying would be time-consuming
|
||||
and error-prone. With a header file, the related declarations appear
|
||||
in only one place. If they need to be changed, they can be changed in one
|
||||
place, and programs that include the header file will automatically use the
|
||||
new version when next recompiled. The header file eliminates the labor of
|
||||
finding and changing all the copies as well as the risk that a failure to
|
||||
find one copy will result in inconsistencies within a program.
|
||||
|
||||
In C, the usual convention is to give header files names that end with `.h'.
|
||||
It is most portable to use only letters, digits, dashes, and underscores in
|
||||
header file names, and at most one dot.
|
||||
|
||||
Read more about using header files in official GCC documentation:
|
||||
|
||||
* Include Syntax
|
||||
* Include Operation
|
||||
* Once-Only Headers
|
||||
* Computed Includes
|
||||
|
||||
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
|
|
@ -0,0 +1,46 @@
|
|||
|
||||
This directory is intended for project specific (private) libraries.
|
||||
PlatformIO will compile them to static libraries and link into executable file.
|
||||
|
||||
The source code of each library should be placed in a an own separate directory
|
||||
("lib/your_library_name/[here are source files]").
|
||||
|
||||
For example, see a structure of the following two libraries `Foo` and `Bar`:
|
||||
|
||||
|--lib
|
||||
| |
|
||||
| |--Bar
|
||||
| | |--docs
|
||||
| | |--examples
|
||||
| | |--src
|
||||
| | |- Bar.c
|
||||
| | |- Bar.h
|
||||
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
|
||||
| |
|
||||
| |--Foo
|
||||
| | |- Foo.c
|
||||
| | |- Foo.h
|
||||
| |
|
||||
| |- README --> THIS FILE
|
||||
|
|
||||
|- platformio.ini
|
||||
|--src
|
||||
|- main.c
|
||||
|
||||
and a contents of `src/main.c`:
|
||||
```
|
||||
#include <Foo.h>
|
||||
#include <Bar.h>
|
||||
|
||||
int main (void)
|
||||
{
|
||||
...
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
PlatformIO Library Dependency Finder will find automatically dependent
|
||||
libraries scanning project source files.
|
||||
|
||||
More information about PlatformIO Library Dependency Finder
|
||||
- https://docs.platformio.org/page/librarymanager/ldf.html
|
|
@ -0,0 +1,15 @@
|
|||
; PlatformIO Project Configuration File
|
||||
;
|
||||
; Build options: build flags, source filter
|
||||
; Upload options: custom upload port, speed and extra flags
|
||||
; Library options: dependencies, extra library storages
|
||||
; Advanced options: extra scripting
|
||||
;
|
||||
; Please visit documentation for the other options and examples
|
||||
; https://docs.platformio.org/page/projectconf.html
|
||||
|
||||
[env:m5stack-atom]
|
||||
platform = espressif32
|
||||
board = m5stack-atom
|
||||
framework = arduino
|
||||
lib_extra_dirs = C:\Users\38093\Documents\Arduino\libraries
|
|
@ -0,0 +1,696 @@
|
|||
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
|
||||
#include <Preferences.h> //Сохранение настроек хеша прошивки
|
||||
#include <HTTPClient.h>
|
||||
#include <ESP32httpUpdate.h> //Библиотека ОТА обновлений
|
||||
#include "M5Atom.h" //Библиотека атома для функции Led и Кнопки, можно упразднить и убрать
|
||||
#include <WiFiUdp.h> //Udp клиент
|
||||
#include <NTPClient.h> //NTP запрос времени
|
||||
#include <TimeLib.h> //Внутреннее время
|
||||
#include <Wire.h> //Библиотека дял I2C
|
||||
#include <PubSubClient.h> //Mtqq
|
||||
#include <ArduinoJson.h> //Упакова в JSon - удобная библиотека
|
||||
#include <ESPmDNS.h>
|
||||
|
||||
#define Fpin 22
|
||||
#define Bpin 19
|
||||
#define Resist 33
|
||||
|
||||
#define TRIGGER_PIN 39
|
||||
unsigned int VersionSW = 2;
|
||||
|
||||
//3 - Первый код для анемостата
|
||||
|
||||
WiFiManager wm; // обьект менеджера
|
||||
Preferences OTApreferences; //Обьект хранения настроек хеша прошивки
|
||||
|
||||
String JsonData;
|
||||
StaticJsonDocument<200> doc, docResult;
|
||||
|
||||
WiFiClient espClient;
|
||||
PubSubClient MqttClient(espClient);
|
||||
IPAddress IpMqtt;
|
||||
|
||||
WiFiUDP ntpUDP;
|
||||
NTPClient timeClient(ntpUDP, "192.168.89.210", 0, 20000); //Собственно сервер времени смещение и частоат запроса, но он вручную
|
||||
const PROGMEM char *willmess = "{\"conn\":\"err\"}";
|
||||
const char *mqttHostName = "cctv.automation.art"; //Хостнейм брокера metrics.local cctv.automation.art //192.168.89.210
|
||||
unsigned int mqttPort = 8889; //Порт брокера 1883 8889
|
||||
|
||||
String getMacAddress();
|
||||
String macc = getMacAddress();
|
||||
String topicTemp = "aastudio/act/" + macc + "/data/0";
|
||||
String setTopic = "aastudio/act/" + macc + "/set/0";
|
||||
String willTopicTemp = "aastudio/act/" + macc + "/status";
|
||||
const PROGMEM char *mqttLogin = "AA_Lab", *mqttPass = "automation.art$";
|
||||
|
||||
byte setPercent = 0, setSpeedAnemo = 0;
|
||||
int stateResistor = 0;
|
||||
|
||||
const char *mqttIPHost; //тут хранится IP хоста по хостнейму
|
||||
unsigned long timingUpdate = 0, timingReqSensor = 0, timingSendMqtt = 0; //Таймеры для millis()
|
||||
int PROGMEM nextM5Update = 450000, nextMqttSend = 60000; //каждые 7.5 минут запрос обновления с сервера
|
||||
|
||||
bool mqttSendFlag = false;
|
||||
int reqCounter = 0;
|
||||
long rssi = 0;
|
||||
char bufTopic[140], bufWillTopic[150], bufSetTopic[150];
|
||||
|
||||
int moveAnemo(byte speed, byte percent);
|
||||
int setMotor(bool Finput, int Binput);
|
||||
void callback(char *topic, byte *payload, unsigned int length);
|
||||
int disconnectMQTT();
|
||||
|
||||
void ledset(byte color = 0)
|
||||
{
|
||||
M5.dis.setBrightness(60); //Половина яркости
|
||||
switch (color)
|
||||
{
|
||||
case 2:
|
||||
M5.dis.drawpix(0, 0xf00000); //Зеленый
|
||||
break;
|
||||
case 1:
|
||||
M5.dis.drawpix(0, 0x00ff00); //Красный
|
||||
break;
|
||||
case 3:
|
||||
M5.dis.drawpix(0, 0x0000ff); //Синий
|
||||
break;
|
||||
case 4:
|
||||
M5.dis.drawpix(0, 0xffffff); //Белый
|
||||
break;
|
||||
case 5:
|
||||
M5.dis.drawpix(0, 0xffec00); //желтый
|
||||
break;
|
||||
|
||||
default:
|
||||
M5.dis.clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//Настройки
|
||||
|
||||
int getIpBlock(int index, String str)
|
||||
{
|
||||
char separator = '.';
|
||||
int found = 0;
|
||||
int strIndex[] = {0, -1};
|
||||
int maxIndex = str.length() - 1;
|
||||
|
||||
for (int i = 0; i <= maxIndex && found <= index; i++)
|
||||
{
|
||||
if (str.charAt(i) == separator || i == maxIndex)
|
||||
{
|
||||
found++;
|
||||
strIndex[0] = strIndex[1] + 1;
|
||||
strIndex[1] = (i == maxIndex) ? i + 1 : i;
|
||||
}
|
||||
}
|
||||
|
||||
return found > index ? str.substring(strIndex[0], strIndex[1]).toInt() : 0;
|
||||
}
|
||||
|
||||
IPAddress str2IP(String str)
|
||||
{
|
||||
IPAddress ret(getIpBlock(0, str), getIpBlock(1, str), getIpBlock(2, str), getIpBlock(3, str));
|
||||
return ret;
|
||||
}
|
||||
|
||||
int setMqttServer(const char *mqttHostNameF, unsigned int mqttPortF)
|
||||
{
|
||||
mdns_init();
|
||||
|
||||
IPAddress ipaddr;
|
||||
OTApreferences.begin("ota-config");
|
||||
|
||||
OTApreferences.putString("mqttip", "0");
|
||||
delay(1000);
|
||||
String keyIpMqtt = OTApreferences.getString("mqttip", "0");
|
||||
Serial.print("keyIpMqtt: ");
|
||||
Serial.println(keyIpMqtt);
|
||||
|
||||
if (keyIpMqtt == "0")
|
||||
{
|
||||
//Запрос по хостнейму .local
|
||||
ipaddr = MDNS.queryHost(mqttHostNameF, 4000);
|
||||
//Таймаут 4 секунды
|
||||
//Если не получили по хостнейму МДНС
|
||||
Serial.print("mdns: ");
|
||||
Serial.println(ipaddr);
|
||||
|
||||
if (ipaddr.toString() == "0.0.0.0")
|
||||
{
|
||||
//Запрос к ДНС по адресу сайта
|
||||
int err = WiFi.hostByName(mqttHostNameF, ipaddr);
|
||||
////real internal timeout in lwip library is 14[s]
|
||||
//Если получили по хостнейму
|
||||
if (err == 1)
|
||||
{
|
||||
Serial.print("hostByName: ");
|
||||
Serial.println(ipaddr);
|
||||
MqttClient.setServer(ipaddr, mqttPortF);
|
||||
OTApreferences.putString("mqttip", ipaddr.toString());
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.print("All method not FOUND IP");
|
||||
}
|
||||
}
|
||||
else
|
||||
{ //Если все хорошо
|
||||
OTApreferences.putString("mqttip", ipaddr.toString());
|
||||
MqttClient.setServer(ipaddr, mqttPortF);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MqttClient.setServer(str2IP(keyIpMqtt), mqttPortF);
|
||||
}
|
||||
|
||||
MqttClient.setCallback(callback);
|
||||
OTApreferences.end();
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Запрос времени NTP и установка локлаьного времени
|
||||
int reqNtpTime()
|
||||
{
|
||||
if (timeClient.update())
|
||||
{
|
||||
uint32_t timeEpoch = timeClient.getEpochTime();
|
||||
if (timeEpoch < 1600000000)
|
||||
{
|
||||
Serial.println("Error reqNtpTime() Time");
|
||||
return 1;
|
||||
}
|
||||
setTime(timeEpoch);
|
||||
// Serial.print(timeEpoch);
|
||||
// Serial.print(" <=ntp== ==device=> ");
|
||||
// Serial.println(now());
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//{"percent":50,"speed":20}
|
||||
void callback(char *topic, byte *payload, unsigned int length)
|
||||
{
|
||||
Serial.print("Message arrived [");
|
||||
Serial.print(topic);
|
||||
Serial.print("] ");
|
||||
|
||||
char jsonResult[250];
|
||||
|
||||
for (int i = 0; i < length; i++)
|
||||
{
|
||||
Serial.print((char)payload[i]);
|
||||
jsonResult[i] = (char)payload[i];
|
||||
}
|
||||
|
||||
DeserializationError error = deserializeJson(docResult, jsonResult);
|
||||
if (error)
|
||||
{
|
||||
Serial.print(F("deserializeJson() failed: "));
|
||||
return;
|
||||
}
|
||||
|
||||
setPercent = (byte)docResult["percent"]; //0-100
|
||||
setSpeedAnemo = (byte)docResult["speed"]; //speed
|
||||
|
||||
moveAnemo(setSpeedAnemo, setPercent);
|
||||
}
|
||||
|
||||
int moveAnemo(byte speed, byte percent)
|
||||
{
|
||||
|
||||
Serial.print("Set: ");
|
||||
Serial.print(speed);
|
||||
Serial.print(" ");
|
||||
Serial.println(percent);
|
||||
|
||||
int setResist = map(percent, 0, 100, 1420, 2630);
|
||||
|
||||
Serial.print("NOW: ");
|
||||
Serial.print(setResist);
|
||||
Serial.print(" ");
|
||||
Serial.println(map(setResist, 1420, 2630, 0, 100));
|
||||
Serial.println(" %");
|
||||
|
||||
Serial.println(" -------------------- ");
|
||||
|
||||
if (setResist <= stateResistor)
|
||||
{
|
||||
setMotor(false, true);
|
||||
while (setResist <= stateResistor)
|
||||
{
|
||||
stateResistor = analogRead(Resist);
|
||||
Serial.print("Now: ");
|
||||
Serial.print(map(stateResistor, 1420, 2630, 0, 100));
|
||||
Serial.println(" %");
|
||||
delay(200);
|
||||
}
|
||||
}
|
||||
|
||||
if (setResist >= stateResistor)
|
||||
{
|
||||
setMotor(true, false);
|
||||
while (setResist >= stateResistor)
|
||||
{
|
||||
stateResistor = analogRead(Resist);
|
||||
Serial.print("Now: ");
|
||||
Serial.print(map(stateResistor, 1420, 2630, 0, 100));
|
||||
Serial.println(" %");
|
||||
delay(200);
|
||||
}
|
||||
}
|
||||
|
||||
// 0 - 1460
|
||||
// 10 - 1535 - 1547
|
||||
// 20 - 1656 - 1668
|
||||
// 30 - 1777 - 1789
|
||||
// 40 - 1898 - 1910
|
||||
// 50 - 2019 - 2031
|
||||
// 60 - 2140 - 2152
|
||||
// 70 - 2261 - 2273
|
||||
// 80 - 2382 - 2394
|
||||
// 90 - 2503 - 2515
|
||||
// 100 -2624 - 2640
|
||||
|
||||
//1420 - закрыто
|
||||
//2630 - открыто
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Нажатие кнопки для сброса
|
||||
void checkButton()
|
||||
{
|
||||
Serial.println("Button RESET Pressed");
|
||||
disconnectMQTT();
|
||||
delay(100);
|
||||
OTApreferences.begin("ota-config");
|
||||
OTApreferences.putString("mqttip", "0");
|
||||
OTApreferences.end();
|
||||
wm.resetSettings();
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
//Обновление прошивки, происходит проверка и загрузка
|
||||
//Делается Get запрос на хостинг проверяется хеш, если хеш
|
||||
void OTAUpdate()
|
||||
{
|
||||
////Serial.\println("OTAUpdate()");
|
||||
bool flagOTA = false;
|
||||
String keyOTA;
|
||||
String payload;
|
||||
OTApreferences.begin("ota-config");
|
||||
if (WiFi.status() == WL_CONNECTED)
|
||||
{
|
||||
|
||||
HTTPClient http;
|
||||
String serverPath = "http://meteosence.s-host.net/airqa/airquality.php?meteopas=sfddsg38r327kjsdgf8932r&mac = " + macc + " &meteodata = gethash";
|
||||
http.begin(serverPath.c_str());
|
||||
int httpResponseCode = http.GET();
|
||||
|
||||
if (httpResponseCode > 0)
|
||||
{
|
||||
Serial.print("HTTP Response code: ");
|
||||
Serial.println(httpResponseCode);
|
||||
payload = http.getString();
|
||||
Serial.println(payload);
|
||||
|
||||
if (payload != "errno" || payload != "errfi")
|
||||
{
|
||||
|
||||
keyOTA = OTApreferences.getString("md5HashOTA");
|
||||
|
||||
if (keyOTA.length() <= 0)
|
||||
{
|
||||
OTApreferences.putString("md5HashOTA", "undifined");
|
||||
}
|
||||
|
||||
keyOTA = OTApreferences.getString("md5HashOTA");
|
||||
|
||||
if (payload != keyOTA)
|
||||
{
|
||||
flagOTA = true;
|
||||
OTApreferences.putString("md5HashOTA", payload);
|
||||
//Serial.println("flagOTA = true;");
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Serial.print("Error code HTTP: ");
|
||||
Serial.println(httpResponseCode);
|
||||
}
|
||||
// Free resources
|
||||
http.end();
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Serial.println("WiFi Disconnected");
|
||||
}
|
||||
|
||||
if (flagOTA == true)
|
||||
{
|
||||
flagOTA = false;
|
||||
//Serial.println("flagOTA = false;");
|
||||
|
||||
t_httpUpdate_return ret = ESPhttpUpdate.update("http://meteosence.s-host.net/airqa/co2/co2.bin");
|
||||
|
||||
//После update ничего не происходит, такая вот особенность.
|
||||
//Если все прошло хорошо, перезагрузка на новую прошивку
|
||||
|
||||
//Serial.print("ret ");
|
||||
//Serial.println(ret);
|
||||
|
||||
switch (ret)
|
||||
{
|
||||
|
||||
case HTTP_UPDATE_FAILED:
|
||||
//Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
//Serial.println(ESPhttpUpdate.getLastError());
|
||||
//Serial.println(ESPhttpUpdate.getLastErrorString().c_str());
|
||||
//Serial.println("HTTP_UPDATE_FAILD Error");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
//Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
//Serial.println("HTTP_UPDATE_OK");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
}
|
||||
}
|
||||
OTApreferences.end();
|
||||
}
|
||||
|
||||
//Получение мак адреса
|
||||
String getMacAddress()
|
||||
{
|
||||
uint8_t baseMac[6];
|
||||
esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
|
||||
char baseMacChr[18] = {0};
|
||||
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
|
||||
return String(baseMacChr);
|
||||
}
|
||||
|
||||
//Отправка данных по MQTT
|
||||
int SendMqttReq(bool sendVal = true, bool sendStatus = true, byte statusConn = 1)
|
||||
{
|
||||
if (mqttSendFlag == true)
|
||||
{
|
||||
|
||||
char resultString[200];
|
||||
String JsonData = "";
|
||||
rssi = WiFi.RSSI();
|
||||
unsigned long timeNow = now();
|
||||
|
||||
doc["t"] = "";
|
||||
doc["h"] = "";
|
||||
doc["co2"] = "";
|
||||
|
||||
doc["ts"] = timeNow;
|
||||
|
||||
serializeJson(doc, JsonData);
|
||||
doc.remove("ts");
|
||||
doc.remove("t");
|
||||
doc.remove("h");
|
||||
doc.remove("co2");
|
||||
doc.clear();
|
||||
doc.garbageCollect();
|
||||
|
||||
Serial.println(JsonData); //Вывод JSON строки в консоль
|
||||
JsonData.toCharArray(resultString, JsonData.length() + 1);
|
||||
MqttClient.publish(bufTopic, resultString, true);
|
||||
|
||||
if (sendStatus == true)
|
||||
{
|
||||
const char *conn;
|
||||
switch (statusConn)
|
||||
{
|
||||
case 1:
|
||||
conn = "on";
|
||||
break;
|
||||
|
||||
case 2:
|
||||
conn = "off";
|
||||
break;
|
||||
|
||||
case 3:
|
||||
conn = "slp";
|
||||
break;
|
||||
|
||||
case 4:
|
||||
conn = "upd";
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
doc["conn"] = conn;
|
||||
doc["rssi"] = rssi;
|
||||
doc["bsid"] = WiFi.BSSIDstr();
|
||||
doc["ts"] = timeNow;
|
||||
doc["exp"] = timeNow + 600;
|
||||
doc["sv"] = VersionSW;
|
||||
|
||||
JsonData = "";
|
||||
serializeJson(doc, JsonData);
|
||||
Serial.println(JsonData); //Вывод JSON строки в консоль
|
||||
|
||||
doc.clear();
|
||||
doc.garbageCollect();
|
||||
|
||||
JsonData.toCharArray(resultString, JsonData.length() + 1);
|
||||
MqttClient.publish(bufWillTopic, resultString, true);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Переподключение при петери связи с MQTT
|
||||
//7 раз проверили и вернулись в общий цикл что бы вдруг что втянуть обновления
|
||||
void reconnectMqtt()
|
||||
{
|
||||
byte circle = 0;
|
||||
while (!MqttClient.connected())
|
||||
{
|
||||
circle++;
|
||||
if (circle == 5)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
String maccrandom = macc + String(random(0xffff), HEX);
|
||||
const char *clientId = maccrandom.c_str();
|
||||
|
||||
if (MqttClient.connect(clientId, mqttLogin, mqttPass, bufWillTopic, 2, true, willmess))
|
||||
{
|
||||
Serial.println("Mqttconnect - OK");
|
||||
mqttSendFlag = true;
|
||||
MqttClient.subscribe(bufSetTopic);
|
||||
SendMqttReq(false, true, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.print("Mqtt.state() = ");
|
||||
Serial.println(MqttClient.state());
|
||||
/*
|
||||
-4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time
|
||||
-3 : MQTT_CONNECTION_LOST - the network connection was broken
|
||||
-2 : MQTT_CONNECT_FAILED - the network connection failed
|
||||
-1 : MQTT_DISCONNECTED - the client is disconnected cleanly
|
||||
0 : MQTT_CONNECTED - the client is connected
|
||||
1 : MQTT_CONNECT_BAD_PROTOCOL - the server doesn't support the requested version of MQTT
|
||||
2 : MQTT_CONNECT_BAD_CLIENT_ID - the server rejected the client identifier
|
||||
3 : MQTT_CONNECT_UNAVAILABLE - the server was unable to accept the connection
|
||||
4 : MQTT_CONNECT_BAD_CREDENTIALS - the username/password were rejected
|
||||
5 : MQTT_CONNECT_UNAUTHORIZED - the client was not authorized to connect
|
||||
*/
|
||||
mqttSendFlag = false;
|
||||
delay(500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setup()
|
||||
{
|
||||
Serial.begin(115200);
|
||||
Serial.setDebugOutput(true);
|
||||
M5.begin(true, false, true);
|
||||
|
||||
delay(50);
|
||||
pinMode(TRIGGER_PIN, INPUT);
|
||||
|
||||
pinMode(Fpin, OUTPUT);
|
||||
pinMode(Bpin, OUTPUT);
|
||||
|
||||
setMotor(false, false);
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
delay(100);
|
||||
|
||||
Serial.println(setTopic);
|
||||
Serial.println(topicTemp);
|
||||
Serial.println(willTopicTemp);
|
||||
|
||||
setTopic.toCharArray(bufSetTopic, setTopic.length() + 1);
|
||||
topicTemp.toCharArray(bufTopic, topicTemp.length() + 1);
|
||||
willTopicTemp.toCharArray(bufWillTopic, willTopicTemp.length() + 1);
|
||||
|
||||
// wm.resetSettings(); // wipe settings
|
||||
|
||||
std::vector<const char *> menu = {"wifi", "info", "param", "sep", "restart", "exit"};
|
||||
wm.setMenu(menu);
|
||||
// set dark theme
|
||||
wm.setClass("invert");
|
||||
//set static ip
|
||||
// wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn
|
||||
// wm.setShowStaticFields(true); // force show static ip fields
|
||||
// wm.setShowDnsFields(true); // force show dns field always
|
||||
// wm.setConnectTimeout(20); // how long to try to connect for before continuing
|
||||
wm.setConfigPortalTimeout(30); // auto close configportal after n seconds
|
||||
wm.setMinimumSignalQuality(10); // set min RSSI (percentage) to show in scans, null = 8%
|
||||
wm.setScanDispPerc(true); // show RSSI as percentage not graph icons
|
||||
wm.setWiFiAutoReconnect(true); // if true, enable autoreconnecting
|
||||
|
||||
bool res;
|
||||
|
||||
res = wm.autoConnect("AnemostatM5Portal", "12345678"); // Подключение к анонимной точке доступа
|
||||
if (!res)
|
||||
{
|
||||
Serial.println("Failed to connect or hit timeout");
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
if (reqNtpTime() == 1)
|
||||
{
|
||||
reqNtpTime();
|
||||
}
|
||||
|
||||
setMqttServer(mqttHostName, mqttPort);
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
M5.update();
|
||||
|
||||
if (WiFi.status() != WL_CONNECTED)
|
||||
{
|
||||
Serial.println(WiFi.status());
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
if (!MqttClient.connected())
|
||||
{
|
||||
reconnectMqtt();
|
||||
}
|
||||
|
||||
stateResistor = analogRead(Resist);
|
||||
|
||||
// if (millis() - timingSendMqtt > nextMqttSend)
|
||||
// {
|
||||
// SendMqttReq();
|
||||
// timingSendMqtt = millis();
|
||||
// }
|
||||
|
||||
// 40 секунд и происходит сброс настроек WIFI
|
||||
if (M5.Btn.wasReleasefor(40000))
|
||||
{
|
||||
checkButton();
|
||||
}
|
||||
|
||||
//По таймеру запруск обновления прошивки
|
||||
if (millis() - timingUpdate > nextM5Update)
|
||||
{
|
||||
reqNtpTime();
|
||||
SendMqttReq(false, true, 4);
|
||||
OTAUpdate();
|
||||
SendMqttReq(false, true, 1);
|
||||
timingUpdate = millis();
|
||||
}
|
||||
|
||||
//Таймер отправки данных в брокер
|
||||
MqttClient.loop();
|
||||
}
|
||||
|
||||
int disconnectMQTT()
|
||||
{
|
||||
MqttClient.disconnect();
|
||||
return 0;
|
||||
}
|
||||
|
||||
int setMotor(bool Finput, int Binput)
|
||||
{
|
||||
|
||||
if (Finput == true && Binput == false)
|
||||
{
|
||||
digitalWrite(Fpin, HIGH);
|
||||
digitalWrite(Bpin, LOW);
|
||||
}
|
||||
|
||||
if (Finput == false && Binput == true)
|
||||
{
|
||||
digitalWrite(Fpin, LOW);
|
||||
digitalWrite(Bpin, HIGH);
|
||||
}
|
||||
|
||||
//stop
|
||||
if (Finput == false && Binput == false)
|
||||
{
|
||||
digitalWrite(Fpin, LOW);
|
||||
digitalWrite(Bpin, LOW);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Закрыто
|
||||
// 1422
|
||||
// 1418
|
||||
// 1423
|
||||
// 1421
|
||||
// 1423
|
||||
// 1422
|
||||
// 1424
|
||||
// 1424
|
||||
// 1421
|
||||
// 1424
|
||||
// 1424
|
||||
// 1421
|
||||
// 1423
|
||||
// 1424
|
||||
// 1421
|
||||
// 1419
|
||||
// 1421
|
||||
// 1423
|
||||
// 1423
|
||||
// 1424
|
||||
|
||||
//Открыто
|
||||
// 2631
|
||||
// 2635
|
||||
// 2631
|
||||
// 2637
|
||||
// 2634
|
||||
// 2635
|
||||
// 2637
|
||||
// 2635
|
||||
// 2635
|
||||
// 2634
|
||||
// 2637
|
||||
// 2637
|
||||
// 2635
|
||||
// 2631
|
||||
// 2638
|
|
@ -0,0 +1,11 @@
|
|||
|
||||
This directory is intended for PlatformIO Unit Testing and project tests.
|
||||
|
||||
Unit Testing is a software testing method by which individual units of
|
||||
source code, sets of one or more MCU program modules together with associated
|
||||
control data, usage procedures, and operating procedures, are tested to
|
||||
determine whether they are fit for use. Unit testing finds problems early
|
||||
in the development cycle.
|
||||
|
||||
More information about PlatformIO Unit Testing:
|
||||
- https://docs.platformio.org/page/plus/unit-testing.html
|
|
@ -0,0 +1,40 @@
|
|||
0;1350
|
||||
1;1354
|
||||
2;1351
|
||||
3;1360
|
||||
4;1406
|
||||
5;1453
|
||||
6;1495
|
||||
7;1542
|
||||
8;1596
|
||||
9;1648
|
||||
10;1665
|
||||
11;1695
|
||||
12;1730
|
||||
13;1776
|
||||
14;1808
|
||||
15;1847
|
||||
16;1891
|
||||
17;1912
|
||||
18;1950
|
||||
19;1978
|
||||
20;2011
|
||||
21;2043
|
||||
22;2081
|
||||
23;2111
|
||||
24;2136
|
||||
25;2167
|
||||
26;2195
|
||||
27;2226
|
||||
28;2256
|
||||
29;2286
|
||||
30;2314
|
||||
31;2347
|
||||
32;2377
|
||||
33;2416
|
||||
34;2462
|
||||
35;2512
|
||||
36;2544
|
||||
37;2577
|
||||
38;2610
|
||||
39;2634
|
|
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,213 @@
|
|||
2575 98
|
||||
2571 97
|
||||
2573 98
|
||||
2575 98
|
||||
2567 97
|
||||
2574 98
|
||||
2575 98
|
||||
2576 98
|
||||
2576 98
|
||||
2576 98
|
||||
2575 98
|
||||
2576 98
|
||||
2576 98
|
||||
2577 98
|
||||
2576 98
|
||||
2576 98
|
||||
2576 98
|
||||
2576 98
|
||||
2576 98
|
||||
2575 98
|
||||
2576 98
|
||||
2575 98
|
||||
2576 98
|
||||
2575 98
|
||||
2576 98
|
||||
2576 98
|
||||
2577 98
|
||||
2578 98
|
||||
2576 98
|
||||
2576 98
|
||||
2574 98
|
||||
2575 98
|
||||
2577 98
|
||||
2575 98
|
||||
2576 98
|
||||
2576 98
|
||||
2578 98
|
||||
2576 98
|
||||
2573 98
|
||||
2576 98
|
||||
2575 98
|
||||
2576 98
|
||||
2578 98
|
||||
2575 98
|
||||
2525 93
|
||||
2525 93
|
||||
2515 93
|
||||
2519 93
|
||||
2523 93
|
||||
2527 94
|
||||
2530 94
|
||||
2527 94
|
||||
2516 93
|
||||
2510 92
|
||||
2508 92
|
||||
2503 91
|
||||
2497 91
|
||||
2489 90
|
||||
2480 89
|
||||
2474 89
|
||||
2467 88
|
||||
2468 88
|
||||
2464 88
|
||||
2451 87
|
||||
2446 86
|
||||
2442 86
|
||||
2433 85
|
||||
2434 85
|
||||
2433 85
|
||||
2422 84
|
||||
2415 84
|
||||
2407 83
|
||||
2409 83
|
||||
2401 83
|
||||
2401 83
|
||||
2393 82
|
||||
2382 81
|
||||
2380 81
|
||||
2377 80
|
||||
2369 80
|
||||
2365 79
|
||||
2352 78
|
||||
2351 78
|
||||
2346 78
|
||||
2347 78
|
||||
2341 77
|
||||
2333 77
|
||||
2323 76
|
||||
2320 75
|
||||
2320 75
|
||||
2315 75
|
||||
2310 75
|
||||
2300 74
|
||||
2293 73
|
||||
2282 72
|
||||
2278 72
|
||||
2266 71
|
||||
2262 70
|
||||
2250 69
|
||||
2224 67
|
||||
2209 66
|
||||
2206 65
|
||||
2202 65
|
||||
2196 65
|
||||
2182 63
|
||||
2178 63
|
||||
2175 63
|
||||
2171 62
|
||||
2167 62
|
||||
2159 61
|
||||
2154 61
|
||||
2149 60
|
||||
2143 60
|
||||
2139 60
|
||||
2137 59
|
||||
2128 59
|
||||
2119 58
|
||||
2117 58
|
||||
2115 57
|
||||
2109 57
|
||||
2105 57
|
||||
2093 56
|
||||
2087 55
|
||||
2083 55
|
||||
2077 54
|
||||
2071 54
|
||||
2064 53
|
||||
2054 52
|
||||
2046 51
|
||||
2042 51
|
||||
2032 50
|
||||
2026 50
|
||||
2018 49
|
||||
2014 49
|
||||
2003 48
|
||||
2000 47
|
||||
1997 47
|
||||
1986 46
|
||||
1982 46
|
||||
1975 45
|
||||
1967 44
|
||||
1959 44
|
||||
1954 43
|
||||
1937 42
|
||||
1937 42
|
||||
1933 41
|
||||
1925 41
|
||||
1920 40
|
||||
1906 39
|
||||
1903 39
|
||||
1899 39
|
||||
1891 38
|
||||
1885 37
|
||||
1875 36
|
||||
1865 36
|
||||
1862 35
|
||||
1855 35
|
||||
1846 34
|
||||
1840 33
|
||||
1835 33
|
||||
1819 31
|
||||
1822 32
|
||||
1809 31
|
||||
1800 30
|
||||
1793 29
|
||||
1788 29
|
||||
1776 28
|
||||
1773 27
|
||||
1763 27
|
||||
1754 26
|
||||
1748 25
|
||||
1735 24
|
||||
1731 24
|
||||
1725 23
|
||||
1714 22
|
||||
1712 22
|
||||
1699 21
|
||||
1687 20
|
||||
1686 20
|
||||
1678 19
|
||||
1670 18
|
||||
1664 18
|
||||
1655 17
|
||||
1645 16
|
||||
1640 16
|
||||
1632 15
|
||||
1616 14
|
||||
1612 13
|
||||
1606 13
|
||||
1596 12
|
||||
1588 11
|
||||
1581 11
|
||||
1570 10
|
||||
1558 9
|
||||
1550 8
|
||||
1533 6
|
||||
1530 6
|
||||
1517 5
|
||||
1510 4
|
||||
1503 4
|
||||
1494 3
|
||||
1488 2
|
||||
1477 1
|
||||
1472 1
|
||||
1460 0
|
||||
1450 0
|
||||
1456 0
|
||||
1456 0
|
||||
1456 0
|
||||
1456 0
|
||||
1456 0
|
||||
1456 0
|
||||
1456 0
|
|
@ -0,0 +1,5 @@
|
|||
.pio
|
||||
.vscode/.browse.c_cpp.db*
|
||||
.vscode/c_cpp_properties.json
|
||||
.vscode/launch.json
|
||||
.vscode/ipch
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
// See http://go.microsoft.com/fwlink/?LinkId=827846
|
||||
// for the documentation about the extensions.json format
|
||||
"recommendations": [
|
||||
"platformio.platformio-ide"
|
||||
]
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
|
||||
This directory is intended for project header files.
|
||||
|
||||
A header file is a file containing C declarations and macro definitions
|
||||
to be shared between several project source files. You request the use of a
|
||||
header file in your project source file (C, C++, etc) located in `src` folder
|
||||
by including it, with the C preprocessing directive `#include'.
|
||||
|
||||
```src/main.c
|
||||
|
||||
#include "header.h"
|
||||
|
||||
int main (void)
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Including a header file produces the same results as copying the header file
|
||||
into each source file that needs it. Such copying would be time-consuming
|
||||
and error-prone. With a header file, the related declarations appear
|
||||
in only one place. If they need to be changed, they can be changed in one
|
||||
place, and programs that include the header file will automatically use the
|
||||
new version when next recompiled. The header file eliminates the labor of
|
||||
finding and changing all the copies as well as the risk that a failure to
|
||||
find one copy will result in inconsistencies within a program.
|
||||
|
||||
In C, the usual convention is to give header files names that end with `.h'.
|
||||
It is most portable to use only letters, digits, dashes, and underscores in
|
||||
header file names, and at most one dot.
|
||||
|
||||
Read more about using header files in official GCC documentation:
|
||||
|
||||
* Include Syntax
|
||||
* Include Operation
|
||||
* Once-Only Headers
|
||||
* Computed Includes
|
||||
|
||||
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
|
|
@ -0,0 +1,46 @@
|
|||
|
||||
This directory is intended for project specific (private) libraries.
|
||||
PlatformIO will compile them to static libraries and link into executable file.
|
||||
|
||||
The source code of each library should be placed in a an own separate directory
|
||||
("lib/your_library_name/[here are source files]").
|
||||
|
||||
For example, see a structure of the following two libraries `Foo` and `Bar`:
|
||||
|
||||
|--lib
|
||||
| |
|
||||
| |--Bar
|
||||
| | |--docs
|
||||
| | |--examples
|
||||
| | |--src
|
||||
| | |- Bar.c
|
||||
| | |- Bar.h
|
||||
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
|
||||
| |
|
||||
| |--Foo
|
||||
| | |- Foo.c
|
||||
| | |- Foo.h
|
||||
| |
|
||||
| |- README --> THIS FILE
|
||||
|
|
||||
|- platformio.ini
|
||||
|--src
|
||||
|- main.c
|
||||
|
||||
and a contents of `src/main.c`:
|
||||
```
|
||||
#include <Foo.h>
|
||||
#include <Bar.h>
|
||||
|
||||
int main (void)
|
||||
{
|
||||
...
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
PlatformIO Library Dependency Finder will find automatically dependent
|
||||
libraries scanning project source files.
|
||||
|
||||
More information about PlatformIO Library Dependency Finder
|
||||
- https://docs.platformio.org/page/librarymanager/ldf.html
|
|
@ -0,0 +1,15 @@
|
|||
; PlatformIO Project Configuration File
|
||||
;
|
||||
; Build options: build flags, source filter
|
||||
; Upload options: custom upload port, speed and extra flags
|
||||
; Library options: dependencies, extra library storages
|
||||
; Advanced options: extra scripting
|
||||
;
|
||||
; Please visit documentation for the other options and examples
|
||||
; https://docs.platformio.org/page/projectconf.html
|
||||
|
||||
[env:m5stack-atom]
|
||||
platform = espressif32
|
||||
board = m5stack-atom
|
||||
framework = arduino
|
||||
lib_extra_dirs = C:\Users\38093\Documents\Arduino\libraries
|
|
@ -0,0 +1,608 @@
|
|||
#include <Arduino.h>
|
||||
|
||||
/*
|
||||
Мониторинг параметров сети
|
||||
*/
|
||||
|
||||
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
|
||||
#include <Preferences.h> //Сохранение настроек хеша прошивки
|
||||
|
||||
#include <HTTPClient.h>
|
||||
#include <ESP32httpUpdate.h> //Библиотека ОТА обновлений
|
||||
#include "M5Atom.h" //Библиотека атома для функции Led и Кнопки, можно упразднить и убрать
|
||||
|
||||
#include <WiFiUdp.h> //Udp клиент
|
||||
#include <NTPClient.h> //NTP запрос времени
|
||||
#include <TimeLib.h> //Внутреннее время
|
||||
#include <Wire.h> //Библиотека дял I2C
|
||||
|
||||
#include <PubSubClient.h> //Mtqq
|
||||
#include <ArduinoJson.h> //Упакова в JSon - удобная библиотека
|
||||
#include <ESPmDNS.h>
|
||||
#include <OneWire.h>
|
||||
#include <DallasTemperature.h>
|
||||
|
||||
OneWire ds18x20[] = {33, 23};
|
||||
const int oneWireCount = sizeof(ds18x20) / sizeof(OneWire);
|
||||
DallasTemperature sensor[oneWireCount];
|
||||
|
||||
//Наша кнопочка при нажатии на которую произойдет вызов wifi менеджера и перезагрузка в станцию
|
||||
#define TRIGGER_PIN 39
|
||||
|
||||
#define txPin 25
|
||||
|
||||
unsigned int VersionSW = 3; //65536 Версия прошивки
|
||||
byte errorID = 0; //Сбор и вывод ошибок
|
||||
|
||||
//3- опрос датчиков последовательно
|
||||
|
||||
WiFiManager wm; // обьект менеджера
|
||||
Preferences OTApreferences; //Обьект хранения настроек хеша прошивки
|
||||
|
||||
String JsonData;
|
||||
StaticJsonDocument<200> doc;
|
||||
|
||||
WiFiClient espClient;
|
||||
PubSubClient MqttClient(espClient);
|
||||
IPAddress IpMqtt;
|
||||
|
||||
WiFiUDP ntpUDP;
|
||||
NTPClient timeClient(ntpUDP, "192.168.89.210", 0, 20000); //Собственно сервер времени смещение и частоат запроса, но он вручную
|
||||
const PROGMEM char *willmess = "{\"conn\":\"err\"}";
|
||||
const char *mqttHostName = "metrics"; //Хостнейм брокера metrics.local cctv.automation.art //192.168.89.210
|
||||
unsigned int mqttPort = 1883; //Порт брокера 1883 8889
|
||||
|
||||
String getMacAddress();
|
||||
String macc = getMacAddress();
|
||||
String topicTemp = "aastudio/sens/" + macc + "/data/0";
|
||||
|
||||
String willTopicTemp = "aastudio/sens/" + macc + "/status";
|
||||
const PROGMEM char *mqttLogin = "AA_Lab", *mqttPass = "automation.art$";
|
||||
|
||||
const char *mqttIPHost; //тут хранится IP хоста по хостнейму
|
||||
|
||||
unsigned long timingUpdate, timingReqSensor, timingSendMqtt; //Таймеры для millis()
|
||||
int PROGMEM nextM5Update = 1450000, nextMqttSend = 10000; //Раз в 7 часов //каждые 7.5 минут запрос обновления с сервера //опрос датчиков раз в 10 секунд
|
||||
|
||||
bool mqttSendFlag = false, safetyStateNow = false, safetyStateOld = false, flag = false;
|
||||
int reqCounter = 0;
|
||||
long rssi = 0;
|
||||
|
||||
char bufTopic[140], bufTopic1[140], bufTopic2[140], bufWillTopic[150], bufAngleTopic[150], readCh;
|
||||
String string_convert = "";
|
||||
float arrData[18];
|
||||
byte indexs;
|
||||
|
||||
int disconnectMQTT();
|
||||
int setMqttServer(const char *mqttHostNameF, unsigned int mqttPortF);
|
||||
int reqNtpTime();
|
||||
|
||||
//Настройки
|
||||
void setup()
|
||||
{
|
||||
|
||||
M5.begin(true, false, true);
|
||||
delay(50);
|
||||
pinMode(TRIGGER_PIN, INPUT);
|
||||
|
||||
Serial.begin(9600);
|
||||
Serial1.begin(9600, SERIAL_8N1, 21, 25);
|
||||
|
||||
Serial.setDebugOutput(true);
|
||||
|
||||
DeviceAddress deviceAddress;
|
||||
for (int i = 0; i < oneWireCount; i++)
|
||||
{
|
||||
sensor[i].setOneWire(&ds18x20[i]);
|
||||
sensor[i].begin();
|
||||
if (sensor[i].getAddress(deviceAddress, 0))
|
||||
sensor[i].setResolution(deviceAddress, 12);
|
||||
}
|
||||
|
||||
WiFi.mode(WIFI_STA);
|
||||
|
||||
delay(100);
|
||||
|
||||
Serial.println(topicTemp);
|
||||
Serial.println(willTopicTemp);
|
||||
|
||||
topicTemp.toCharArray(bufTopic, topicTemp.length() + 1);
|
||||
|
||||
willTopicTemp.toCharArray(bufWillTopic, willTopicTemp.length() + 1);
|
||||
|
||||
// wm.resetSettings(); // wipe settings
|
||||
|
||||
std::vector<const char *> menu = {"wifi", "info", "param", "sep", "restart", "exit"};
|
||||
wm.setMenu(menu);
|
||||
// set dark theme
|
||||
wm.setClass("invert");
|
||||
//set static ip
|
||||
// wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn
|
||||
// wm.setShowStaticFields(true); // force show static ip fields
|
||||
// wm.setShowDnsFields(true); // force show dns field always
|
||||
// wm.setConnectTimeout(20); // how long to try to connect for before continuing
|
||||
wm.setConfigPortalTimeout(30); // auto close configportal after n seconds
|
||||
wm.setMinimumSignalQuality(15); // set min RSSI (percentage) to show in scans, null = 8%
|
||||
wm.setScanDispPerc(true); // show RSSI as percentage not graph icons
|
||||
wm.setWiFiAutoReconnect(true); // if true, enable autoreconnecting
|
||||
|
||||
bool res;
|
||||
|
||||
res = wm.autoConnect("PowerM5Portal", "12345678"); // Подключение к анонимной точке доступа
|
||||
if (!res)
|
||||
{
|
||||
Serial.println("Failed to connect or hit timeout");
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
setMqttServer(mqttHostName, mqttPort);
|
||||
|
||||
if (reqNtpTime() == 1)
|
||||
{
|
||||
reqNtpTime();
|
||||
reqNtpTime();
|
||||
}
|
||||
}
|
||||
|
||||
int getIpBlock(int index, String str)
|
||||
{
|
||||
char separator = '.';
|
||||
int found = 0;
|
||||
int strIndex[] = {0, -1};
|
||||
int maxIndex = str.length() - 1;
|
||||
|
||||
for (int i = 0; i <= maxIndex && found <= index; i++)
|
||||
{
|
||||
if (str.charAt(i) == separator || i == maxIndex)
|
||||
{
|
||||
found++;
|
||||
strIndex[0] = strIndex[1] + 1;
|
||||
strIndex[1] = (i == maxIndex) ? i + 1 : i;
|
||||
}
|
||||
}
|
||||
|
||||
return found > index ? str.substring(strIndex[0], strIndex[1]).toInt() : 0;
|
||||
}
|
||||
|
||||
IPAddress str2IP(String str)
|
||||
{
|
||||
IPAddress ret(getIpBlock(0, str), getIpBlock(1, str), getIpBlock(2, str), getIpBlock(3, str));
|
||||
return ret;
|
||||
}
|
||||
|
||||
int setMqttServer(const char *mqttHostNameF, unsigned int mqttPortF)
|
||||
{
|
||||
mdns_init();
|
||||
|
||||
IPAddress ipaddr;
|
||||
OTApreferences.begin("ota-config");
|
||||
|
||||
String keyIpMqtt = OTApreferences.getString("mqttip", "0");
|
||||
Serial.print("keyIpMqtt: ");
|
||||
Serial.println(keyIpMqtt);
|
||||
|
||||
if (keyIpMqtt == "0")
|
||||
{
|
||||
//Запрос по хостнейму .local
|
||||
ipaddr = MDNS.queryHost(mqttHostNameF, 4000);
|
||||
//Таймаут 4 секунды
|
||||
//Если не получили по хостнейму МДНС
|
||||
Serial.print("mdns: ");
|
||||
Serial.println(ipaddr);
|
||||
|
||||
if (ipaddr.toString() == "0.0.0.0")
|
||||
{
|
||||
//Запрос к ДНС по адресу сайта
|
||||
int err = WiFi.hostByName(mqttHostNameF, ipaddr);
|
||||
////real internal timeout in lwip library is 14[s]
|
||||
//Если получили по хостнейму
|
||||
if (err == 1)
|
||||
{
|
||||
Serial.print("hostByName: ");
|
||||
Serial.println(ipaddr);
|
||||
MqttClient.setServer(ipaddr, mqttPortF);
|
||||
OTApreferences.putString("mqttip", ipaddr.toString());
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.print("All method not FOUND IP - RESET MQTT IP");
|
||||
}
|
||||
}
|
||||
else
|
||||
{ //Если все хорошо
|
||||
OTApreferences.putString("mqttip", ipaddr.toString());
|
||||
MqttClient.setServer(ipaddr, mqttPortF);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MqttClient.setServer(str2IP(keyIpMqtt), mqttPortF);
|
||||
}
|
||||
|
||||
OTApreferences.end();
|
||||
return 0;
|
||||
}
|
||||
|
||||
void setServCall(IPAddress SetIpaddr)
|
||||
{
|
||||
MqttClient.setServer(SetIpaddr, mqttPort);
|
||||
// MqttClient.setCallback(callback);
|
||||
}
|
||||
|
||||
//Функция получения данных из MQTT если мы подпишемся на топики
|
||||
// void callback(char *topic, byte *payload, unsigned int length)
|
||||
// {
|
||||
// //Serial.print("Message arrived [");
|
||||
// //Serial.print(topic);
|
||||
// //Serial.print("] ");
|
||||
// for (int i = 0; i < length; i++)
|
||||
// {
|
||||
// //Serial.print((char)payload[i]);
|
||||
// }
|
||||
// //Serial.println();
|
||||
// }
|
||||
|
||||
//Запрос времени NTP и установка локлаьного времени
|
||||
int reqNtpTime()
|
||||
{
|
||||
if (timeClient.update())
|
||||
{
|
||||
uint32_t timeEpoch = timeClient.getEpochTime();
|
||||
if (timeEpoch < 1600000000)
|
||||
{
|
||||
Serial.println("Error reqNtpTime() Time");
|
||||
return 1;
|
||||
}
|
||||
setTime(timeEpoch);
|
||||
// Serial.print(timeEpoch);
|
||||
// Serial.print(" <=ntp== ==device=> ");
|
||||
// Serial.println(now());
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Нажатие кнопки для сброса
|
||||
void checkButton()
|
||||
{
|
||||
Serial.println("Button RESET Pressed");
|
||||
disconnectMQTT();
|
||||
delay(100);
|
||||
wm.resetSettings();
|
||||
|
||||
OTApreferences.begin("ota-config");
|
||||
OTApreferences.putString("mqttip", "0");
|
||||
OTApreferences.end();
|
||||
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
//Обновление прошивки, происходит проверка и загрузка
|
||||
//Делается Get запрос на хостинг проверяется хеш, если хеш
|
||||
void OTAUpdate()
|
||||
{
|
||||
////Serial.\println("OTAUpdate()");
|
||||
bool flagOTA = false;
|
||||
String keyOTA;
|
||||
String payload;
|
||||
|
||||
OTApreferences.begin("ota-config");
|
||||
|
||||
if (WiFi.status() == WL_CONNECTED)
|
||||
{
|
||||
|
||||
HTTPClient http;
|
||||
String serverPath = "http://meteosence.s-host.net/airqa/airquality.php?meteopas=94386jdfg54gjn5n5trn8&mac=" + macc + "&meteodata=gethash";
|
||||
|
||||
http.begin(serverPath.c_str());
|
||||
int httpResponseCode = http.GET();
|
||||
|
||||
if (httpResponseCode > 0)
|
||||
{
|
||||
Serial.print("HTTP Response code: ");
|
||||
Serial.println(httpResponseCode);
|
||||
payload = http.getString();
|
||||
Serial.println(payload);
|
||||
|
||||
if (payload != "errno" || payload != "errfi")
|
||||
{
|
||||
|
||||
keyOTA = OTApreferences.getString("md5HashOTA");
|
||||
|
||||
if (keyOTA.length() <= 0)
|
||||
{
|
||||
OTApreferences.putString("md5HashOTA", "undifined");
|
||||
}
|
||||
|
||||
keyOTA = OTApreferences.getString("md5HashOTA");
|
||||
|
||||
if (payload != keyOTA)
|
||||
{
|
||||
flagOTA = true;
|
||||
OTApreferences.putString("md5HashOTA", payload);
|
||||
//Serial.println("flagOTA = true;");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//Serial.println("Hosting return error HASH or error REQUEST");
|
||||
errorID = 2;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
errorID = 3;
|
||||
Serial.print("Error code HTTP: ");
|
||||
Serial.println(httpResponseCode);
|
||||
}
|
||||
// Free resources
|
||||
http.end();
|
||||
}
|
||||
else
|
||||
{
|
||||
errorID = 4;
|
||||
Serial.println("WiFi Disconnected");
|
||||
}
|
||||
|
||||
if (flagOTA == true)
|
||||
{
|
||||
flagOTA = false;
|
||||
//Serial.println("flagOTA = false;");
|
||||
|
||||
t_httpUpdate_return ret = ESPhttpUpdate.update("http://meteosence.s-host.net/airqa/vent/tinput.bin");
|
||||
|
||||
//После update ничего не происходит, такая вот особенность.
|
||||
//Если все прошло хорошо, перезагрузка на новую прошивку
|
||||
|
||||
//Serial.print("ret ");
|
||||
//Serial.println(ret);
|
||||
|
||||
switch (ret)
|
||||
{
|
||||
|
||||
case HTTP_UPDATE_FAILED:
|
||||
//Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
|
||||
//Serial.println(ESPhttpUpdate.getLastError());
|
||||
//Serial.println(ESPhttpUpdate.getLastErrorString().c_str());
|
||||
//Serial.println("HTTP_UPDATE_FAILD Error");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_NO_UPDATES:
|
||||
//Serial.println("HTTP_UPDATE_NO_UPDATES");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
|
||||
case HTTP_UPDATE_OK:
|
||||
//Serial.println("HTTP_UPDATE_OK");
|
||||
|
||||
ESP.restart();
|
||||
break;
|
||||
}
|
||||
}
|
||||
OTApreferences.end();
|
||||
}
|
||||
|
||||
//Получение мак адреса
|
||||
String getMacAddress()
|
||||
{
|
||||
uint8_t baseMac[6];
|
||||
esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
|
||||
char baseMacChr[18] = {0};
|
||||
sprintf(baseMacChr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
|
||||
return String(baseMacChr);
|
||||
}
|
||||
|
||||
//Отправка данных по MQTT
|
||||
int SendMqttReq(bool sendVal = true, bool sendStatus = true, byte statusConn = 1)
|
||||
{
|
||||
if (mqttSendFlag == true)
|
||||
{
|
||||
|
||||
char resultString[200];
|
||||
String JsonData = "";
|
||||
rssi = WiFi.RSSI();
|
||||
unsigned long timeNow = now();
|
||||
|
||||
// {
|
||||
// "val": 1,
|
||||
// "ts": 1617194420
|
||||
// }
|
||||
// Last device status (ts=59s ago):
|
||||
// {
|
||||
// "conn": "on",
|
||||
// "ts": 1617204271,
|
||||
// "exp": 1617204871
|
||||
// }
|
||||
|
||||
if (sendVal == true)
|
||||
{
|
||||
|
||||
Serial.print("Requesting temperatures...");
|
||||
for (int i = 0; i < oneWireCount; i++)
|
||||
{
|
||||
sensor[i].requestTemperatures();
|
||||
}
|
||||
Serial.println("DONE");
|
||||
|
||||
delay(1000);
|
||||
|
||||
for (int i = 0; i < oneWireCount; i++)
|
||||
{
|
||||
float temperature = sensor[i].getTempCByIndex(0);
|
||||
Serial.print("Temperature for the sensor ");
|
||||
Serial.print(i);
|
||||
Serial.print(" is ");
|
||||
Serial.println(temperature);
|
||||
|
||||
// String idnum = String(i);
|
||||
// const char num = idnum.c_str();
|
||||
|
||||
doc["t"][i] = temperature;
|
||||
}
|
||||
doc["ts"] = timeNow;
|
||||
serializeJson(doc, JsonData);
|
||||
|
||||
// doc.remove("V");
|
||||
doc.remove("ts");
|
||||
|
||||
doc.clear();
|
||||
doc.garbageCollect();
|
||||
|
||||
Serial.println(JsonData); //Вывод JSON строки в консоль
|
||||
JsonData.toCharArray(resultString, JsonData.length() + 1);
|
||||
MqttClient.publish(bufTopic, resultString, true);
|
||||
JsonData = "";
|
||||
}
|
||||
|
||||
if (sendStatus == true)
|
||||
{
|
||||
const char *conn;
|
||||
switch (statusConn)
|
||||
{
|
||||
case 1:
|
||||
conn = "on";
|
||||
break;
|
||||
|
||||
case 2:
|
||||
conn = "off";
|
||||
break;
|
||||
|
||||
case 3:
|
||||
conn = "slp";
|
||||
break;
|
||||
|
||||
case 4:
|
||||
conn = "upd";
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
doc["conn"] = conn;
|
||||
doc["rssi"] = rssi;
|
||||
doc["bsid"] = WiFi.BSSIDstr();
|
||||
doc["ts"] = timeNow;
|
||||
doc["exp"] = timeNow + 10;
|
||||
doc["sv"] = VersionSW;
|
||||
|
||||
JsonData = "";
|
||||
serializeJson(doc, JsonData);
|
||||
Serial.println(JsonData); //Вывод JSON строки в консоль
|
||||
|
||||
doc.clear();
|
||||
doc.garbageCollect();
|
||||
|
||||
JsonData.toCharArray(resultString, JsonData.length() + 1);
|
||||
MqttClient.publish(bufWillTopic, resultString, true);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Переподключение при петери связи с MQTT
|
||||
//7 раз проверили и вернулись в общий цикл что бы вдруг что втянуть обновления
|
||||
void reconnectMqtt()
|
||||
{
|
||||
byte circle = 0;
|
||||
while (!MqttClient.connected())
|
||||
{
|
||||
circle++;
|
||||
if (circle == 7)
|
||||
{
|
||||
|
||||
OTApreferences.begin("ota-config");
|
||||
OTApreferences.putString("mqttip", "0");
|
||||
OTApreferences.end();
|
||||
break;
|
||||
}
|
||||
|
||||
String maccrandom = macc + String(random(0xffff), HEX);
|
||||
const char *clientId = maccrandom.c_str();
|
||||
|
||||
if (MqttClient.connect(clientId, mqttLogin, mqttPass, bufWillTopic, 2, true, willmess))
|
||||
{
|
||||
Serial.println("Mqttconnect - OK");
|
||||
mqttSendFlag = true;
|
||||
SendMqttReq(false, true, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
Serial.print("Mqtt.state() = ");
|
||||
Serial.println(MqttClient.state());
|
||||
/*
|
||||
-4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time
|
||||
-3 : MQTT_CONNECTION_LOST - the network connection was broken
|
||||
-2 : MQTT_CONNECT_FAILED - the network connection failed
|
||||
-1 : MQTT_DISCONNECTED - the client is disconnected cleanly
|
||||
0 : MQTT_CONNECTED - the client is connected
|
||||
1 : MQTT_CONNECT_BAD_PROTOCOL - the server doesn't support the requested version of MQTT
|
||||
2 : MQTT_CONNECT_BAD_CLIENT_ID - the server rejected the client identifier
|
||||
3 : MQTT_CONNECT_UNAVAILABLE - the server was unable to accept the connection
|
||||
4 : MQTT_CONNECT_BAD_CREDENTIALS - the username/password were rejected
|
||||
5 : MQTT_CONNECT_UNAUTHORIZED - the client was not authorized to connect
|
||||
*/
|
||||
mqttSendFlag = false;
|
||||
delay(500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
M5.update();
|
||||
|
||||
if (WiFi.status() != WL_CONNECTED)
|
||||
{
|
||||
Serial.println(WiFi.status());
|
||||
errorID = 6;
|
||||
delay(3000);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
if (!MqttClient.connected())
|
||||
{
|
||||
reconnectMqtt();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////
|
||||
/////////////////////////////////////////////////////////////
|
||||
|
||||
if (millis() - timingSendMqtt > nextMqttSend)
|
||||
{
|
||||
SendMqttReq();
|
||||
timingSendMqtt = millis();
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////
|
||||
/////////////////////////////////////////////////////////////
|
||||
|
||||
// 40 секунд и происходит сброс настроек WIFI
|
||||
if (M5.Btn.wasReleasefor(40000))
|
||||
{
|
||||
checkButton();
|
||||
}
|
||||
|
||||
//По таймеру запруск обновления прошивки
|
||||
if (millis() - timingUpdate > nextM5Update)
|
||||
{
|
||||
reqNtpTime();
|
||||
SendMqttReq(false, true, 4);
|
||||
OTAUpdate();
|
||||
SendMqttReq(false, true, 1);
|
||||
timingUpdate = millis();
|
||||
}
|
||||
|
||||
//Таймер отправки данных в брокер
|
||||
MqttClient.loop();
|
||||
}
|
||||
|
||||
int disconnectMQTT()
|
||||
{
|
||||
MqttClient.disconnect();
|
||||
return 0;
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
|
||||
This directory is intended for PlatformIO Unit Testing and project tests.
|
||||
|
||||
Unit Testing is a software testing method by which individual units of
|
||||
source code, sets of one or more MCU program modules together with associated
|
||||
control data, usage procedures, and operating procedures, are tested to
|
||||
determine whether they are fit for use. Unit testing finds problems early
|
||||
in the development cycle.
|
||||
|
||||
More information about PlatformIO Unit Testing:
|
||||
- https://docs.platformio.org/page/plus/unit-testing.html
|
Binary file not shown.
Loading…
Reference in New Issue