#pragma once #include #include #include #include #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) #include #elif defined(RP2040_PLATFORM) #include #elif defined(ESP32) #include #include "../../arch/esp32/CPUUsageTracker.h" using File = fs::File; #endif #ifdef WITH_RS232_BRIDGE #include "helpers/bridges/RS232Bridge.h" #define WITH_BRIDGE #endif #ifdef WITH_ESPNOW_BRIDGE #include "helpers/bridges/ESPNowBridge.h" #define WITH_BRIDGE #endif #ifdef WITH_MQTT_BRIDGE #include "helpers/bridges/MQTTBridge.h" #define WITH_BRIDGE #endif #ifdef WITH_MQTT_UPLINK #include #endif #include #include #include #include #include #include // Сколько отправителей помним в таблице лимита анонсов (24 байта на запись) #ifndef ADVERT_JAIL_TABLE_SIZE #define ADVERT_JAIL_TABLE_SIZE 24 #endif #include #include #include #include #include #include #include #include #include #include #include #include "RateLimiter.h" #ifdef WITH_BRIDGE extern AbstractBridge* bridge; #endif struct RepeaterStats { uint16_t batt_milli_volts; uint16_t curr_tx_queue_len; int16_t noise_floor; int16_t last_rssi; uint32_t n_packets_recv; uint32_t n_packets_sent; uint32_t total_air_time_secs; uint32_t total_up_time_secs; uint32_t n_sent_flood, n_sent_direct; uint32_t n_recv_flood, n_recv_direct; uint16_t err_events; // was 'n_full_events' int16_t last_snr; // x 4 uint16_t n_direct_dups, n_flood_dups; uint32_t total_rx_air_time_secs; uint32_t n_recv_errors; }; struct WebSensorSnapshot { bool has_battery = false; uint16_t battery_mv = 0; bool has_supply_voltage = false; float supply_voltage_v = NAN; bool has_sensor_temp = false; float sensor_temp_c = NAN; bool has_mcu_temp = false; float mcu_temp_c = NAN; bool has_humidity = false; float humidity_pct = NAN; bool has_pressure = false; float pressure_hpa = NAN; bool has_pressure_altitude = false; float pressure_altitude_m = NAN; bool has_gps = false; bool gps_enabled = false; bool gps_fix = false; bool has_gps_lat = false; float gps_lat = NAN; bool has_gps_lon = false; float gps_lon = NAN; bool has_gps_altitude = false; float gps_altitude_m = NAN; bool has_satellites = false; long satellites = 0; }; #ifndef MAX_CLIENTS #define MAX_CLIENTS 32 #endif #define MAX_PATH_PREFIX_LEN 4 #define MAX_BLACKLIST_ENTRIES 64 #define MAX_CHAN_NAME_FILTERS 32 struct BlacklistEntry { uint8_t len; // 0 = empty slot uint8_t prefix[MAX_PATH_PREFIX_LEN]; }; struct ChanNameFilter { uint8_t hash[PATH_HASH_SIZE]; uint8_t secret[PUB_KEY_SIZE]; char name[32]; }; struct NeighbourInfo { mesh::Identity id; uint32_t advert_timestamp; uint32_t heard_timestamp; int8_t snr; // multiplied by 4, user should divide to get float value char name[24]; // имя из анонса (обрезается), пусто = неизвестно float lat, lon; // координаты из анонса uint8_t has_pos; // 1 = координаты достоверны }; #ifndef FIRMWARE_BUILD_DATE #define FIRMWARE_BUILD_DATE "15 Oct 2026" #endif #ifndef FIRMWARE_VERSION #define FIRMWARE_VERSION "v1.18.0" #endif #define FIRMWARE_ROLE "repeater" #define PACKET_LOG_FILE "/packet_log" class MyMesh : public mesh::Mesh, public CommonCLICallbacks, public WebPanelCommandRunner { FILESYSTEM* _fs; ArchiveStorage* _archive; uint32_t last_millis; uint64_t uptime_millis; unsigned long next_archive_neighbours_flush_ms; unsigned long next_archive_recover_ms; unsigned long next_battery_sample_ms; unsigned long next_history_sample_ms; unsigned long next_local_advert, next_flood_advert; bool _logging; bool _archive_neighbours_dirty; bool _battery_sample_valid; uint16_t _battery_mv_cache; bool _web_sensor_snapshot_valid; WebSensorSnapshot _web_sensor_snapshot; NodePrefs _prefs; ClientACL acl; CommonCLI _cli; uint8_t reply_data[MAX_PACKET_PAYLOAD]; uint8_t reply_path[MAX_PATH_SIZE]; uint8_t reply_path_len; TransportKeyStore key_store; RegionMap region_map, temp_map; RegionEntry* load_stack[8]; RegionEntry* recv_pkt_region; TransportKey default_scope; RateLimiter discover_limiter, anon_limiter; uint32_t pending_discover_tag; unsigned long pending_discover_until; bool region_load_active; unsigned long dirty_contacts_expiry; BlacklistEntry _path_blacklist[MAX_BLACKLIST_ENTRIES]; BlacklistEntry _chan_blacklist[MAX_BLACKLIST_ENTRIES]; // Защита сети: таблица лимита анонсов и бюджет эфира на канал (около 1,6 КБ на ESP32) #if defined(ESP32) AdvertJailEntry _advert_jail[ADVERT_JAIL_TABLE_SIZE]; uint32_t _chan_budget[CHAN_BUDGET_CHANNELS]; #endif ChanNameFilter _chan_name_filters[MAX_CHAN_NAME_FILTERS]; int _num_chan_name_filters; #if MAX_NEIGHBOURS NeighbourInfo neighbours[MAX_NEIGHBOURS]; #endif CayenneLPP telemetry; unsigned long set_radio_at, revert_radio_at; float pending_freq; float pending_bw; uint8_t pending_sf; uint8_t pending_cr; int matching_peer_indexes[MAX_CLIENTS]; #if defined(WITH_RS232_BRIDGE) RS232Bridge bridge; #elif defined(WITH_ESPNOW_BRIDGE) ESPNowBridge bridge; #elif defined(WITH_MQTT_BRIDGE) MQTTBridge bridge; #endif #ifdef WITH_MQTT_UPLINK MQTTUplink mqtt; #endif #if defined(ESP_PLATFORM) NetworkService network; #endif #if defined(ESP_PLATFORM) && WITH_WEB_PANEL WebService web; #endif #if defined(ESP32) CPUUsageTracker _cpu_tracker; #endif StatsHistory _stats_history; struct { bool initialized; bool wifi_connected; bool mqtt_connected; bool web_panel_up; bool archive_mounted; bool low_memory; uint32_t mqtt_token_refresh_count; uint32_t last_low_memory_event_uptime_secs; } _stats_state; void putNeighbour(const mesh::Identity& id, uint32_t timestamp, float snr, const char* name = nullptr, float lat = 0.0f, float lon = 0.0f, bool has_pos = false); size_t getNeighbourCount() const; void updateStatsHistory(unsigned long now_ms); void maybeRecoverArchive(unsigned long now_ms); bool restoreArchiveNeighbours(); void flushArchiveNeighbours(); void maybeFlushArchiveNeighbours(unsigned long now_ms); void recordStatsEvent(uint8_t type, int16_t value = 0); bool appendJsonEvents(char* reply, size_t reply_size, size_t& offset) const; bool appendJsonNeighbours(char* reply, size_t reply_size, size_t& offset) const; bool appendJsonSensors(char* reply, size_t reply_size, size_t& offset, const WebSensorSnapshot& snapshot) const; uint16_t getBatteryMilliVolts(bool force_refresh = false); uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood); uint8_t handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data); uint8_t handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data); uint8_t handleAnonClockReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data); int handleRequest(ClientInfo* sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len); mesh::Packet* createSelfAdvert(); File openAppend(const char* fname); bool isLooped(const mesh::Packet* packet, const uint8_t max_counters[]); bool isPathBlacklisted(const mesh::Packet* packet) const; bool isChanBlacklisted(const mesh::Packet* packet) const; void loadBlacklist(const char* fname, BlacklistEntry* list); void saveBlacklist(const char* fname, const BlacklistEntry* list); bool addToBlacklist(BlacklistEntry* list, const uint8_t* prefix, uint8_t len); bool removeFromBlacklist(BlacklistEntry* list, const uint8_t* prefix, uint8_t len); void formatBlacklist(const BlacklistEntry* list, char* reply); void deriveChanNameFilter(ChanNameFilter& entry, const char* name); bool addChanNameFilter(const char* name); bool removeChanNameFilter(const char* name); void loadChanBlacklist(const char* fname); void saveChanBlacklist(const char* fname); void formatChanBlacklist(char* reply); protected: float getAirtimeBudgetFactor() const override { return _prefs.airtime_factor; } bool allowPacketForward(const mesh::Packet* packet) override; const char* getLogDateTime() override; void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override; void logRx(mesh::Packet* pkt, int len, float score) override; void logTx(mesh::Packet* pkt, int len) override; void logTxFail(mesh::Packet* pkt, int len) override; int calcRxDelay(float score, uint32_t air_time) const override; uint32_t getRetransmitDelay(const mesh::Packet* packet) override; uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override; int getInterferenceThreshold() const override { return _prefs.interference_threshold; } bool getCADEnabled() const override { return _prefs.cad_enabled; } int getAGCResetInterval() const override { return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds } uint8_t getExtraAckTransmitCount() const override { return _prefs.multi_acks; } #if ENV_INCLUDE_GPS == 1 void applyGpsPrefs() { sensors.setSettingValue("gps", _prefs.gps_enabled?"1":"0"); } #endif mesh::DispatcherAction onRecvPacket(mesh::Packet* pkt) override; void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override; int searchPeersByHash(const uint8_t* hash) override; void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override; void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len); void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override; bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override; void onControlDataRecv(mesh::Packet* packet) override; void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size); public: MyMesh(mesh::MainBoard& board, mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables); void begin(FILESYSTEM* fs, ArchiveStorage* archive = nullptr); void sendNodeDiscoverReq(); const char* getFirmwareVer() override { return FIRMWARE_VERSION; } const char* getBuildDate() override { return FIRMWARE_BUILD_DATE; } const char* getRole() override { return FIRMWARE_ROLE; } const char* getNodeName() { return _prefs.node_name; } NodePrefs* getNodePrefs() { return &_prefs; } // Локальному мастеру настройки (UITask) нужен тот же обработчик команд, что и // последовательному порту: проверка значений и сохранение остаются в CommonCLI. CommonCLI& getCLI() { return _cli; } bool isHiddenNode() const { return _prefs.advert_interval == 0 && _prefs.flood_advert_interval == 0; } void savePrefs() override { _cli.savePrefs(_fs); } void sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size); // CommonCLICallbacks void applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) override; bool formatFileSystem() override; void sendSelfAdvertisement(int delay_millis, bool flood) override; void updateAdvertTimer() override; void updateFloodAdvertTimer() override; void setLoggingOn(bool enable) override { _logging = enable; } void eraseLogFile() override { _fs->remove(PACKET_LOG_FILE); } void dumpLogFile() override; void setTxPower(int8_t power_dbm) override; void formatNeighborsReply(char *reply) override; void clearNeighbours() override; void removeNeighbor(const uint8_t* pubkey, int key_len) override; void formatStatsReply(char *reply, size_t reply_size) override; void formatRadioStatsReply(char *reply, size_t reply_size) override; void formatPacketStatsReply(char *reply, size_t reply_size) override; void formatMemoryReply(char *reply, size_t reply_size) override; bool purgeSdCard(char* reply, size_t reply_size); void prepareForOTAStart() override; void startRegionsLoad() override; bool saveRegions() override; void onDefaultRegionChanged(const RegionEntry* r) override; mesh::LocalIdentity& getSelfId() override { return self_id; } void saveIdentity(const mesh::LocalIdentity& new_id) override; void clearStats() override; void handleCommand(uint32_t sender_timestamp, char* command, char* reply); void runWebCommand(const char* command, char* reply, size_t reply_size) override; const char* getWebAdminPassword() const override { return _prefs.password; } #if defined(ESP_PLATFORM) && WITH_WEB_PANEL bool installWebCertBundle(const char* pem, size_t len, char* err, size_t err_size) override { return web.installCertBundle(pem, len, err, err_size); } #endif bool isWebStatsEnabled() const override; bool formatWebStatsSummaryJson(char* reply, size_t reply_size) override; bool formatWebStatsSeriesJson(const char* series, char* reply, size_t reply_size) override; void loop(); #if defined(WITH_BRIDGE) void setBridgeState(bool enable) override { if (enable == bridge.isRunning()) return; if (enable) { bridge.begin(); } else { bridge.end(); } } void restartBridge() override { if (!bridge.isRunning()) return; bridge.end(); bridge.begin(); } #endif // To check if there is pending work bool hasPendingWork() const; bool setRxBoostedGain(bool enable) override; #if defined(USE_LR2021) virtual bool configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) override; #endif };