libretiny

This commit is contained in:
Mit4el
2024-09-20 12:45:17 +03:00
parent b32abb5a28
commit 596eb9cad4
78 changed files with 8577 additions and 63 deletions

View File

@@ -37,7 +37,11 @@ void addThisDeviceToList() {
AsyncUDP asyncUdp;
void udpListningInit() {
if (asyncUdp.listenMulticast(IPAddress(239, 255, 255, 255), 4210)) {
#if defined(LIBRETINY)
if (asyncUdp.listenMulticast(IPAddress(239, 255, 255, 255), 4210/* , WiFi.localIP() */)) {
#else
if (asyncUdp.listenMulticast(IPAddress(239, 255, 255, 255), 4210)) {
#endif
asyncUdp.onPacket([](AsyncUDPPacket packet) {
// если был включен автоматический поиск устройств то начнем запись в оперативную память
if (jsonReadInt(settingsFlashJson, F("udps")) != 0) {
@@ -65,8 +69,12 @@ void udpListningInit() {
String loacalWorkgroup = "";
jsonRead(settingsFlashJson, F("wg"), loacalWorkgroup);
if (remoteWorkgroup == loacalWorkgroup) {
#if defined(LIBRETINY)
SerialPrint("i", F("UDP"), "IP: " + ipToString(packet.remoteIP()) + ":" + String(packet.remotePort()) + " localIP:"+String(packet.localIP()));
#else
SerialPrint("i", F("UDP"), "IP: " + packet.remoteIP().toString() + ":" + String(packet.remotePort()));
jsonMergeArrays(devListHeapJson, data);
#endif
jsonMergeArrays(devListHeapJson, data);
// эксперементальный вариант отправки нового списка сразу по приходу
// sendStringToWs("devlis", devListHeapJson, -1);
}
@@ -91,7 +99,7 @@ void udpListningInit() {
void udpBroadcastInit() {
// будем отправлять каждые 60 секунд презентацию данного устройства
ts.add(
UDP, 60000, [&](void*) { // UDPP
UDPt, 60000, [&](void*) { // UDPP
if (isNetworkActive()) {
SerialPrint("i", F("UDP"), F("Broadcast device presentation"));
asyncUdp.broadcastTo(getThisDevice().c_str(), 4210);

View File

@@ -66,7 +66,7 @@ void clearConfigure() {
if (*it) delete *it;
}
IoTItems.clear();
#ifdef libretiny
#ifdef LIBRETINY
valuesFlashJson.remove(0, valuesFlashJson.length());
#else
valuesFlashJson.clear();

View File

@@ -18,14 +18,17 @@ void globalVarsSync()
valuesFlashJson = readFile(F("values.json"), 4096);
valuesFlashJson.replace("\r\n", "");
if (settingsFlashJson == "failed")
return;
mqttPrefix = jsonReadStr(settingsFlashJson, F("mqttPrefix"));
jsonWriteStr_(settingsFlashJson, "id", chipId);
mqttRootDevice = mqttPrefix + "/" + chipId;
#ifdef LIBRETINY
jsonWriteStr_(settingsFlashJson, "ip", ipToString(WiFi.localIP()));
#else
jsonWriteStr_(settingsFlashJson, "ip", WiFi.localIP().toString());
#endif
// это не используется - удалить в последствии
jsonWriteStr_(settingsFlashJson, "root", mqttRootDevice);
}
@@ -134,7 +137,7 @@ uint32_t getFlashChipIdNew()
}
// esp_flash_read_id(nullptr, &flashChipId);
#elif defined(ESP8266)
#elif defined(ESP8266) || defined(LIBRETINY)
flashChipId = ESP.getFlashChipId();
#endif // ifdef ESP32
}
@@ -148,9 +151,12 @@ const String getMacAddress()
#if defined(ESP8266)
WiFi.macAddress(mac);
sprintf(buf, MACSTR, MAC2STR(mac));
#else
#elif defined(ESP32)
esp_read_mac(mac, ESP_MAC_WIFI_STA);
sprintf(buf, MACSTR, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
#elif defined(LIBRETINY)
uint32_t macid = lt_cpu_get_mac_id ();
memcpy(buf, &macid, sizeof(macid));
#endif
return String(buf);
}

View File

@@ -20,7 +20,7 @@ ESP8266WebServer HTTP(80);
#ifdef ESP32
WebServer HTTP(80);
#endif
#ifdef libretiny
#ifdef LIBRETINY
WebServer HTTP(80);
#endif
#endif

View File

@@ -3,7 +3,9 @@
#include "classes/IoTDB.h"
#include "utils/Statistic.h"
#include "classes/IoTBench.h"
#ifndef LIBRETINY
#include <Wire.h>
#endif
#include "DebugTrace.h"
#if defined(esp32s2_4mb) || defined(esp32s3_16mb)
#include <USB.h>
@@ -143,7 +145,7 @@ void setup() {
#ifdef ESP32
Wire.end();
Wire.begin(pinSDA, pinSCL, (uint32_t)i2cFreq);
#else
#elif defined(ESP8266)
Wire.begin(pinSDA, pinSCL);
Wire.setClock(i2cFreq);
#endif
@@ -211,9 +213,10 @@ void setup() {
// запуск работы udp
addThisDeviceToList();
#ifdef UDP_ENABLED
udpListningInit();
udpBroadcastInit();
#endif
// создаем событие завершения конфигурирования для возможности выполнения блока кода при загрузке
createItemFromNet("onStart", "1", 1);

View File

@@ -1,9 +1,23 @@
#include "NTP.h"
#if defined(LIBRETINY)
#include "lwip/apps/sntp.h"
#endif
#include "Global.h"
#include "utils/SerialPrint.h"
void ntpInit() {
#if defined(USE_LIBRETINY)
if (sntp_enabled()) {
sntp_stop();
}
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, jsonReadStr(settingsFlashJson, F("ntp")).c_str());
sntp_setservername(1, "pool.ntp.org");
sntp_setservername(2, "ru.pool.ntp.org");
sntp_init();
#endif
synchTime();
ts.add(
@@ -44,7 +58,15 @@ void ntpInit() {
}
void synchTime() {
#if defined LIBRETINY
// force resync
if (sntp_enabled()) {
sntp_stop();
sntp_init();
}
#else
configTime(0, 0, "pool.ntp.org", "ru.pool.ntp.org", jsonReadStr(settingsFlashJson, F("ntp")).c_str());
#endif
}
//событие смены даты

View File

@@ -59,6 +59,11 @@ String ESP_getResetReason(void) {
return ESP.getResetReason();
}
#endif
#ifdef LIBRETINY
String ESP_getResetReason(void) {
return ESP.getResetReason();
}
#endif
#if defined(esp32s2_4mb) || defined(esp32s3_16mb) || defined(esp32c3m_4mb)
String ESP_getResetReason(void) {
// return ESP32GetResetReason(0); // CPU 0

View File

@@ -231,7 +231,12 @@ bool handleFileRead(String path) {
return the path of the closest parent still existing
*/
String lastExistingParent(String path) {
while (!path.isEmpty() && !FileFS.exists(path)) {
#ifndef LIBRETINY
while (!path.isEmpty() && !FileFS.exists(path))
#else
while (!path.length()==0 && !FileFS.exists(path))
#endif
{
if (path.lastIndexOf('/') > 0) {
path = path.substring(0, path.lastIndexOf('/'));
} else {
@@ -278,7 +283,7 @@ void handleFileUpload() {
}
}
#ifdef ESP8266
#if defined ESP8266
void deleteRecursive(String path) {
File file = FileFS.open(path, "r");
bool isDir = file.isDirectory();
@@ -299,14 +304,14 @@ void deleteRecursive(String path) {
}
#endif
#ifdef ESP32
#if defined ESP32 || defined LIBRETINY
struct treename {
uint8_t type;
char *name;
};
void deleteRecursive(String path) {
fs::File dir = FileFS.open(path);
fs::File dir = FileFS.open(path.c_str());
if (!dir.isDirectory()) {
Serial.printf("%s is a file\n", path);
@@ -321,7 +326,11 @@ void deleteRecursive(String path) {
while (entry = dir.openNextFile()) {
if (entry.isDirectory()) {
#if defined ESP32
deleteRecursive(entry.path());
#elif defined LIBRETINY
deleteRecursive(entry.fullName());
#endif
} else {
String tmpname = path + "/" + strdup(entry.name()); // buffer file name
entry.close();
@@ -342,10 +351,15 @@ void deleteRecursive(String path) {
*/
void handleFileDelete() {
String path = HTTP.arg(0);
#ifndef LIBRETINY
if (path.isEmpty() || path == "/") {
return replyBadRequest("BAD PATH");
}
#else
if (path.length()==0 || path == "/") {
return replyBadRequest("BAD PATH");
}
#endif
// DBG_OUTPUT_PORT.println(String("handleFileDelete: ") + path);
if (!FileFS.exists(path)) {
return replyNotFound(FPSTR(FILE_NOT_FOUND));
@@ -368,10 +382,15 @@ void handleFileDelete() {
*/
void handleFileCreate() {
String path = HTTP.arg("path");
#ifndef LIBRETINY
if (path.isEmpty()) {
return replyBadRequest(F("PATH ARG MISSING"));
}
#else
if (path.length()==0) {
return replyBadRequest(F("PATH ARG MISSING"));
}
#endif
#ifdef USE_SPIFFS
if (checkForUnsupportedPath(path).length() > 0) {
return replyServerError(F("INVALID FILENAME"));
@@ -386,7 +405,11 @@ void handleFileCreate() {
}
String src = HTTP.arg("src");
#ifndef LIBRETINY
if (src.isEmpty()) {
#else
if (src.length()==0) {
#endif
// No source specified: creation
// DBG_OUTPUT_PORT.println(String("handleFileCreate: ") + path);
if (path.endsWith("/")) {
@@ -404,6 +427,9 @@ void handleFileCreate() {
#endif
#ifdef ESP32
file.write(0);
#endif
#ifdef LIBRETINY
file.write((uint8_t)0);
#endif
file.close();
} else {
@@ -509,7 +535,7 @@ void handleFileList() {
}
#endif
#ifdef ESP32
#if defined ESP32
void handleFileList() {
if (!HTTP.hasArg("dir")) {
HTTP.send(500, "text/plain", "BAD ARGS");
@@ -517,15 +543,29 @@ void handleFileList() {
}
String path = HTTP.arg("dir");
// DBG_OUTPUT_PORT.println("handleFileList: " + path);
if (path != "/" && !FileFS.exists(path)) {
return replyBadRequest("BAD PATH");
}
//path = "/build/";
Serial.println("handleFileList: " + path);
#if defined LIBRETINY
File root = FileFS.open(path.c_str());
//Dir root = FileFS.openDir(path);
Serial.println("handleFileList FIRST OPEN Name: " + String(root.name()));
#else
File root = FileFS.open(path);
#endif
path = String();
String output = "[";
if (root.isDirectory()) {
Serial.println("handleFileList IS DIR: " + String(root.name()));
//root.close();
File file = root.openNextFile();
Serial.println("handleFileList openNextFile: " + String(file.name()));
while (file) {
if (output != "[") {
output += ',';
}
@@ -549,6 +589,72 @@ void handleFileList() {
}
#endif
#if defined LIBRETINY
void handleFileList() {
if (!HTTP.hasArg("dir")) {
HTTP.send(500, "text/plain", "BAD ARGS");
return;
}
String path = HTTP.arg("dir");
if (path != "/" && !FileFS.exists(path)) {
return replyBadRequest("BAD PATH");
}
lfs_dir_t dir;
struct lfs_info info;
int err = lfs_dir_open(&lfs, &dir, path);
if (err) {
HTTP.send(500, "text/plain", "FAIL OPEN DIR");
return;
}
String output = "[";
while (true) {
int res = lfs_dir_read(&lfs, &dir, &info);
if (res < 0) {
lfs_dir_close(&lfs, &dir);
return err;
}
if (!res) {
break;
}
Serial.printf("%s %d", info.name, info.type);
if (output != "[") {
output += ',';
}
output += "{\"type\":\"";
// output += (file.isDirectory()) ? "dir" : "file";
if (info.type == LFS_TYPE_DIR) {
output += "dir";
} else {
output += F("file\",\"size\":\"");
output += info.size;
}
output += "\",\"name\":\"";
output += String(info.name);
output += "\"}";
//file = root.openNextFile();
}
err = lfs_dir_close(&lfs, &dir);
if (err) {
HTTP.send(500, "text/plain", "FAIL CLOSE DIR");
return;
}
output += "]";
HTTP.send(200, "text/json", output);
}
#endif
/*
The "Not Found" handler catches all URI not explicitly declared in code
First try to find and return the requested file from the filesystem,
@@ -560,6 +666,9 @@ void handleNotFound() {
#endif
#ifdef ESP32
String uri = WebServer::urlDecode(HTTP.uri()); // required to read paths with blanks
#endif
#ifdef LIBRETINY
String uri = WebServer::urlDecode(HTTP.uri()); // required to read paths with blanks
#endif
if (handleFileRead(uri)) {
return;

View File

@@ -36,6 +36,7 @@ void upgrade_firmware(int type, String path) {
bool upgradeFS(String path) {
bool ret = false;
#ifndef LIBRETINY
WiFiClient wifiClient;
SerialPrint("!!!", F("Update"), "Start upgrade FS... " + path);
@@ -67,11 +68,13 @@ bool upgradeFS(String path) {
SerialPrint("E", F("Update"), "HTTP_UPDATE_NO_UPDATES");
}
}
#endif
return ret;
}
bool upgradeBuild(String path) {
bool ret = false;
#ifndef LIBRETINY
WiFiClient wifiClient;
SerialPrint("!!!", F("Update"), "Start upgrade BUILD... " + path);
@@ -102,6 +105,7 @@ bool upgradeBuild(String path) {
SerialPrint("E", F("Update"), "HTTP_UPDATE_NO_UPDATES");
}
}
#endif
return ret;
}

View File

@@ -378,6 +378,7 @@ void sendFileToWsByFrames(const String& filename, const String& header, const St
auto path = filepath(filename);
auto file = FileFS.open(path, "r");
//SerialPrint("I", "sendFileToWsByFrames", ("reed file: ")+ path);
if (!file) {
SerialPrint("E", "FS", F("reed file error"));
return;
@@ -425,16 +426,25 @@ void sendFileToWsByFrames(const String& filename, const String& header, const St
continuation = true;
}
// Serial.println(String(i) + ") " + "ws: " + String(client_id) + " fr sz:
// " + String(size) + " fin: " + String(fin) + " cnt: " +
// String(continuation));
Serial.println(String(i) + ") " + "ws: " + String(client_id) + " fr sz: "
+ String(size) + " fin: " + String(fin) + " cnt: " +
String(continuation));
#ifdef ASYNC_WEB_SOCKETS
if (client_id == -1) {
//ws.broadcastBIN(frameBuf, size, fin, continuation);
ws.binaryAll(frameBuf, size);
} else {
//ws.sendBIN(client_id, frameBuf, size, fin, continuation);
ws.binary(client_id,frameBuf, size);
}
#elif defined (STANDARD_WEB_SOCKETS)
if (client_id == -1) {
standWebSocket.broadcastBIN(frameBuf, size, fin, continuation);
} else {
standWebSocket.sendBIN(client_id, frameBuf, size, fin, continuation);
}
#endif
}
i++;
}
@@ -444,7 +454,12 @@ void sendFileToWsByFrames(const String& filename, const String& header, const St
}
void sendStringToWs(const String& header, String& payload, int client_id) {
if ((!getNumAPClients() && !isNetworkActive()) || !getNumWSClients()) {
#ifdef LIBRETINY
if (/* (!getNumAPClients() && !isNetworkActive()) || */ !getNumWSClients()) {
#else
if ( (!getNumAPClients() && !isNetworkActive()) || !getNumWSClients()) {
#endif
// SerialPrint("E", "sendStringToWs", "getNumAPClients: " + String(getNumAPClients()) + "isNetworkActive: " + String(isNetworkActive() + "getNumWSClients: " + String(getNumWSClients())));
// standWebSocket.disconnect(); // это и ниже надо сделать при -
// standWebSocket.close(); // - отключении AP И WiFi(STA), надо менять ядро WiFi. Сейчас не закрывается сессия клиента при пропаже AP И WiFi(STA)
return;
@@ -457,14 +472,22 @@ void sendStringToWs(const String& header, String& payload, int client_id) {
String msg = header + "|0012|" + payload;
size_t totalSize = msg.length();
// SerialPrint("E", "sendStringToWs", msg);
char dataArray[totalSize];
msg.toCharArray(dataArray, totalSize + 1);
#ifdef ASYNC_WEB_SOCKETS
if (client_id == -1) {
ws.binaryAll((uint8_t*)dataArray, totalSize);
} else {
ws.binary(client_id, (uint8_t*)dataArray, totalSize);
}
#elif defined (STANDARD_WEB_SOCKETS)
if (client_id == -1) {
standWebSocket.broadcastBIN((uint8_t*)dataArray, totalSize);
} else {
standWebSocket.sendBIN(client_id, (uint8_t*)dataArray, totalSize);
}
#endif
}
void sendDeviceList(uint8_t num) {
@@ -478,5 +501,8 @@ void sendDeviceList(uint8_t num) {
SerialPrint("i", "FS", "flash list");
}
}
int getNumWSClients() { return standWebSocket.connectedClients(false); }
#ifdef ASYNC_WEB_SOCKETS
int getNumWSClients() { return ws.count(); }
#elif defined (STANDARD_WEB_SOCKETS)
int getNumWSClients() { return standWebSocket.connectedClients(false); }
#endif

View File

@@ -9,7 +9,7 @@ IoTGpio::~IoTGpio(){
}
#ifndef LIBRETINY
void IoTGpio::pinMode(int pin, uint8_t mode) {
int pinH = pin/100;
if (_drivers[pinH]) _drivers[pinH]->pinMode(pin - pinH*100, mode);
@@ -21,7 +21,19 @@ void IoTGpio::digitalWrite(int pin, uint8_t val) {
if (_drivers[pinH]) _drivers[pinH]->digitalWrite(pin - pinH*100, val);
else ::digitalWrite(pin, val);
}
#else
void IoTGpio::pinMode(int pin, uint8_t mode) {
int pinH = pin/100;
if (_drivers[pinH]) _drivers[pinH]->pinMode(pin - pinH*100, mode);
else ::pinMode(pin, (PinMode)mode);
}
void IoTGpio::digitalWrite(int pin, uint8_t val) {
int pinH = pin/100;
if (_drivers[pinH]) _drivers[pinH]->digitalWrite(pin - pinH*100, val);
else ::digitalWrite(pin, (PinStatus)val);
}
#endif
int IoTGpio::digitalRead(int pin) {
int pinH = pin/100;
if (_drivers[pinH]) return _drivers[pinH]->digitalRead(pin - pinH*100);
@@ -51,7 +63,11 @@ void IoTGpio::analogWrite(int pin, int val) {
void IoTGpio::digitalInvert(int pin) {
int pinH = pin/100;
if (_drivers[pinH]) _drivers[pinH]->digitalInvert(pin - pinH*100);
else ::digitalWrite(pin, 1 - ::digitalRead(pin));
#ifdef LIBRETINY
else ::digitalWrite(pin, (PinStatus)(1 - ::digitalRead(pin)));
#else
else ::digitalWrite(pin, (1 - ::digitalRead(pin)));
#endif
}

View File

@@ -414,11 +414,11 @@ IoTValue sysExecute(SysOp command, std::vector<IoTValue> &param) {
case sysop_deepSleep:
if (param.size()) {
Serial.printf("Ушел спать на %d сек...", (int)param[0].valD);
#ifdef ESP32
#if defined(ESP32)
esp_sleep_enable_timer_wakeup(param[0].valD * 1000000);
delay(1000);
esp_deep_sleep_start();
#else
#elif defined(ESP8266)
ESP.deepSleep(param[0].valD * 1000000);
#endif
}
@@ -435,7 +435,7 @@ IoTValue sysExecute(SysOp command, std::vector<IoTValue> &param) {
if (param.size() == 2) {
// Serial.printf("Call from sysExecute %s %s\n", param[0].valS.c_str(), param[1].valS.c_str());
String tmpStr = param[1].valS;
if (param[1].isDecimal) tmpStr = param[1].valD;
if (param[1].isDecimal) tmpStr = String(param[1].valD);
value.valD = mqtt.publish(param[0].valS.c_str(), tmpStr.c_str(), false);
}
break;
@@ -658,7 +658,7 @@ int IoTScenario::gettok() {
LastChar = getLastChar();
if (isalpha(LastChar) || LastChar == '_') { // идентификатор: [a-zA-Z][a-zA-Z0-9]*
IdentifierStr = (char)LastChar;
IdentifierStr = String((char)LastChar);
while (isalnum((LastChar = getLastChar())) || LastChar == '_') {
IdentifierStr += (char)LastChar;
}

View File

@@ -138,12 +138,19 @@ public:
~BL0937wh(){};
};
#if defined LIBRETINY
void /* ICACHE_RAM_ATTR */ bl0937_cf1_interrupt()
#else
void ICACHE_RAM_ATTR bl0937_cf1_interrupt()
#endif
{
bl0937->cf1_interrupt();
}
#if defined LIBRETINY
void /* ICACHE_RAM_ATTR */ bl0937_cf_interrupt()
#else
void ICACHE_RAM_ATTR bl0937_cf_interrupt()
#endif
{
bl0937->cf_interrupt();
}

View File

@@ -177,16 +177,21 @@ void BL0937::setResistors(double current, double voltage_upstream, double voltag
_calculateDefaultMultipliers();
}
}
#if defined LIBRETINY
void /* ICACHE_RAM_ATTR */ BL0937::cf_interrupt() {
#else
void ICACHE_RAM_ATTR BL0937::cf_interrupt() {
#endif
unsigned long now = micros();
_power_pulse_width = now - _last_cf_interrupt;
_last_cf_interrupt = now;
_pulse_count++;
}
#if defined LIBRETINY
void /* ICACHE_RAM_ATTR */ BL0937::cf1_interrupt() {
#else
void ICACHE_RAM_ATTR BL0937::cf1_interrupt() {
#endif
unsigned long now = micros();
if ((now - _first_cf1_interrupt) > _pulse_timeout) {

View File

@@ -174,7 +174,11 @@ class Loging : public IoTItem {
SerialPrint("E", F("Loging"), "'" + id + "' db file writing error, return");
return;
}
#ifdef LIBRETINY
SerialPrint("i", F("Loging"), "'" + id + "' file created http://" + ipToString(WiFi.localIP()) + path);
#else
SerialPrint("i", F("Loging"), "'" + id + "' file created http://" + WiFi.localIP().toString() + path);
#endif
}
void addNewDataToExistingFile(String &path, String &logData) {
@@ -183,7 +187,11 @@ class Loging : public IoTItem {
SerialPrint("i", F("Loging"), "'" + id + "' file writing error, return");
return;
};
#ifdef LIBRETINY
SerialPrint("i", F("Loging"), "'" + id + "' loging in file http://" + ipToString(WiFi.localIP()) + path);
#else
SerialPrint("i", F("Loging"), "'" + id + "' loging in file http://" + WiFi.localIP().toString() + path);
#endif
}
// данная функция уже перенесена в ядро и будет удалена в последствии

View File

@@ -139,7 +139,11 @@ class LogingDaily : public IoTItem {
SerialPrint("E", F("LogingDaily"), "'" + id + "' db file writing error, return");
return;
}
#ifdef LIBRETINY
SerialPrint("i", F("LogingDaily"), "'" + id + "' file created http://" + ipToString(WiFi.localIP()) + path);
#else
SerialPrint("i", F("LogingDaily"), "'" + id + "' file created http://" + WiFi.localIP().toString() + path);
#endif
}
void addNewDataToExistingFile(String &path, String &logData) {
@@ -148,7 +152,11 @@ class LogingDaily : public IoTItem {
SerialPrint("i", F("LogingDaily"), "'" + id + "' file writing error, return");
return;
};
#ifdef LIBRETINY
SerialPrint("i", F("LogingDaily"), "'" + id + "' LogingDaily in file http://" + ipToString(WiFi.localIP()) + path);
#else
SerialPrint("i", F("LogingDaily"), "'" + id + "' LogingDaily in file http://" + WiFi.localIP().toString() + path);
#endif
}
bool hasDayChanged() {

View File

@@ -77,7 +77,7 @@ public:
if (httpCode > 0)
{
ret = httpCode;
ret = String(httpCode);
if (httpCode == HTTP_CODE_OK)
{

View File

@@ -60,9 +60,12 @@ File seekFile(const String& filename, size_t position) {
const String writeFile(const String& filename, const String& str) {
String path = filepath(filename);
#ifdef ESP32
#if defined ESP32
auto file = FileFS.open(path, FILE_WRITE, true);
#endif
#if defined LIBRETINY
auto file = FileFS.open(path, FILE_WRITE);
#endif
#ifdef ESP8266
auto file = FileFS.open(path, FILE_WRITE);
#endif
@@ -77,9 +80,12 @@ const String writeFile(const String& filename, const String& str) {
const String writeEmptyFile(const String& filename) {
String path = filepath(filename);
#ifdef ESP32
#if defined ESP32
auto file = FileFS.open(path, FILE_WRITE, true);
#endif
#if defined LIBRETINY
auto file = FileFS.open(path, FILE_WRITE);
#endif
#ifdef ESP8266
auto file = FileFS.open(path, FILE_WRITE);
#endif
@@ -285,7 +291,7 @@ String getFilesList(String& directory) {
#endif
}
#if defined(ESP8266)
#if defined(ESP8266) || defined (LIBRETINY)
bool getInfo(FSInfo& info) { return FileFS.info(info); }
// Информация о ФС

View File

@@ -1,3 +1,4 @@
#ifndef LIBRETINY
#include <Wire.h>
#include "utils/SerialPrint.h"
@@ -29,4 +30,5 @@ void scanI2C() {
message += "done\n";
SerialPrint("i", "I2C Scaner", message);
}
}
#endif

View File

@@ -36,7 +36,11 @@ void updateDeviceStatus() {
if (httpResponseCode > 0) {
ret = http.errorToString(httpResponseCode).c_str();
if (httpResponseCode == HTTP_CODE_OK) {
#ifndef LIBRETINY
String payload = http.getString();
#else
String payload = httpGetString(http);
#endif
ret += " " + payload;
}
} else {

View File

@@ -2,12 +2,32 @@
#include <vector>
#define TRIESONE 25 // количество попыток подключения к одной сети из несколких
#define TRIES 40 // количество попыток подключения сети если она одна
/*
IPAddress stringToIp(String strIp)
{
IPAddress ip;
ip.fromString(strIp);
return ip;
} */
void routerConnect()
{
#if !defined LIBRETINY
WiFi.setAutoConnect(false);
WiFi.persistent(false);
#endif
/* String s_staip = "192.168.2.62";
String s_gateway = "192.168.2.1";
String s_netmask = "255.255.255.0";
String s_dns = "192.168.2.1";
SerialPrint("i", "WIFI", "Use static IP");
WiFi.config(stringToIp(s_staip), stringToIp(s_gateway), stringToIp(s_netmask), stringToIp(s_dns));
// bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = (uint32_t)0x00000000, IPAddress dns2 = (uint32_t)0x00000000);
SerialPrint("i", "WIFI", "Static IP: " + s_staip);
SerialPrint("i", "WIFI", "Gateway: " + s_gateway);
SerialPrint("i", "WIFI", "Netmask: " + s_netmask);
SerialPrint("i", "WIFI", "DNS: " + s_dns); */
WiFi.mode(WIFI_STA);
byte triesOne = TRIESONE;
@@ -20,14 +40,16 @@ void routerConnect()
if (_passwordList.size() == 0 && _ssidList[0] == "" && _passwordList[0] == "")
{
#ifndef LIBRETINY
WiFi.begin();
#endif
}
else
{
WiFi.begin(_ssidList[0].c_str(), _passwordList[0].c_str());
#ifdef ESP32
#if defined (ESP32)
WiFi.setTxPower(WIFI_POWER_19_5dBm);
#else
#elif defined (ESP8266)
WiFi.setOutputPower(20.5);
#endif
String _ssid;
@@ -79,8 +101,13 @@ void routerConnect()
else
{
Serial.println("");
#ifdef LIBRETINY
SerialPrint("i", "WIFI", "http://" + ipToString(WiFi.localIP()));
jsonWriteStr(settingsFlashJson, "ip", ipToString(WiFi.localIP()));
#else
SerialPrint("i", "WIFI", "http://" + WiFi.localIP().toString());
jsonWriteStr(settingsFlashJson, "ip", WiFi.localIP().toString());
#endif
mqttInit();
}
@@ -96,13 +123,18 @@ bool startAPMode()
String _ssidAP = jsonReadStr(settingsFlashJson, "apssid");
String _passwordAP = jsonReadStr(settingsFlashJson, "appass");
WiFi.softAP(_ssidAP.c_str(), _passwordAP.c_str());
if (_passwordAP == "")
WiFi.softAP(_ssidAP.c_str());
else
WiFi.softAP(_ssidAP.c_str(), _passwordAP.c_str());
IPAddress myIP = WiFi.softAPIP();
#ifdef LIBRETINY
SerialPrint("i", "WIFI", "AP IP: " + ipToString(myIP));
jsonWriteStr(settingsFlashJson, "ip", ipToString(myIP));
#else
SerialPrint("i", "WIFI", "AP IP: " + myIP.toString());
jsonWriteStr(settingsFlashJson, "ip", myIP.toString());
#endif
if (jsonReadInt(errorsHeapJson, "passer") != 1)
{
ts.add(
@@ -126,7 +158,54 @@ bool startAPMode()
}
return true;
}
#if defined (LIBRETINY)
boolean RouterFind(std::vector<String> jArray)
{
bool res = false;
int n = WiFi.scanComplete();
SerialPrint("i", "WIFI", "scan result: " + String(n, DEC));
if (n == -2)
{ // Сканирование не было запущено, запускаем
SerialPrint("i", "WIFI", "start scanning");
n = WiFi.scanNetworks(false, false); // async, show_hidden
SerialPrint("i", "WIFI", "scan result: " + String(n, DEC));
}
else if (n == -1)
{ // Сканирование все еще выполняется
SerialPrint("i", "WIFI", "scanning in progress");
}
else if (n == 0)
{ // ни одна сеть не найдена
SerialPrint("i", "WIFI", "no networks found");
n = WiFi.scanNetworks(false, false);
SerialPrint("i", "WIFI", "scan result: " + String(n, DEC));
}
if (n > 0)
{
for (int8_t i = 0; i < n; i++)
{
for (int8_t k = 0; k < jArray.size(); k++)
{
if (WiFi.SSID(i) == jArray[k])
{
res = true;
}
}
// SerialPrint("i", "WIFI", (res ? "*" : "") + String(i, DEC) + ") " + WiFi.SSID(i));
jsonWriteStr_(ssidListHeapJson, String(i), WiFi.SSID(i));
// String(WiFi.RSSI(i)
}
}
SerialPrint("i", "WIFI", ssidListHeapJson);
WiFi.scanDelete();
return res;
}
#elif defined (ESP8266) || defined (ESP32)
boolean RouterFind(std::vector<String> jArray)
{
bool res = false;
@@ -170,6 +249,7 @@ boolean RouterFind(std::vector<String> jArray)
WiFi.scanDelete();
return res;
}
#endif
boolean isNetworkActive() {
return WiFi.status() == WL_CONNECTED;
@@ -199,3 +279,39 @@ uint8_t RSSIquality() {
}
return res;
}
#ifdef LIBRETINY
String httpGetString(HTTPClient &http)
{
String payload = "";
int len = http.getSize();
uint8_t buff[128] = { 0 };
WiFiClient * stream = http.getStreamPtr();
// read all data from server
while(http.connected() && (len > 0 || len == -1)) {
// get available data size
size_t size = stream->available();
if(size) {
// read up to 128 byte
int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
// write it to Serial
// Serial.write(buff,c);
//payload += String((char*)buff);
char charBuff[c + 1]; // Create a character array with space for null terminator
memcpy(charBuff, buff, c); // Copy the data to the character array
charBuff[c] = '\0'; // Null-terminate the character array
payload += String(charBuff); // Append the character array to the payload
if(len > 0) {
len -= c;
}
}
delay(1);
}
return payload;
}
#endif