// SPDX-License-Identifier: Apache-2.0 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include constexpr auto* TAG = "mesh"; namespace { constexpr size_t THREAD_STACK_SIZE = 8192; constexpr size_t OPEN_APP_STACK_SIZE = 4096; /** The Mesh app gets this many steps of 50 ms to stop before it is started again */ constexpr int OPEN_APP_STOP_WAIT_STEPS = 100; constexpr size_t MAX_BACKENDS = 4; constexpr size_t MAX_NODES = 128; constexpr size_t TX_QUEUE_LIMIT = 16; constexpr uint64_t TICK_INTERVAL_MS = 1000; constexpr uint64_t FLUSH_MAX_AGE_MS = 30000; constexpr size_t MAX_UNREAD_ENTRIES = 256; /** Unread messages are counted up to this number, which is shown as "99+" */ constexpr size_t UNREAD_COUNT_LIMIT = MESH_UNREAD_COUNT_LIMIT; constexpr auto* MESH_APP_ID = "tactility.mesh"; constexpr uint64_t DUTY_CYCLE_WINDOW_MS = 3600 * 1000; constexpr int CHANNEL_BUSY_RETRIES = 3; constexpr uint32_t CALL_DONE_BIT = (1 << 0); constexpr int DESTROY_ATTEMPTS = 10; constexpr uint32_t DESTROY_RETRY_DELAY_MS = 200; // 2023-11-14: a system clock before this was never set constexpr int64_t MIN_VALID_WALL_TIME = 1700000000; struct GlobalMutex { Mutex handle {}; GlobalMutex() { mutex_construct(&handle); } ~GlobalMutex() { mutex_destruct(&handle); } }; /** Guards the backend registry, the settings, the event subscriptions and the service pointer with its data */ GlobalMutex globalMutex; void lock() { mutex_lock(&globalMutex.handle); } void unlock() { mutex_unlock(&globalMutex.handle); } /** Serializes callOnServiceThread() callers. Taken before the global lock, never while holding it */ GlobalMutex callMutex; /** Serializes the changes of the mute preferences, so that what is stored and what is in memory end up the same. Taken before the global lock. */ GlobalMutex mutedMutex; /** * Runs @a work on the file operations task and waits until it has completed. The service thread can't access files, as its * stack is in external RAM. Must be called without the global lock, as work that was queued before can take it. * @return false when the work couldn't be started */ bool runFileWork(const std::function& work) { if (file_ops_is_worker()) { work(); return true; } TaskEventGroup group {}; task_event_group_construct(&group); FileOpsSubscription subscription {}; bool done = false; file_ops_tag(&subscription, "mesh"); if (file_ops_subscribe(&subscription, &group) == ERROR_NONE) { const auto run = [](void* context) { (*static_cast*>(context))(); }; if (file_ops_queue(run, const_cast*>(&work), &subscription) == ERROR_NONE) { done = file_ops_await(&subscription, portMAX_DELAY) == ERROR_NONE; } file_ops_unsubscribe(&subscription); } task_event_group_destruct(&group); if (!done) { LOG_E(TAG, "Failed to run file work"); } return done; } /** The registry, settings and subscriptions. Allocated once in external memory and guarded by the global lock. */ struct Globals { const MeshBackendApi* backends[MAX_BACKENDS] = {}; size_t backendCount = 0; MeshSettings settings {}; bool settingsLoaded = false; /** The number of unread messages of each conversation, which is kept up to date and stored as it changes */ struct UnreadEntry { char backend[MESH_BACKEND_ID_MAX_LENGTH + 1]; MeshAddress peer; uint8_t channel; uint64_t peerHash; uint32_t count; }; tt::std::vector unread; bool unreadLoaded = false; /** Conversations that have notifications turned off, as tokens of mutedToken(). Loaded on first use. */ tt::std::vector muted; bool mutedLoaded = false; /** Settings of the backends, loaded on first use */ struct BackendSettingsEntry { const MeshBackendApi* api; MeshBackendSettings settings; /** False when the settings couldn't be read, so the entry has defaults and is loaded again at the next lookup */ bool loaded; /** Held by a setter from reading the settings to committing them, so that two updates of one backend don't overwrite each other. Taken before the global lock. */ Mutex update; } backendSettings[MAX_BACKENDS] = {}; size_t backendSettingsCount = 0; bool legacySettingsMigrated = false; MeshEventSubscription* subscriptions = nullptr; }; Globals& globals() { static Globals* instance = tt::newObject(); check(instance != nullptr); return *instance; } uint64_t getMillis() { return get_micros_since_boot() / 1000; } const MeshBackendApi* findBackend(const char* id) { for (size_t i = 0; i < globals().backendCount; i++) { if (strncmp(globals().backends[i]->id, id, MESH_BACKEND_ID_MAX_LENGTH) == 0) { return globals().backends[i]; } } return nullptr; } void ensureSettingsLoaded(); bool canSendAndReceive(Device* device, RadioModulation modulation) { return radio_can_transmit(device, modulation) && radio_can_receive(device, modulation); } /** Whether the radio does LoRa. Other mesh radios do ESP-NOW. */ bool usesLora(Device* device) { return canSendAndReceive(device, RADIO_MODULATION_LORA); } /** A started radio that can be used for mesh networking */ bool isMeshRadio(Device* device) { return device_is_ready(device) && (usesLora(device) || canSendAndReceive(device, RADIO_MODULATION_ESPNOW)); } /** * Takes a reference on the selected radio. Without a selection, or when the selected radio isn't there, * that is the first radio that isn't ESP-NOW, or the first ESP-NOW radio when there is no other. * @return nullptr when there is none */ Device* findRadio() { char name[MESH_NAME_MAX_LENGTH + 1]; lock(); ensureSettingsLoaded(); strncpy(name, globals().settings.radio, sizeof(name)); name[MESH_NAME_MAX_LENGTH] = '\0'; unlock(); struct Search { const char* name; Device* selected = nullptr; Device* lora = nullptr; Device* other = nullptr; } search { name }; device_for_each_of_type(&RADIO_TYPE, &search, [](Device* device, void* context) { auto* search = static_cast(context); if (!isMeshRadio(device)) { return true; } if (search->name[0] != '\0' && strcmp(device->name, search->name) == 0) { search->selected = device; return false; } Device*& slot = usesLora(device) ? search->lora : search->other; if (slot == nullptr) { slot = device; } return true; }); Device* radio = search.selected != nullptr ? search.selected : (search.lora != nullptr ? search.lora : search.other); if (radio != nullptr && device_get(radio) != ERROR_NONE) { return nullptr; } return radio; } /** Whether the presets of the backend apply to the radio that is used: they are for LoRa */ bool presetsApply() { Device* radio = findRadio(); if (radio == nullptr) { return false; } const bool applies = usesLora(radio); device_put(radio); return applies; } /** Requires the global lock and loaded settings */ const MeshBackendApi* getSelectedBackend() { if (globals().settings.backend[0] != '\0') { return findBackend(globals().settings.backend); } return (globals().backendCount > 0) ? globals().backends[0] : nullptr; } /** @param[in] id the backend, or NULL for the selected backend. Requires the global lock and loaded settings. */ const MeshBackendApi* resolveBackend(const char* id) { return (id != nullptr) ? findBackend(id) : getSelectedBackend(); } /** Requires the global lock and loaded settings */ /** Requires the global lock and loaded settings */ Globals::BackendSettingsEntry& getBackendEntry(const MeshBackendApi* api) { auto& entries = globals().backendSettings; for (size_t i = 0; i < globals().backendSettingsCount; i++) { if (entries[i].api == api) { if (!entries[i].loaded) { entries[i].loaded = mesh_settings_load_backend(api->id, &entries[i].settings) == ERROR_NONE; } return entries[i]; } } if (!globals().legacySettingsMigrated) { // The backend that was selected when the settings were saved owns the ones that were stored without a backend const MeshBackendApi* owner = getSelectedBackend(); if (owner != nullptr) { if (mesh_settings_migrate_legacy(owner->id) == ERROR_NONE) { globals().legacySettingsMigrated = true; } } } auto& entry = entries[globals().backendSettingsCount < MAX_BACKENDS ? globals().backendSettingsCount++ : MAX_BACKENDS - 1]; entry.api = api; mutex_construct(&entry.update); entry.loaded = mesh_settings_load_backend(api->id, &entry.settings) == ERROR_NONE; return entry; } /** Requires the global lock and loaded settings */ MeshBackendSettings& getBackendSettings(const MeshBackendApi* api) { return getBackendEntry(api).settings; } size_t getPresetCount(const MeshBackendApi* api) { size_t count = 0; if (api->presets != nullptr) { while (api->presets[count] != nullptr) { count++; } } return count; } /** @return the index of the preset with @a name, or 0 (the default) when there is none */ size_t findPreset(const MeshBackendApi* api, const char* name) { const size_t count = getPresetCount(api); for (size_t i = 0; i < count; i++) { if (strcmp(api->presets[i], name) == 0) { return i; } } return 0; } void ensureSettingsLoaded() { if (!globals().settingsLoaded) { mesh_settings_load(&globals().settings); globals().settingsLoaded = true; } } /** Requires the global lock */ void queueEvent(const MeshEvent& event) { for (auto* sub = globals().subscriptions; sub != nullptr; sub = sub->internal.next) { if (sub->internal.count >= MESH_EVENT_QUEUE_CAPACITY) { continue; } const uint8_t tail = (sub->internal.head + sub->internal.count) % MESH_EVENT_QUEUE_CAPACITY; sub->internal.queue[tail] = event; sub->internal.count++; task_event_group_signal(sub->internal.event_group, sub->bit); } } /** Requires the global lock */ void emitEvent(MeshEventType type, MeshState state, uint32_t seq, MeshDeliveryState delivery) { queueEvent({ .timestamp = get_micros_since_boot(), .type = type, .state = state, .seq = seq, .delivery = delivery, .retry_attempt = 0, .retry_max = 0, .repeat_count = 0, .frame = {}, }); } /** Requires the global lock */ void emitFrame(MeshState state, MeshFrameKind kind, size_t length, float rssi, float snr, const MeshAddress* from, const char* name) { MeshEvent event {}; event.timestamp = get_micros_since_boot(); event.type = MESH_EVENT_FRAME; event.state = state; event.delivery = MESH_DELIVERY_RECEIVED; event.frame.kind = kind; event.frame.length = (uint16_t)length; event.frame.rssi = rssi; event.frame.snr = snr; if (from != nullptr) { event.frame.from = *from; } if (name != nullptr) { strncpy(event.frame.name, name, MESH_NAME_MAX_LENGTH); } queueEvent(event); } struct Frame { tt::std::vector data; uint32_t seq = 0; int busyRetries = 0; }; struct AirtimeRecord { uint64_t timeMs; uint32_t airtimeMs; }; } // namespace /** * The service instance. Fields marked "thread" are only touched by the service thread, the rest is * guarded by the global lock. */ struct MeshHost { MeshState state = MESH_STATE_OFF; /** The network parameters of the active backend */ MeshNetworkSettings network {}; MeshStore store; tt::std::vector nodes; /** The saved contacts of the backend that owns the open storage */ tt::std::vector contacts; /** False when the contacts of the storage backend couldn't be read. They must not be saved then, as that would replace the saved ones. */ bool contactsLoaded = false; /** The contacts changed and are written by the file operations task */ bool contactsDirty = false; /** The message buffer is written by the file operations task */ bool storeFlushPending = false; char activeBackend[MESH_BACKEND_ID_MAX_LENGTH + 1] = {}; /** The backend whose messages and contacts are open. It's the selected backend, whether or not it is running. */ char storageBackend[MESH_BACKEND_ID_MAX_LENGTH + 1] = {}; tt::std::deque> calls; // thread Device* radio = nullptr; bool radioAcquired = false; TaskEventGroup group {}; uint32_t stopBit = 0; uint32_t callBit = 0; RadioRxEventSubscription rxSub {}; RadioTxEventSubscription txSub {}; bool rxSubscribed = false; bool txSubscribed = false; Thread* thread = nullptr; std::atomic running { false }; const MeshBackendApi* api = nullptr; void* backend = nullptr; MeshRadioProfile profile {}; RadioRegion appliedRegion = RADIO_REGION_UNSET; tt::std::deque txQueue; bool txInFlight = false; RadioTxId txId = 0; Frame txFrame; tt::std::deque airtime; RadioRxEvent rxEvent {}; bool dutyCycleLogged = false; uint64_t lastTickMs = 0; uint32_t framesSent = 0; uint32_t framesFailed = 0; uint32_t framesReceived = 0; uint32_t framesUnreadable = 0; /** The notification that counts the new messages, 0 when there is none */ uint32_t notificationId = 0; // Synchronous calls EventGroupHandle_t callEvents = nullptr; }; extern "C" { static void restoreMessageNotification(MeshHost* host); static void preloadStored(); static void queueUnreadFlush(); } namespace { MeshHost* service = nullptr; /** Requires the global lock */ void setState(MeshHost* host, MeshState state) { if (host->state != state) { LOG_I(TAG, "State: %s -> %s", mesh_state_to_string(host->state), mesh_state_to_string(state)); host->state = state; emitEvent(MESH_EVENT_STATE, state, 0, MESH_DELIVERY_RECEIVED); } } void setStateLocked(MeshHost* host, MeshState state) { lock(); setState(host, state); unlock(); } // region Contacts constexpr size_t MAX_CONTACTS = 64; /** The contacts of the user. A backend keeps its own contacts.bin in the same folder. */ constexpr auto* CONTACTS_FILE_NAME = "saved_contacts.bin"; constexpr auto* SHARED_CONTACTS_FILE_NAME = "contacts.bin"; constexpr auto* STORE_DIRECTORY_NAME = "store"; bool isSameAddress(const MeshAddress& a, const MeshAddress& b) { return a.length == b.length && memcmp(a.bytes, b.bytes, a.length) == 0; } /** A path in the folder of a backend, where it keeps its messages, contacts and own files. Creates the folder when @a create is set. */ bool getBackendPath(const char* backend, const char* child, char* path, size_t size, bool create) { char directory[FILE_MAX_PATH_STRING_LENGTH]; char backendDirectory[16 + MESH_BACKEND_ID_MAX_LENGTH]; snprintf(backendDirectory, sizeof(backendDirectory), "backends/%s", backend); if (service_paths_get_user_data_path(MESH_SERVICE_ID, backendDirectory, directory, sizeof(directory)) != ERROR_NONE) { return false; } if (create) { const error_t made = directory_make(directory, true); if (made != ERROR_NONE && made != ERROR_ALREADY_EXISTS) { LOG_E(TAG, "Failed to create %s", directory); return false; } } const int written = snprintf(path, size, "%s/%s", directory, child); return written >= 0 && static_cast(written) < size; } /** Requires the global lock */ MeshContact* findContact(MeshHost* host, const MeshAddress& address) { for (auto& contact : host->contacts) { if (strncmp(contact.backend, host->storageBackend, MESH_BACKEND_ID_MAX_LENGTH) == 0 && isSameAddress(contact.address, address)) { return &contact; } } return nullptr; } bool loadContacts(MeshHost* host, const char* backend) { char path[FILE_MAX_PATH_STRING_LENGTH]; if (!getBackendPath(backend, CONTACTS_FILE_NAME, path, sizeof(path), false)) { return false; } FILE* file = fopen(path, "rb"); if (file == nullptr) { // No contacts were saved yet return errno == ENOENT; } MeshContact contact; while (host->contacts.size() < MAX_CONTACTS && fread(&contact, sizeof(contact), 1, file) == 1) { contact.backend[MESH_BACKEND_ID_MAX_LENGTH] = '\0'; contact.name[MESH_NAME_MAX_LENGTH] = '\0'; if (contact.address.length > 0 && contact.address.length <= MESH_ADDRESS_MAX_LENGTH) { host->contacts.push_back(contact); } } const bool failed = ferror(file) != 0; fclose(file); return !failed; } /** Requires the global lock. Accesses files. */ void writeContacts(MeshHost* host) { char path[FILE_MAX_PATH_STRING_LENGTH]; if (host->storageBackend[0] == '\0' || !host->contactsLoaded || !getBackendPath(host->storageBackend, CONTACTS_FILE_NAME, path, sizeof(path), true)) { return; } FILE* file = fopen(path, "wb"); if (file == nullptr) { LOG_E(TAG, "Failed to save the contacts"); return; } if (!host->contacts.empty() && fwrite(host->contacts.data(), sizeof(MeshContact), host->contacts.size(), file) != host->contacts.size()) { LOG_E(TAG, "Failed to save the contacts"); } fclose(file); } bool hostWritesQueued = false; /** Work for the file operations task: writes what the service changed. Its thread can't access files. */ void writeHostData(void*) { lock(); hostWritesQueued = false; MeshHost* host = service; if (host != nullptr) { if (host->storeFlushPending) { host->storeFlushPending = false; host->store.flush(); } if (host->contactsDirty) { host->contactsDirty = false; writeContacts(host); } } unlock(); } /** Requires the global lock. Queues the writes unless they are queued already. A failed queue is tried again at the next tick. */ void queueHostWrites(MeshHost* host) { if (hostWritesQueued || (!host->storeFlushPending && !host->contactsDirty)) { return; } hostWritesQueued = file_ops_queue(writeHostData, nullptr, nullptr) == ERROR_NONE; } /** Requires the global lock. The contacts are written by the file operations task, which writes the latest ones once. */ void saveContacts(MeshHost* host) { host->contactsDirty = true; queueHostWrites(host); } /** * Opens the messages and contacts of @a api, and closes those of the backend that was open. Without a backend, nothing is open. * Every backend has its own, so the data of one backend never shows up in another. * Requires the global lock. Accesses files. * @retval false when the message store couldn't be opened */ bool switchStorage(MeshHost* host, const MeshBackendApi* api) { const char* id = (api != nullptr) ? api->id : ""; // A failed contacts load is retried if (strncmp(host->storageBackend, id, MESH_BACKEND_ID_MAX_LENGTH) == 0 && (api == nullptr || (host->store.isOpen() && host->contactsLoaded))) { return true; } if (host->contactsDirty) { host->contactsDirty = false; writeContacts(host); } host->storeFlushPending = false; host->store.close(); host->contacts.clear(); host->contactsLoaded = false; host->storageBackend[0] = '\0'; if (api == nullptr) { return true; } // Reading the messages and the contacts takes a while on a slow card, and the lock is what other threads need to show // the state. The store counts as unavailable until it is open, and nothing else touches it before that. unlock(); char storePath[FILE_MAX_PATH_STRING_LENGTH]; const bool opened = getBackendPath(id, STORE_DIRECTORY_NAME, storePath, sizeof(storePath), true) && host->store.open(storePath) == ERROR_NONE; bool contactsLoaded = false; if (opened) { contactsLoaded = loadContacts(host, id); } lock(); if (!opened) { LOG_E(TAG, "Failed to open the message store of %s", id); host->store.close(); return false; } strncpy(host->storageBackend, id, MESH_BACKEND_ID_MAX_LENGTH); host->contactsLoaded = contactsLoaded; if (!host->contactsLoaded) { LOG_E(TAG, "Failed to load the contacts of %s", id); host->contacts.clear(); } return true; } /** * Save a contact of the active backend. An existing contact is renamed when @a rename is set. * Requires the global lock. */ error_t addContact(MeshHost* host, const MeshAddress& address, const char* name, bool rename) { if (address.length == 0 || address.length > MESH_ADDRESS_MAX_LENGTH) { return ERROR_INVALID_ARGUMENT; } if (!host->contactsLoaded) { return ERROR_INVALID_STATE; } char resolvedName[MESH_NAME_MAX_LENGTH + 1] = {}; if (name != nullptr) { strncpy(resolvedName, name, MESH_NAME_MAX_LENGTH); } if (resolvedName[0] == '\0') { for (const auto& node : host->nodes) { if (isSameAddress(node.address, address) && strncmp(node.backend, host->activeBackend, MESH_BACKEND_ID_MAX_LENGTH) == 0) { strncpy(resolvedName, node.name, MESH_NAME_MAX_LENGTH); break; } } } if (resolvedName[0] == '\0') { // The first bytes identify the node well enough to tell nodes apart for (size_t i = 0; i < address.length && i < 4; i++) { snprintf(resolvedName + i * 2, 3, "%02x", address.bytes[i]); } } auto* existing = findContact(host, address); if (existing != nullptr) { if (!rename || name == nullptr || name[0] == '\0') { return ERROR_NONE; } strncpy(existing->name, resolvedName, MESH_NAME_MAX_LENGTH); } else { if (host->contacts.size() >= MAX_CONTACTS) { return ERROR_RESOURCE; } MeshContact contact {}; strncpy(contact.backend, host->storageBackend, MESH_BACKEND_ID_MAX_LENGTH); contact.address = address; strncpy(contact.name, resolvedName, MESH_NAME_MAX_LENGTH); host->contacts.push_back(contact); } saveContacts(host); emitEvent(MESH_EVENT_CONTACT, host->state, 0, MESH_DELIVERY_RECEIVED); return ERROR_NONE; } // endregion /** Requires the global lock */ void setDelivery(MeshHost* host, uint32_t seq, MeshDeliveryState delivery) { if (host->store.setDelivery(seq, delivery) == ERROR_NONE) { emitEvent(MESH_EVENT_DELIVERY, host->state, seq, delivery); } } /** Queue work for the service thread. Requires the global lock. */ void post(MeshHost* host, std::function work) { host->calls.push_back(std::move(work)); task_event_group_signal(&host->group, host->callBit); } /** * Run work on the service thread and wait for it. Must be called without the global lock and never from * the service thread. The thread drains all posted work before it exits, so the wait always ends. */ error_t callOnServiceThread(const std::function& work) { mutex_lock(&callMutex.handle); lock(); MeshHost* host = service; if (host == nullptr) { unlock(); mutex_unlock(&callMutex.handle); return ERROR_INVALID_STATE; } event_group_clear(host->callEvents, CALL_DONE_BIT); post(host, [host, &work] { work(host); event_group_set(host->callEvents, CALL_DONE_BIT); }); unlock(); event_group_wait(host->callEvents, CALL_DONE_BIT, false, true, nullptr, portMAX_DELAY); mutex_unlock(&callMutex.handle); return ERROR_NONE; } // region Radio and backend lifecycle (service thread) /** Subscribes to the events of @a radio, which is a referenced device. */ void attachRadio(MeshHost* host, Device* radio) { host->radio = radio; host->rxSubscribed = radio_rx_event_subscribe(&host->rxSub, &host->group, host->radio) == ERROR_NONE; host->txSubscribed = radio_tx_event_subscribe(&host->txSub, &host->group, host->radio) == ERROR_NONE; } /** Unsubscribes from the radio, releases it and drops the reference */ void detachRadio(MeshHost* host) { if (host->rxSubscribed) { radio_rx_event_unsubscribe(&host->rxSub); host->rxSubscribed = false; } if (host->txSubscribed) { radio_tx_event_unsubscribe(&host->txSub); host->txSubscribed = false; } if (host->radio != nullptr) { if (host->radioAcquired) { radio_release(host->radio); host->radioAcquired = false; } device_put(host->radio); host->radio = nullptr; } } void radioOff(MeshHost* host) { if (host->radio != nullptr && host->radioAcquired) { radio_set_enabled(host->radio, false); } } /** The notification of the new messages belongs to the backend that received them, so it goes with it. Service thread. */ void dismissMessageNotification(MeshHost* host) { if (host->notificationId != 0) { notification_dismiss(host->notificationId); } host->notificationId = 0; } /** Backends read and write their files when they are created and destroyed, so that runs on the file operations task */ void* createBackend(const MeshBackendApi* api, MeshHost* host) { void* backend = nullptr; runFileWork([&] { backend = api->create(host); }); return backend; } /** * The file operations task can fail to start when memory is low, which is usually temporary, so this tries again. * The backend writes its pending changes when it is destroyed, so it is only given up after that kept failing. */ void destroyBackend(const MeshBackendApi* api, void* backend) { for (int attempt = 0; attempt < DESTROY_ATTEMPTS; attempt++) { if (attempt > 0) { delay_millis(DESTROY_RETRY_DELAY_MS); } if (runFileWork([&] { api->destroy(backend); })) { return; } } LOG_E(TAG, "Backend %s couldn't be destroyed", api->id); } void deactivateBackend(MeshHost* host) { if (host->api == nullptr) { return; } const char* id = host->api->id; destroyBackend(host->api, host->backend); host->api = nullptr; host->backend = nullptr; host->txQueue.clear(); host->txInFlight = false; radioOff(host); lock(); // Messages that weren't sent wait for this backend to come back for (uint32_t seq : host->store.findOutgoing(id, MESH_DELIVERY_QUEUED)) { setDelivery(host, seq, MESH_DELIVERY_BLOCKED); } // The retries went with the backend, so there is nothing left that could finish these for (uint32_t seq : host->store.findOutgoing(id, MESH_DELIVERY_RETRYING)) { setDelivery(host, seq, MESH_DELIVERY_FAILED); } host->nodes.clear(); host->activeBackend[0] = '\0'; unlock(); } bool applyProfile(MeshHost* host) { const auto& profile = host->profile; radio_set_enabled(host->radio, false); if (radio_set_modulation(host->radio, profile.modulation) != ERROR_NONE) { LOG_E(TAG, "Radio doesn't support the backend's modulation"); return false; } const struct { RadioParameter parameter; int32_t value; } parameters[] = { { RADIO_PARAMETER_FREQUENCY, profile.frequency }, { RADIO_PARAMETER_BANDWIDTH, profile.bandwidth }, { RADIO_PARAMETER_SPREADING_FACTOR, profile.spreading_factor }, { RADIO_PARAMETER_CODING_RATE, profile.coding_rate }, { RADIO_PARAMETER_SYNC_WORD, profile.sync_word }, { RADIO_PARAMETER_PREAMBLE_LENGTH, profile.preamble_length }, { RADIO_PARAMETER_POWER, profile.power }, }; for (const auto& entry : parameters) { const error_t result = radio_set_parameter(host->radio, entry.parameter, entry.value); if (result != ERROR_NONE && result != ERROR_NOT_SUPPORTED) { LOG_E(TAG, "Setting radio parameter %d to %d failed: %d", (int)entry.parameter, (int)entry.value, (int)result); return false; } } if (profile.channel != 0) { const error_t result = radio_set_parameter(host->radio, RADIO_PARAMETER_CHANNEL, profile.channel); if (result != ERROR_NONE) { LOG_E(TAG, "Setting the radio channel to %d failed: %d", (int)profile.channel, (int)result); return false; } } // Listen-before-talk is optional, so a driver without it is fine radio_set_parameter(host->radio, RADIO_PARAMETER_LBT, 1); // Only radios of the SX126x family have a boosted gain mode lock(); const bool boostedGain = globals().settings.rx_boosted_gain; unlock(); radio_set_parameter(host->radio, RADIO_PARAMETER_BOOSTED_GAIN, boostedGain ? 1 : 0); if (radio_set_enabled(host->radio, true) != ERROR_NONE) { LOG_E(TAG, "Failed to turn on the radio"); return false; } return true; } void resubmitPending(MeshHost* host); /** @return the band of @a region that holds the whole channel of width @a bandwidth around @a frequency, NULL when there is none */ const RadioRegionBand* findBand(RadioRegion region, int32_t frequency, int32_t bandwidth) { const RadioRegionBand* bands = nullptr; const size_t count = radio_get_region_bands(region, &bands); // 64-bit, because a frequency that was typed in can be close to the limit of 32 bits const int64_t low = static_cast(frequency) - bandwidth / 2; const int64_t high = static_cast(frequency) + bandwidth / 2; const auto* band = std::find_if(bands, bands + count, [=](const RadioRegionBand& candidate) { return low >= candidate.frequency_min && high <= candidate.frequency_max; }); return (band != bands + count) ? band : nullptr; } /** * The profile of a preset with the settings applied, and the power limited to what the region allows (the radio rejects more). * @param[in] backend the backend state, or NULL to only get the parameters of the preset */ error_t getRadioProfile(const MeshBackendApi* api, void* backend, RadioRegion region, RadioModulation modulation, size_t preset, const MeshRadioSettings& settings, MeshRadioProfile* profile) { const error_t error = api->get_radio_profile(backend, region, modulation, preset, profile); if (error != ERROR_NONE || modulation != RADIO_MODULATION_LORA) { return error; } if (settings.frequency != 0) profile->frequency = settings.frequency; if (settings.bandwidth != 0) profile->bandwidth = settings.bandwidth; if (settings.spreading_factor != 0) profile->spreading_factor = settings.spreading_factor; if (settings.coding_rate != 0) profile->coding_rate = settings.coding_rate; if (settings.power != 0) profile->power = settings.power; // The limit of the band that holds the channel, because bands of a region have their own limits const RadioRegionBand* band = findBand(region, profile->frequency, profile->bandwidth); if (band != nullptr) { profile->power = std::min(profile->power, band->power_max); } return ERROR_NONE; } /** The preset's network parameters with the settings applied */ MeshNetworkSettings getNetwork(const MeshBackendApi* api, size_t preset, const MeshNetworkSettings& settings) { MeshNetworkSettings network = {}; if (api->get_preset_network != nullptr) { api->get_preset_network(preset, &network); } // A value that was stored by hand can be out of range, and the preset's value is used then if (settings.path_hash_size >= 1 && settings.path_hash_size <= MESH_PATH_HASH_SIZE_MAX) { network.path_hash_size = settings.path_hash_size; } if (settings.region_scope[0] == '\0') { // The preset's scope } else if (strcmp(settings.region_scope, MESH_REGION_SCOPE_NONE) == 0) { network.region_scope[0] = '\0'; } else { strncpy(network.region_scope, settings.region_scope, MESH_NAME_MAX_LENGTH); } return network; } /** (Re)select the backend and configure the radio from the settings and the radio's region */ void configure(MeshHost* host) { deactivateBackend(host); // The messages and contacts of the selected backend are available when its radio is off, and no other backend's are bool storageReady = false; bool storageChanged = false; runFileWork([&] { preloadStored(); lock(); char previousStorage[MESH_BACKEND_ID_MAX_LENGTH + 1]; strncpy(previousStorage, host->storageBackend, sizeof(previousStorage)); previousStorage[MESH_BACKEND_ID_MAX_LENGTH] = '\0'; storageReady = switchStorage(host, getSelectedBackend()); // Consumers show the contacts and channels of the selected backend, also when its radio is off storageChanged = strncmp(previousStorage, host->storageBackend, MESH_BACKEND_ID_MAX_LENGTH) != 0; if (storageChanged) { emitEvent(MESH_EVENT_CONTACT, host->state, 0, MESH_DELIVERY_RECEIVED); emitEvent(MESH_EVENT_CHANNEL, host->state, 0, MESH_DELIVERY_RECEIVED); } unlock(); }); if (storageChanged) { // Switching from MeshCore to Meshtastic, for example, leaves the unread messages behind dismissMessageNotification(host); } if (!storageReady) { setStateLocked(host, MESH_STATE_ERROR); return; } // Messages that were unread before a restart show up again restoreMessageNotification(host); if (host->radio == nullptr) { setStateLocked(host, MESH_STATE_NO_RADIO); return; } if (!host->radioAcquired) { host->radioAcquired = radio_acquire(host->radio, "mesh") == ERROR_NONE; if (!host->radioAcquired) { setStateLocked(host, MESH_STATE_RADIO_BUSY); return; } } lock(); const MeshBackendApi* api = getSelectedBackend(); unlock(); MeshBackendSettings backendSettings {}; if (api != nullptr) { // The settings of a backend are read on first use const bool read = runFileWork([&] { lock(); backendSettings = getBackendSettings(api); unlock(); }); if (!read) { // Defaults would configure the radio with a preset that the user didn't select setStateLocked(host, MESH_STATE_ERROR); return; } } const size_t preset = (api != nullptr) ? findPreset(api, backendSettings.preset) : 0; if (api == nullptr) { setStateLocked(host, MESH_STATE_NO_BACKEND); return; } // Only LoRa is bound to a region. The Wi-Fi stack limits ESP-NOW by country. host->appliedRegion = radio_get_region(host->radio); if (host->appliedRegion == RADIO_REGION_UNSET && usesLora(host->radio)) { setStateLocked(host, MESH_STATE_NO_REGION); return; } // Set before create() because backends use host functions there host->api = api; void* backend = createBackend(api, host); if (backend == nullptr) { host->api = nullptr; setStateLocked(host, MESH_STATE_ERROR); return; } // A radio that doesn't do LoRa does ESP-NOW const RadioModulation modulation = usesLora(host->radio) ? RADIO_MODULATION_LORA : RADIO_MODULATION_ESPNOW; if (getRadioProfile(api, backend, host->appliedRegion, modulation, preset, backendSettings.radio_settings, &host->profile) != ERROR_NONE) { LOG_E(TAG, "Backend %s doesn't support region %s with preset %u", api->id, radio_region_to_string(host->appliedRegion), (unsigned)preset); destroyBackend(api, backend); host->api = nullptr; setStateLocked(host, MESH_STATE_ERROR); return; } lock(); host->network = getNetwork(api, preset, backendSettings.network); unlock(); host->backend = backend; if (!applyProfile(host)) { deactivateBackend(host); setStateLocked(host, MESH_STATE_ERROR); return; } lock(); strncpy(host->activeBackend, api->id, MESH_BACKEND_ID_MAX_LENGTH); host->activeBackend[MESH_BACKEND_ID_MAX_LENGTH] = '\0'; // Switching between backends keeps the state on, but consumers show the active backend const bool wasOn = host->state == MESH_STATE_ON; setState(host, MESH_STATE_ON); if (wasOn) { emitEvent(MESH_EVENT_STATE, MESH_STATE_ON, 0, MESH_DELIVERY_RECEIVED); } unlock(); LOG_I(TAG, "Backend %s active in region %s", api->id, radio_region_to_string(host->appliedRegion)); api->on_start(backend); resubmitPending(host); } /** Reads a message that isn't in the buffer anymore on the file operations task. Must be called without the global lock. */ bool getStored(MeshHost* host, uint32_t seq, MeshMessage* message) { lock(); const bool inBuffer = !host->store.needsRead(seq); const bool found = inBuffer && host->store.get(seq, message) == ERROR_NONE; unlock(); if (inBuffer) { return found; } bool read = false; runFileWork([&] { lock(); read = host->store.get(seq, message) == ERROR_NONE; unlock(); }); return read; } void sendStored(MeshHost* host, uint32_t seq) { MeshMessage message; const bool found = getStored(host, seq, &message); if (!found || message.delivery != MESH_DELIVERY_QUEUED) { return; } if (host->api == nullptr || strcmp(message.backend, host->api->id) != 0) { lock(); setDelivery(host, seq, MESH_DELIVERY_BLOCKED); unlock(); return; } const MeshAddress* to = (message.peer.length > 0) ? &message.peer : nullptr; if (host->api->send_text(host->backend, seq, to, message.channel, message.text) != ERROR_NONE) { lock(); setDelivery(host, seq, MESH_DELIVERY_FAILED); unlock(); } } void resubmitPending(MeshHost* host) { lock(); tt::std::vector pending = host->store.findOutgoing(host->api->id, MESH_DELIVERY_BLOCKED); for (uint32_t seq : pending) { setDelivery(host, seq, MESH_DELIVERY_QUEUED); } unlock(); for (uint32_t seq : pending) { sendStored(host, seq); } } // endregion // region TX (service thread) uint32_t getAirtimeUsedMs(MeshHost* host, uint64_t nowMs) { while (!host->airtime.empty() && nowMs - host->airtime.front().timeMs > DUTY_CYCLE_WINDOW_MS) { host->airtime.pop_front(); } uint32_t used = 0; for (const auto& record : host->airtime) { used += record.airtimeMs; } return used; } /** Wi-Fi radios have no duty cycle limit */ uint32_t getDutyCyclePercent(MeshHost* host) { return (host->profile.modulation == RADIO_MODULATION_ESPNOW) ? 100 : mesh_airtime_duty_cycle_percent(host->appliedRegion, host->profile.frequency); } void notifyFrameDone(MeshHost* host, uint32_t seq, bool transmitted) { if (seq != 0 && host->api != nullptr && host->api->on_frame_done != nullptr) { host->api->on_frame_done(host->backend, seq, transmitted); } } void pumpTx(MeshHost* host) { if (host->txInFlight || host->txQueue.empty() || host->api == nullptr) { return; } const auto& frame = host->txQueue.front(); const uint32_t airtimeMs = mesh_airtime_estimate_ms(host->profile, frame.data.size()); const uint32_t dutyCycle = getDutyCyclePercent(host); const uint64_t nowMs = getMillis(); if (dutyCycle < 100) { const uint64_t budgetMs = DUTY_CYCLE_WINDOW_MS * dutyCycle / 100; if (getAirtimeUsedMs(host, nowMs) + airtimeMs > budgetMs) { if (!host->dutyCycleLogged) { LOG_W(TAG, "Duty cycle budget used up, holding %u frames", (unsigned)host->txQueue.size()); host->dutyCycleLogged = true; } return; } } host->dutyCycleLogged = false; host->txFrame = std::move(host->txQueue.front()); host->txQueue.pop_front(); if (radio_transmit(host->radio, host->txFrame.data.data(), host->txFrame.data.size(), &host->txId) != ERROR_NONE) { host->framesFailed++; if (host->txFrame.seq != 0) { lock(); setDelivery(host, host->txFrame.seq, MESH_DELIVERY_FAILED); unlock(); } notifyFrameDone(host, host->txFrame.seq, false); return; } host->txInFlight = true; host->airtime.push_back({ .timeMs = nowMs, .airtimeMs = airtimeMs }); } void onTxEvent(MeshHost* host, const RadioTxEvent& event) { if (!host->txInFlight || event.id != host->txId) { return; } const uint32_t seq = host->txFrame.seq; switch (event.state) { case RADIO_TRANSMISSION_STATE_TRANSMITTED: host->txInFlight = false; host->framesSent++; if (seq != 0) { lock(); MeshDeliveryState delivery; if (host->store.getDelivery(seq, &delivery) == ERROR_NONE && delivery == MESH_DELIVERY_QUEUED) { setDelivery(host, seq, MESH_DELIVERY_SENT); } unlock(); } notifyFrameDone(host, seq, true); break; case RADIO_TRANSMISSION_STATE_CHANNEL_BUSY: host->txInFlight = false; if (host->txFrame.busyRetries < CHANNEL_BUSY_RETRIES) { host->txFrame.busyRetries++; host->txQueue.push_front(std::move(host->txFrame)); break; } [[fallthrough]]; case RADIO_TRANSMISSION_STATE_TIMEOUT: case RADIO_TRANSMISSION_STATE_ERROR: host->txInFlight = false; host->framesFailed++; if (seq != 0) { lock(); setDelivery(host, seq, MESH_DELIVERY_FAILED); unlock(); } notifyFrameDone(host, seq, false); break; default: break; } } // endregion // region Service thread /** Takes the first radio and subscribes to its events. @return false when there is none */ bool attachRadio(MeshHost* host) { Device* radio = findRadio(); if (radio == nullptr) { return false; } attachRadio(host, radio); return true; } /** Moves to the radio that is selected in the settings */ void reselectRadio(MeshHost* host) { deactivateBackend(host); detachRadio(host); if (!attachRadio(host)) { setStateLocked(host, MESH_STATE_NO_RADIO); return; } configure(host); } void drainRadioEvents(MeshHost* host) { if (host->rxSubscribed) { // A host member: RadioRxEvent is large and only used on this thread auto& rxEvent = host->rxEvent; while (radio_rx_event_poll(&host->rxSub, &rxEvent) == ERROR_NONE) { host->framesReceived++; if (host->api != nullptr) { if (!host->api->on_receive(host->backend, rxEvent.data, rxEvent.length, rxEvent.rssi, rxEvent.snr)) { host->framesUnreadable++; lock(); emitFrame(host->state, MESH_FRAME_UNREADABLE, rxEvent.length, rxEvent.rssi, rxEvent.snr, nullptr, nullptr); unlock(); } } } } if (host->txSubscribed) { RadioTxEvent txEvent; while (radio_tx_event_poll(&host->txSub, &txEvent) == ERROR_NONE) { onTxEvent(host, txEvent); } } } void runCalls(MeshHost* host) { while (true) { lock(); if (host->calls.empty()) { unlock(); return; } auto work = std::move(host->calls.front()); host->calls.pop_front(); unlock(); work(); } } void tick(MeshHost* host) { // Radios can start after the service, e.g. once the hotplug poller detects an add-on if (host->radio == nullptr && attachRadio(host)) { LOG_I(TAG, "Mesh radio found"); configure(host); } if (host->radio != nullptr && host->radioAcquired && radio_get_region(host->radio) != host->appliedRegion) { LOG_I(TAG, "Region changed, reconfiguring"); configure(host); } RadioState radioState = RADIO_STATE_OFF; if (host->api != nullptr && radio_get_state(host->radio, &radioState) == ERROR_NONE && radioState == RADIO_STATE_ERROR) { LOG_E(TAG, "Radio failed"); deactivateBackend(host); setStateLocked(host, MESH_STATE_ERROR); } if (host->api != nullptr) { host->api->on_tick(host->backend); } lock(); if (host->store.shouldFlush(getMillis(), FLUSH_MAX_AGE_MS)) { host->storeFlushPending = true; } // Writes that couldn't be queued are tried again queueHostWrites(host); // Counts that couldn't be stored are tried again queueUnreadFlush(); unlock(); } int32_t threadMain(void* context) { auto* host = static_cast(context); configure(host); while (host->running) { uint32_t flags = 0; task_event_group_wait_any(&host->group, &flags, pdMS_TO_TICKS(TICK_INTERVAL_MS)); if (!host->running) { break; } drainRadioEvents(host); runCalls(host); const uint64_t nowMs = getMillis(); if (nowMs - host->lastTickMs >= TICK_INTERVAL_MS) { host->lastTickMs = nowMs; tick(host); } pumpTx(host); } runCalls(host); deactivateBackend(host); // Turning mesh off removes the notification. A later start counts from zero. dismissMessageNotification(host); return 0; } // endregion // region Service lifecycle void* createService(const ServiceManifest*) { auto* host = tt::newObject(); if (host != nullptr) { // The service thread adds messages, and it can't access files host->store.setFlushWhenFull(false); } return host; } void destroyService(const ServiceManifest*, void* data) { tt::deleteObject(static_cast(data)); } void releaseResources(MeshHost* host) { detachRadio(host); task_event_group_destruct(&host->group); event_group_destruct(&host->callEvents); } bool isValidBackendId(const char* id) { if (id[0] == '\0') { return false; } for (const char* c = id; *c != '\0'; c++) { if (!isalnum(static_cast(*c)) && *c != '_' && *c != '-') { return false; } } return true; } /** A message store of a backend that is open while messages are moved to it */ struct MigrationTarget { char id[MESH_BACKEND_ID_MAX_LENGTH + 1]; MeshStore* store; }; /** @return false when messages couldn't be moved, in which case the shared store is kept to try again */ bool migrateSharedMessages(const char* sharedPath) { MeshStore shared; if (shared.open(sharedPath) != ERROR_NONE) { return false; } MigrationTarget targets[MAX_BACKENDS] = {}; size_t targetCount = 0; bool ok = true; tt::std::vector batch(8); uint32_t afterSeq = 0; for (size_t count = shared.getAfter(afterSeq, batch.data(), batch.size()); count > 0; count = shared.getAfter(afterSeq, batch.data(), batch.size())) { for (size_t i = 0; i < count; i++) { MeshMessage& message = batch[i]; afterSeq = message.seq; message.backend[MESH_BACKEND_ID_MAX_LENGTH] = '\0'; if (!isValidBackendId(message.backend)) { continue; } MigrationTarget* target = nullptr; for (size_t t = 0; t < targetCount; t++) { if (strcmp(targets[t].id, message.backend) == 0) { target = &targets[t]; } } if (target == nullptr && targetCount < MAX_BACKENDS) { char path[FILE_MAX_PATH_STRING_LENGTH]; auto* store = tt::newObject(); if (store != nullptr && getBackendPath(message.backend, STORE_DIRECTORY_NAME, path, sizeof(path), true) && store->open(path) == ERROR_NONE) { target = &targets[targetCount++]; strncpy(target->id, message.backend, MESH_BACKEND_ID_MAX_LENGTH); target->store = store; } else { tt::deleteObject(store); } } if (target == nullptr || target->store->add(&message) != ERROR_NONE) { ok = false; } } } for (size_t t = 0; t < targetCount; t++) { targets[t].store->close(); tt::deleteObject(targets[t].store); } shared.close(); return ok; } /** @return false when contacts couldn't be moved, in which case the shared file is kept to try again */ bool migrateSharedContacts(const char* sharedPath) { FILE* file = fopen(sharedPath, "rb"); if (file == nullptr) { return false; } bool ok = true; MeshContact contact; while (fread(&contact, sizeof(contact), 1, file) == 1) { contact.backend[MESH_BACKEND_ID_MAX_LENGTH] = '\0'; if (!isValidBackendId(contact.backend)) { continue; } char path[FILE_MAX_PATH_STRING_LENGTH]; FILE* target = getBackendPath(contact.backend, CONTACTS_FILE_NAME, path, sizeof(path), true) ? fopen(path, "ab") : nullptr; if (target == nullptr || fwrite(&contact, sizeof(contact), 1, target) != 1) { ok = false; } if (target != nullptr) { fclose(target); } } fclose(file); return ok; } /** * Messages and contacts used to be kept together for all backends. They are moved to the folders of their backends once, * and the shared ones are removed when that worked. */ void migrateSharedStorage() { char storePath[FILE_MAX_PATH_STRING_LENGTH]; char contactsPath[FILE_MAX_PATH_STRING_LENGTH]; if (service_paths_get_user_data_path(MESH_SERVICE_ID, STORE_DIRECTORY_NAME, storePath, sizeof(storePath)) != ERROR_NONE || service_paths_get_user_data_path(MESH_SERVICE_ID, SHARED_CONTACTS_FILE_NAME, contactsPath, sizeof(contactsPath)) != ERROR_NONE) { return; } if (directory_exists(storePath) && migrateSharedMessages(storePath)) { directory_remove_tree(storePath); } FILE* file = fopen(contactsPath, "rb"); if (file != nullptr) { fclose(file); if (migrateSharedContacts(contactsPath)) { file_remove(contactsPath); } } } error_t onStart(ServiceInstance*, void* data) { auto* host = static_cast(data); event_group_construct(&host->callEvents); task_event_group_construct(&host->group); if (task_event_group_claim_bit(&host->group, &host->stopBit) != ERROR_NONE || task_event_group_claim_bit(&host->group, &host->callBit) != ERROR_NONE) { releaseResources(host); return ERROR_RESOURCE; } migrateSharedStorage(); if (!attachRadio(host)) { LOG_W(TAG, "No mesh radio found yet"); device_for_each_of_type(&RADIO_TYPE, nullptr, [](Device* device, void*) { LOG_I(TAG, "Radio %s: ready=%d lora=%d espnow=%d", device->name, (int)device_is_ready(device), (int)usesLora(device), (int)canSendAndReceive(device, RADIO_MODULATION_ESPNOW)); return true; }); } // The store is opened by configure() on the service thread, as reading the messages takes seconds on a slow card and // starting the service must not wait for that. Until then the storage counts as unavailable, not as empty. lock(); ensureSettingsLoaded(); service = host; unlock(); host->running = true; host->thread = thread_alloc_full("mesh", THREAD_STACK_SIZE, threadMain, host, -1); if (host->thread != nullptr) { // Every file access of the service thread runs on the file operations task, which has its stack in internal RAM thread_set_stack_external(host->thread, true); } if (host->thread == nullptr || thread_start(host->thread) != ERROR_NONE) { host->running = false; if (host->thread != nullptr) { thread_free(host->thread); host->thread = nullptr; } lock(); service = nullptr; switchStorage(host, nullptr); unlock(); releaseResources(host); return ERROR_RESOURCE; } return ERROR_NONE; } void onStop(ServiceInstance*, void* data) { auto* host = static_cast(data); // No new work can be posted from here on, and the thread drains what was posted before lock(); service = nullptr; unlock(); host->running = false; task_event_group_signal(&host->group, host->stopBit); thread_join(host->thread, portMAX_DELAY, pdMS_TO_TICKS(10)); thread_free(host->thread); host->thread = nullptr; lock(); switchStorage(host, nullptr); setState(host, MESH_STATE_OFF); unlock(); releaseResources(host); } // endregion } // namespace const ServiceManifest mesh_service_manifest = { .id = MESH_SERVICE_ID, .create_service = createService, .destroy_service = destroyService, .on_start = onStart, .on_stop = onStop, }; bool mesh_service_should_auto_start() { lock(); ensureSettingsLoaded(); const bool enabled = globals().settings.enabled; unlock(); return enabled; } extern "C" { // region Backend registry error_t mesh_backend_register(const MeshBackendApi* api) { lock(); error_t result = ERROR_NONE; if (!isValidBackendId(api->id)) { result = ERROR_INVALID_ARGUMENT; } else if (findBackend(api->id) != nullptr) { result = ERROR_ALREADY_EXISTS; } else if (globals().backendCount >= MAX_BACKENDS) { result = ERROR_RESOURCE; } else { globals().backends[globals().backendCount++] = api; if (service != nullptr && service->state == MESH_STATE_NO_BACKEND) { MeshHost* host = service; post(host, [host] { configure(host); }); } } unlock(); return result; } error_t mesh_backend_unregister(const MeshBackendApi* api) { lock(); error_t result = ERROR_NOT_FOUND; for (size_t i = 0; i < globals().backendCount; i++) { if (globals().backends[i] == api) { globals().backends[i] = globals().backends[--globals().backendCount]; globals().backends[globals().backendCount] = nullptr; result = ERROR_NONE; break; } } MeshHost* host = service; unlock(); // The service may be using it, so wait for the service thread to let go of it if (result == ERROR_NONE && host != nullptr) { callOnServiceThread([api](MeshHost* serviceHost) { if (serviceHost->api == api) { configure(serviceHost); } }); } return result; } // endregion // region Host functions error_t mesh_host_transmit(MeshHost* host, const uint8_t* data, size_t length, uint32_t seq) { if (length == 0 || length > RADIO_RX_MAX_PACKET_LENGTH) { return ERROR_OUT_OF_RANGE; } if (host->txQueue.size() >= TX_QUEUE_LIMIT) { return ERROR_RESOURCE; } host->txQueue.push_back(Frame { .data = tt::std::vector(data, data + length), .seq = seq, .busyRetries = 0 }); return ERROR_NONE; } /** Identifies a conversation in the stored settings: the backend, then the peer in hexadecimal or the channel */ static std::string mutedToken(const char* backend, const MeshAddress* peer, uint8_t channel) { std::string token = std::string(backend) + (peer != nullptr && peer->length > 0 ? ".p" : ".c"); if (peer != nullptr && peer->length > 0) { char hex[3]; for (size_t i = 0; i < peer->length; i++) { snprintf(hex, sizeof(hex), "%02x", peer->bytes[i]); token += hex; } } else { token += std::to_string(channel); } return token; } /** Requires the global lock */ static tt::std::vector::iterator findMuted(const std::string& token) { return std::find_if(globals().muted.begin(), globals().muted.end(), [&token](const tt::std::string& muted) { return strcmp(muted.c_str(), token.c_str()) == 0; }); } /** Requires the global lock. Reads the file once. */ static bool isMuted(const std::string& token) { if (!globals().mutedLoaded) { globals().mutedLoaded = true; mesh_settings_load_muted([](const char* stored, void*) { globals().muted.push_back(stored); }, nullptr); } return findMuted(token) != globals().muted.end(); } /** Requires the global lock. A direct conversation is told apart by its peer, a channel by its index. */ static Globals::UnreadEntry* findUnread(const char* backend, const MeshAddress* peer, uint8_t channel) { const bool direct = peer != nullptr && peer->length > 0; for (auto& entry : globals().unread) { if (strncmp(entry.backend, backend, MESH_BACKEND_ID_MAX_LENGTH) != 0) { continue; } if (direct ? (entry.peer.length == peer->length && memcmp(entry.peer.bytes, peer->bytes, peer->length) == 0) : (entry.peer.length == 0 && entry.channel == channel)) { return &entry; } } return nullptr; } /** Reads the token of mutedToken() back as a conversation. @return false when it isn't one. */ static bool parseToken(const char* token, Globals::UnreadEntry& entry) { // ".p" for a contact or ".c" for a channel const char* dot = strchr(token, '.'); if (dot == nullptr || dot == token || static_cast(dot - token) > MESH_BACKEND_ID_MAX_LENGTH || (dot[1] != 'p' && dot[1] != 'c')) { return false; } entry = {}; memcpy(entry.backend, token, dot - token); if (dot[1] == 'c') { entry.channel = static_cast(atoi(dot + 2)); } else { const char* hex = dot + 2; const size_t length = strlen(hex) / 2; if (length == 0 || length > MESH_ADDRESS_MAX_LENGTH) { return false; } for (size_t i = 0; i < length; i++) { char pair[3] = { hex[i * 2], hex[i * 2 + 1], '\0' }; entry.peer.bytes[i] = static_cast(strtoul(pair, nullptr, 16)); } entry.peer.length = static_cast(length); } entry.peerHash = MeshStore::hashPeerAddress(entry.peer.length > 0 ? &entry.peer : nullptr); return true; } /** * Reads the stored unread counts and the muted conversations once. The files are read without the global lock, as * other threads need it to show the state. Service thread. */ static void preloadStored() { lock(); const bool unreadNeeded = !globals().unreadLoaded; const bool mutedNeeded = !globals().mutedLoaded; unlock(); if (!unreadNeeded && !mutedNeeded) { return; } tt::std::vector unread; tt::std::vector muted; if (unreadNeeded) { mesh_settings_load_unread([](const char* token, uint32_t count, void* data) { auto* entries = static_cast*>(data); Globals::UnreadEntry entry {}; if (count > 0 && entries->size() < MAX_UNREAD_ENTRIES && parseToken(token, entry)) { entry.count = std::min(count, UNREAD_COUNT_LIMIT); entries->push_back(entry); } }, &unread); } if (mutedNeeded) { mesh_settings_load_muted([](const char* stored, void* data) { static_cast*>(data)->push_back(stored); }, &muted); } lock(); if (unreadNeeded && !globals().unreadLoaded) { globals().unreadLoaded = true; for (const auto& entry : unread) { // What counted while the file was read is kept if (findUnread(entry.backend, entry.peer.length > 0 ? &entry.peer : nullptr, entry.channel) == nullptr) { globals().unread.push_back(entry); } } } if (mutedNeeded && !globals().mutedLoaded) { globals().mutedLoaded = true; for (const auto& token : muted) { globals().muted.push_back(token.c_str()); } } unlock(); } /** * The latest count of each conversation that isn't stored yet. A save that fails stays here and is tried again, and only the * latest count is ever written, so an older one can't overtake a newer one. Guarded by the global lock. */ static tt::std::map& pendingUnread() { static auto* instance = tt::newObject>(); check(instance != nullptr); return *instance; } static bool unreadFlushQueued = false; /** Work for the file operations task, so that no thread waits for the storage to count messages */ static void flushUnread(void*) { while (true) { // The pending counts are copied under the lock and written in one update, so the file operations task isn't // held by one write per conversation lock(); std::vector tokens; std::vector counts; for (const auto& [token, count] : pendingUnread()) { tokens.push_back(token.c_str()); counts.push_back(count); } if (tokens.empty()) { unreadFlushQueued = false; unlock(); return; } unlock(); std::vector names; for (const auto& token : tokens) { names.push_back(token.c_str()); } const bool saved = mesh_settings_save_unread(names.data(), counts.data(), names.size()) == ERROR_NONE; lock(); if (!saved) { // Everything stays pending LOG_W(TAG, "Failed to store the unread counts, they are tried again later"); unreadFlushQueued = false; unlock(); return; } // A count that changed meanwhile stays pending for (size_t i = 0; i < tokens.size(); i++) { const auto entry = pendingUnread().find(tt::std::string(tokens[i].c_str())); if (entry != pendingUnread().end() && entry->second == counts[i]) { pendingUnread().erase(entry); } } unlock(); } } /** Requires the global lock. Queues a flush unless one is queued already. */ static void queueUnreadFlush() { if (unreadFlushQueued || pendingUnread().empty()) { return; } unreadFlushQueued = true; if (file_ops_queue(flushUnread, nullptr, nullptr) != ERROR_NONE) { unreadFlushQueued = false; } } /** Requires the global lock. Stores the count of a conversation without waiting for it. */ static void queueUnreadSave(const std::string& token, uint32_t count) { pendingUnread()[token.c_str()] = count; queueUnreadFlush(); } /** Replaces the first "{}" of a translated text by a number */ static std::string formatCount(const char* text, uint32_t count) { std::string result = text; const size_t position = result.find("{}"); if (position != std::string::npos) { // Counting stops at the limit, so more than 99 is only known as 99+ result.replace(position, 2, count >= MESH_UNREAD_COUNT_LIMIT ? "99+" : std::to_string(count)); } return result; } /** * Shows the Mesh app. It runs on a task of its own, as stopping an app waits for it, and the app can be waiting for the * service thread, which must not be the one that waits. The task ends itself, so nothing refers to it. */ static void openAppTask(void*) { // An app that is the topmost one already is what the user wants to see char topmost[APP_MANIFEST_ID_LENGTH + 1] = {}; const bool alreadyTopmost = app_manager_get_topmost_app_id(topmost, sizeof(topmost)) == ERROR_NONE && strcmp(topmost, MESH_APP_ID) == 0; if (!alreadyTopmost) { // One in the background can't be brought forward, so it is replaced by a new one that shows the chats AppInstanceId running = 0; if (app_manager_find_running_instance(MESH_APP_ID, &running) == ERROR_NONE) { app_manager_stop(running); // The new one starts when the old one is gone for (int i = 0; i < OPEN_APP_STOP_WAIT_STEPS && app_manager_is_running(MESH_APP_ID); i++) { delay_millis(50); } } if (app_manager_is_running(MESH_APP_ID)) { LOG_W(TAG, "The Mesh app didn't stop, so it isn't started again"); } else { AppStartContext context; AppInstanceId instance = 0; if (app_start_context_from_id(MESH_APP_ID, &context) == ERROR_NONE) { app_start_with_context(&context, &instance); } } } vTaskDelete(nullptr); } /** * Runs when the notification is tapped, on the task of the UI. It only starts a task that does the work. * The notification is sticky, so it goes when no message is unread anymore, not when it is tapped. */ static void onMessageNotificationAction(uint32_t /*id*/, void* /*data*/) { if (xTaskCreate(openAppTask, "mesh_open", OPEN_APP_STACK_SIZE, nullptr, tskIDLE_PRIORITY + 2, nullptr) != pdPASS) { LOG_E(TAG, "Failed to start the task that shows the Mesh app"); } } /** The unread messages of all conversations of the active backend, up to the limit. Takes the global lock. */ static uint32_t getTotalUnread(MeshHost* host, bool* hasUnmuted = nullptr) { lock(); uint32_t total = 0; bool unmuted = false; if (host->storageBackend[0] != '\0') { for (const auto& entry : globals().unread) { if (entry.count > 0 && strncmp(entry.backend, host->storageBackend, MESH_BACKEND_ID_MAX_LENGTH) == 0) { total += entry.count; // Unread messages of muted conversations are counted, but they don't raise a notification unmuted |= !isMuted(mutedToken(entry.backend, entry.peer.length > 0 ? &entry.peer : nullptr, entry.channel)); } } } unlock(); // Read in the same lock as the total, so the two describe one state if (hasUnmuted != nullptr) { *hasUnmuted = unmuted; } return std::min(total, UNREAD_COUNT_LIMIT); } /** Sends or updates the notification with the number of unread messages. @return false when the update didn't find the notification. */ static bool postMessageNotification(MeshHost* host, uint32_t unread, bool update) { const char* pattern = localisation_get(nullptr, unread == 1 ? "{} new message" : "{} new messages"); const std::string message = formatCount(pattern, unread); NotificationContext context = notification_context_for_service(MESH_SERVICE_ID, message.c_str()); notification_context_set_action(&context, onMessageNotificationAction, nullptr); notification_context_set_sticky(&context, true); uint32_t id = host->notificationId; const error_t error = update ? notification_update(id, &context, true) : notification_send(&context, &id); if (error != ERROR_NONE) { notification_context_destroy(&context); return false; } host->notificationId = id; return true; } /** One notification shows how many messages are unread in total, until the user dismisses it. Called on the service thread. */ static void notifyNewMessage(MeshHost* host) { const uint32_t unread = getTotalUnread(host); if (unread == 0) { return; } if (host->notificationId != 0 && postMessageNotification(host, unread, true)) { return; } // There is none yet, or the user dismissed it host->notificationId = 0; postMessageNotification(host, unread, false); } /** Follows the number of unread messages when a conversation is read: a new count, or no notification when all are read. Service thread. */ static void refreshMessageNotification(MeshHost* host) { if (host->notificationId == 0) { return; } bool hasUnmuted = false; const uint32_t unread = getTotalUnread(host, &hasUnmuted); // A notification without an unmuted conversation behind it goes, which is the case after the last one was read or muted if (unread == 0 || !hasUnmuted) { dismissMessageNotification(host); } else if (!postMessageNotification(host, unread, true)) { // The user dismissed it, which isn't undone host->notificationId = 0; } } /** Unread messages that are left from before the service started get a notification again. Service thread. */ static void restoreMessageNotification(MeshHost* host) { if (host->notificationId != 0) { return; } // One snapshot of the counts and of what is muted, as they can change while this runs bool hasUnmuted = false; const uint32_t unread = getTotalUnread(host, &hasUnmuted); if (unread > 0 && hasUnmuted) { postMessageNotification(host, unread, false); } } uint32_t mesh_host_receive_text( MeshHost* host, const MeshAddress* from, uint8_t channel, const char* sender_name, const char* text, float rssi, float snr, int64_t sender_time ) { MeshMessage message {}; strncpy(message.backend, host->api->id, MESH_BACKEND_ID_MAX_LENGTH); message.outgoing = false; message.delivery = MESH_DELIVERY_RECEIVED; if (from != nullptr) { message.peer = *from; } message.channel = channel; if (sender_name != nullptr) { strncpy(message.sender_name, sender_name, MESH_NAME_MAX_LENGTH); } const int64_t now = (int64_t)time(nullptr); if (now >= MIN_VALID_WALL_TIME) { message.wall_time = now; message.time_source = MESH_TIME_SOURCE_SYSTEM; } else if (sender_time >= MIN_VALID_WALL_TIME) { message.wall_time = sender_time; message.time_source = MESH_TIME_SOURCE_MESH; } else { message.time_source = MESH_TIME_SOURCE_NONE; } message.uptime_ms = getMillis(); message.rssi = rssi; message.snr = snr; strncpy(message.text, text, MESH_TEXT_MAX_LENGTH); lock(); uint32_t seq = 0; bool notify = false; std::string unreadToken; if (host->store.add(&message) == ERROR_NONE) { seq = message.seq; // A sender of a direct message is saved, so the conversation can be found and answered if (from != nullptr && from->length > 0) { addContact(host, *from, sender_name, false); } unreadToken = mutedToken(host->api->id, from, channel); notify = !isMuted(unreadToken); // Unread messages are counted when they arrive, so showing the count never reads the history Globals::UnreadEntry* entry = findUnread(host->api->id, from, channel); if (entry == nullptr && globals().unread.size() < MAX_UNREAD_ENTRIES) { Globals::UnreadEntry created {}; strncpy(created.backend, host->api->id, MESH_BACKEND_ID_MAX_LENGTH); if (from != nullptr && from->length > 0) { created.peer = *from; } else { created.channel = channel; } created.peerHash = MeshStore::hashPeerAddress(created.peer.length > 0 ? &created.peer : nullptr); globals().unread.push_back(created); entry = &globals().unread.back(); } if (entry != nullptr) { entry->count = std::min(entry->count + 1, UNREAD_COUNT_LIMIT); // Queued under the lock that changed the count, so the saves are written in the order of the changes queueUnreadSave(unreadToken, entry->count); } emitEvent(MESH_EVENT_MESSAGE, host->state, seq, MESH_DELIVERY_RECEIVED); } unlock(); if (seq != 0 && notify) { notifyNewMessage(host); } return seq; } void mesh_host_set_delivery(MeshHost* host, uint32_t seq, MeshDeliveryState delivery) { lock(); setDelivery(host, seq, delivery); unlock(); } void mesh_host_set_retry(MeshHost* host, uint32_t seq, uint8_t attempt, uint8_t max) { lock(); if (host->store.setDelivery(seq, MESH_DELIVERY_RETRYING) == ERROR_NONE) { MeshEvent event {}; event.timestamp = get_micros_since_boot(); event.type = MESH_EVENT_DELIVERY; event.state = host->state; event.seq = seq; event.delivery = MESH_DELIVERY_RETRYING; event.retry_attempt = attempt; event.retry_max = max; queueEvent(event); } unlock(); } void mesh_host_set_repeats(MeshHost* host, uint32_t seq, uint8_t count) { lock(); if (host->store.setDelivery(seq, MESH_DELIVERY_REPEATED) == ERROR_NONE) { MeshEvent event {}; event.timestamp = get_micros_since_boot(); event.type = MESH_EVENT_DELIVERY; event.state = host->state; event.seq = seq; event.delivery = MESH_DELIVERY_REPEATED; event.repeat_count = count; queueEvent(event); } unlock(); } void mesh_host_node_heard(MeshHost* host, const MeshAddress* address, const char* name, float rssi, float snr) { lock(); MeshNode* node = nullptr; for (auto& candidate : host->nodes) { if (candidate.address.length == address->length && memcmp(candidate.address.bytes, address->bytes, address->length) == 0) { node = &candidate; break; } } if (node == nullptr) { if (host->nodes.size() >= MAX_NODES) { // Replace the node that wasn't heard for the longest time auto oldest = host->nodes.begin(); for (auto iterator = host->nodes.begin(); iterator != host->nodes.end(); ++iterator) { if (iterator->last_heard_ms < oldest->last_heard_ms) { oldest = iterator; } } host->nodes.erase(oldest); } host->nodes.push_back({}); node = &host->nodes.back(); strncpy(node->backend, host->activeBackend, MESH_BACKEND_ID_MAX_LENGTH); node->address = *address; } if (name != nullptr) { strncpy(node->name, name, MESH_NAME_MAX_LENGTH); node->name[MESH_NAME_MAX_LENGTH] = '\0'; } node->last_heard_ms = getMillis(); node->rssi = rssi; node->snr = snr; emitEvent(MESH_EVENT_NODE, host->state, 0, MESH_DELIVERY_RECEIVED); unlock(); } bool mesh_host_is_contact(MeshHost* host, const MeshAddress* address) { lock(); const bool found = findContact(host, *address) != nullptr; unlock(); return found; } void mesh_host_advert_heard(MeshHost* host, const MeshAddress* address, const char* name, float rssi, float snr) { mesh_host_node_heard(host, address, name, rssi, snr); lock(); for (auto& node : host->nodes) { if (node.address.length == address->length && memcmp(node.address.bytes, address->bytes, address->length) == 0) { node.last_advert_ms = getMillis(); break; } } emitFrame(host->state, MESH_FRAME_ADVERT, 0, rssi, snr, address, name); unlock(); } error_t mesh_host_run_file_work(MeshHost*, void (*work)(void* context), void* context) { return runFileWork([work, context] { work(context); }) ? ERROR_NONE : ERROR_RESOURCE; } error_t mesh_host_get_data_path(MeshHost* host, const char* child_path, char* out_path, size_t out_path_size) { char directory[FILE_MAX_PATH_STRING_LENGTH]; char backendDirectory[16 + MESH_BACKEND_ID_MAX_LENGTH]; snprintf(backendDirectory, sizeof(backendDirectory), "backends/%s", host->api->id); if (service_paths_get_user_data_path(MESH_SERVICE_ID, backendDirectory, directory, sizeof(directory)) != ERROR_NONE) { return ERROR_BUFFER_OVERFLOW; } const error_t made = directory_make(directory, true); if (made != ERROR_NONE && made != ERROR_ALREADY_EXISTS) { return ERROR_RESOURCE; } const int written = snprintf(out_path, out_path_size, "%s/%s", directory, child_path); return (written < 0 || (size_t)written >= out_path_size) ? ERROR_BUFFER_OVERFLOW : ERROR_NONE; } void mesh_host_get_network(MeshHost* host, MeshNetworkSettings* network) { lock(); *network = host->network; unlock(); } void mesh_host_get_node_name(MeshHost*, char* name, size_t name_size) { lock(); ensureSettingsLoaded(); strncpy(name, globals().settings.node_name, name_size - 1); name[name_size - 1] = '\0'; unlock(); } // endregion // region Public API const char* mesh_state_to_string(MeshState state) { switch (state) { case MESH_STATE_OFF: return "off"; case MESH_STATE_ON: return "on"; case MESH_STATE_NO_RADIO: return "no radio"; case MESH_STATE_RADIO_BUSY: return "radio busy"; case MESH_STATE_NO_REGION: return "no region"; case MESH_STATE_NO_BACKEND: return "no backend"; case MESH_STATE_ERROR: return "error"; default: return "unknown"; } } error_t mesh_set_enabled(bool enabled) { lock(); ensureSettingsLoaded(); globals().settings.enabled = enabled; const MeshSettings copy = globals().settings; unlock(); const error_t saved = mesh_settings_save(©); const error_t result = enabled ? service_manager_start(MESH_SERVICE_ID) : service_manager_stop(MESH_SERVICE_ID); return (result != ERROR_NONE) ? result : saved; } bool mesh_is_enabled(void) { lock(); ensureSettingsLoaded(); const bool enabled = globals().settings.enabled; unlock(); return enabled; } MeshState mesh_get_state(void) { lock(); const MeshState state = (service != nullptr) ? service->state : MESH_STATE_OFF; unlock(); return state; } error_t mesh_set_node_name(const char* name) { if (name == nullptr || name[0] == '\0' || strlen(name) > MESH_NAME_MAX_LENGTH) { return ERROR_INVALID_ARGUMENT; } lock(); ensureSettingsLoaded(); strncpy(globals().settings.node_name, name, MESH_NAME_MAX_LENGTH); globals().settings.node_name[MESH_NAME_MAX_LENGTH] = '\0'; const MeshSettings copy = globals().settings; // The backend announces the new name if (service != nullptr) { post(service, [host = service] { if (host->api != nullptr && host->api->on_node_name_changed != nullptr) { host->api->on_node_name_changed(host->backend); } }); } unlock(); return mesh_settings_save(©); } error_t mesh_set_rx_boosted_gain(bool enabled) { lock(); ensureSettingsLoaded(); globals().settings.rx_boosted_gain = enabled; const MeshSettings copy = globals().settings; if (service != nullptr) { // Only the radio changes. Configuring again would recreate the backend, which loses the acknowledgements // that it still waits for. MeshHost* host = service; post(host, [host, enabled] { if (host->radio != nullptr && host->radioAcquired) { radio_set_parameter(host->radio, RADIO_PARAMETER_BOOSTED_GAIN, enabled ? 1 : 0); } }); } unlock(); return mesh_settings_save(©); } error_t mesh_get_rx_boosted_gain(bool* enabled) { Device* radio = findRadio(); if (radio == nullptr) { return ERROR_NOT_FOUND; } int32_t value = 0; const error_t supported = radio_get_parameter(radio, RADIO_PARAMETER_BOOSTED_GAIN, &value); device_put(radio); if (supported != ERROR_NONE) { return ERROR_NOT_SUPPORTED; } lock(); ensureSettingsLoaded(); *enabled = globals().settings.rx_boosted_gain; unlock(); return ERROR_NONE; } error_t mesh_get_node_name(char* name, size_t name_size) { if (name_size == 0) { return ERROR_BUFFER_OVERFLOW; } mesh_host_get_node_name(nullptr, name, name_size); return ERROR_NONE; } bool mesh_is_available(void) { Device* radio = findRadio(); if (radio == nullptr) { return false; } device_put(radio); return true; } size_t mesh_get_radio_count(void) { size_t count = 0; device_for_each_of_type(&RADIO_TYPE, &count, [](Device* device, void* context) { if (isMeshRadio(device)) { (*static_cast(context))++; } return true; }); return count; } error_t mesh_get_radio_kind(size_t index, MeshRadioKind* kind) { struct Search { size_t index; MeshRadioKind* kind; error_t result; } search = { index, kind, ERROR_NOT_FOUND }; device_for_each_of_type(&RADIO_TYPE, &search, [](Device* device, void* context) { auto* search = static_cast(context); if (!isMeshRadio(device)) { return true; } if (search->index-- > 0) { return true; } *search->kind = usesLora(device) ? MESH_RADIO_LORA : MESH_RADIO_ESPNOW; search->result = ERROR_NONE; return false; }); return search.result; } error_t mesh_get_radio_name(size_t index, char* name, size_t name_size) { struct Search { size_t index; char* name; size_t size; error_t result; } search = { index, name, name_size, ERROR_NOT_FOUND }; device_for_each_of_type(&RADIO_TYPE, &search, [](Device* device, void* context) { auto* search = static_cast(context); if (!isMeshRadio(device)) { return true; } if (search->index-- > 0) { return true; } if (search->size > 0) { strncpy(search->name, device->name, search->size - 1); search->name[search->size - 1] = '\0'; search->result = ERROR_NONE; } return false; }); return search.result; } error_t mesh_get_radio(char* name, size_t name_size) { Device* radio = findRadio(); if (radio == nullptr || name_size == 0) { if (radio != nullptr) { device_put(radio); } return ERROR_NOT_FOUND; } strncpy(name, radio->name, name_size - 1); name[name_size - 1] = '\0'; device_put(radio); return ERROR_NONE; } error_t mesh_set_radio(const char* name) { const char* selected = (name != nullptr) ? name : ""; if (selected[0] != '\0') { bool found = false; for (size_t i = 0, count = mesh_get_radio_count(); i < count && !found; i++) { char radioName[MESH_NAME_MAX_LENGTH + 1]; found = mesh_get_radio_name(i, radioName, sizeof(radioName)) == ERROR_NONE && strcmp(radioName, selected) == 0; } if (!found) { return ERROR_NOT_FOUND; } } lock(); ensureSettingsLoaded(); strncpy(globals().settings.radio, selected, MESH_NAME_MAX_LENGTH); globals().settings.radio[MESH_NAME_MAX_LENGTH] = '\0'; const MeshSettings copy = globals().settings; if (service != nullptr) { MeshHost* host = service; post(host, [host] { reselectRadio(host); }); } unlock(); return mesh_settings_save(©); } size_t mesh_get_backend_count(void) { lock(); const size_t count = globals().backendCount; unlock(); return count; } error_t mesh_get_backend_id(size_t index, char* id, size_t id_size) { lock(); error_t result = ERROR_NOT_FOUND; if (index < globals().backendCount && id_size > 0) { strncpy(id, globals().backends[index]->id, id_size - 1); id[id_size - 1] = '\0'; result = ERROR_NONE; } unlock(); return result; } error_t mesh_set_backend(const char* id) { lock(); if (findBackend(id) == nullptr) { unlock(); return ERROR_NOT_FOUND; } ensureSettingsLoaded(); strncpy(globals().settings.backend, id, MESH_BACKEND_ID_MAX_LENGTH); globals().settings.backend[MESH_BACKEND_ID_MAX_LENGTH] = '\0'; const MeshSettings copy = globals().settings; if (service != nullptr) { MeshHost* host = service; post(host, [host] { configure(host); }); } unlock(); return mesh_settings_save(©); } error_t mesh_get_backend(char* id, size_t id_size) { lock(); ensureSettingsLoaded(); const char* selected = globals().settings.backend; if (service != nullptr && service->activeBackend[0] != '\0') { selected = service->activeBackend; } error_t result = ERROR_NOT_FOUND; if (selected[0] != '\0' && id_size > 0) { strncpy(id, selected, id_size - 1); id[id_size - 1] = '\0'; result = ERROR_NONE; } unlock(); return result; } bool mesh_supports(uint32_t features) { lock(); ensureSettingsLoaded(); const MeshBackendApi* api = getSelectedBackend(); const bool supported = api != nullptr && (api->features & features) == features; unlock(); return supported; } size_t mesh_get_preset_count(const char* backend) { const bool applies = presetsApply(); lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); const size_t count = (api != nullptr && applies) ? getPresetCount(api) : 0; unlock(); return count; } error_t mesh_get_preset_name(const char* backend, size_t index, char* name, size_t name_size) { const bool applies = presetsApply(); lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); error_t result = ERROR_NOT_FOUND; if (api != nullptr && applies && index < getPresetCount(api) && name_size > 0) { strncpy(name, api->presets[index], name_size - 1); name[name_size - 1] = '\0'; result = ERROR_NONE; } unlock(); return result; } /** * Persists the settings of a backend, and only when that worked uses them: the cache is updated and the radio is * reconfigured when the backend is selected. Called without the global lock, because saving does file operations. */ static error_t commitBackendSettings(const MeshBackendApi* api, const MeshBackendSettings& settings) { const error_t saved = mesh_settings_save_backend(api->id, &settings); if (saved != ERROR_NONE) { return saved; } lock(); auto& entry = getBackendEntry(api); entry.settings = settings; // What was saved is what the backend runs with, whether or not the file could be read before entry.loaded = true; if (service != nullptr && api == getSelectedBackend()) { MeshHost* host = service; post(host, [host] { configure(host); }); } unlock(); return ERROR_NONE; } /** Holds the update mutex of a backend. Taken without the global lock, and the global lock is taken inside. */ struct UpdateGuard { Mutex* mutex; explicit UpdateGuard(Mutex* mutex) : mutex(mutex) { mutex_lock(mutex); } ~UpdateGuard() { mutex_unlock(mutex); } }; error_t mesh_set_preset(const char* backend, const char* name) { const bool applies = presetsApply(); Device* radio = findRadio(); const RadioRegion region = (radio != nullptr) ? radio_get_region(radio) : RADIO_REGION_UNSET; if (radio != nullptr) { device_put(radio); } lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); const size_t index = (api != nullptr) ? findPreset(api, name) : 0; if (api == nullptr || !applies || index >= getPresetCount(api) || strcmp(api->presets[index], name) != 0) { unlock(); return ERROR_NOT_FOUND; } Mutex* updateMutex = &getBackendEntry(api).update; unlock(); UpdateGuard guard(updateMutex); MeshBackendSettings settings = {}; strncpy(settings.preset, name, MESH_NAME_MAX_LENGTH); if (region != RADIO_REGION_UNSET) { // The radio would reject a preset that doesn't fit the region, which would leave the mesh in the error state MeshRadioProfile profile {}; if (getRadioProfile(api, nullptr, region, RADIO_MODULATION_LORA, index, settings.radio_settings, &profile) != ERROR_NONE || findBand(region, profile.frequency, profile.bandwidth) == nullptr) { return ERROR_NOT_SUPPORTED; } } return commitBackendSettings(api, settings); } error_t mesh_get_preset_region(const char* backend, const char* name, RadioRegion* region) { Device* radio = findRadio(); const RadioRegion current = (radio != nullptr) ? radio_get_region(radio) : RADIO_REGION_UNSET; if (radio != nullptr) { device_put(radio); } lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); const size_t index = (api != nullptr) ? findPreset(api, name) : 0; error_t result = ERROR_NOT_FOUND; if (api != nullptr && index < getPresetCount(api) && strcmp(api->presets[index], name) == 0) { *region = current; result = (api->get_preset_region != nullptr) ? api->get_preset_region(index, current, region) : ERROR_NONE; } unlock(); return result; } error_t mesh_get_preset(const char* backend, char* name, size_t name_size) { const bool applies = presetsApply(); lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); error_t result = ERROR_NOT_FOUND; if (api != nullptr && applies && getPresetCount(api) > 0 && name_size > 0) { strncpy(name, api->presets[findPreset(api, getBackendSettings(api).preset)], name_size - 1); name[name_size - 1] = '\0'; result = ERROR_NONE; } unlock(); return result; } error_t mesh_set_radio_settings(const char* backend, const MeshRadioSettings* radio_settings) { const bool applies = presetsApply(); Device* radio = findRadio(); const RadioRegion region = (radio != nullptr) ? radio_get_region(radio) : RADIO_REGION_UNSET; if (radio != nullptr) { device_put(radio); } lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); if (api == nullptr) { unlock(); return ERROR_NOT_FOUND; } Mutex* updateMutex = &getBackendEntry(api).update; unlock(); UpdateGuard guard(updateMutex); lock(); MeshBackendSettings settings = getBackendSettings(api); unlock(); settings.radio_settings = *radio_settings; if (applies && region != RADIO_REGION_UNSET) { // The radio rejects a channel outside the bands of the region, and a power above the limit of the band that holds // the channel. Either would leave the mesh in the error state. MeshRadioProfile profile {}; if (getRadioProfile(api, nullptr, region, RADIO_MODULATION_LORA, findPreset(api, settings.preset), settings.radio_settings, &profile) == ERROR_NONE) { const RadioRegionBand* band = findBand(region, profile.frequency, profile.bandwidth); if (profile.bandwidth <= 0 || band == nullptr || settings.radio_settings.power > band->power_max) { return ERROR_OUT_OF_RANGE; } } } return commitBackendSettings(api, settings); } error_t mesh_get_radio_settings(const char* backend, MeshRadioSettings* radio_settings) { lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); error_t result = ERROR_NOT_FOUND; if (api != nullptr) { *radio_settings = getBackendSettings(api).radio_settings; result = ERROR_NONE; } unlock(); return result; } error_t mesh_set_network_settings(const char* backend, const MeshNetworkSettings* network_settings) { if (network_settings->path_hash_size < 0 || network_settings->path_hash_size > MESH_PATH_HASH_SIZE_MAX) { return ERROR_INVALID_ARGUMENT; } lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); if (api == nullptr) { unlock(); return ERROR_NOT_FOUND; } Mutex* updateMutex = &getBackendEntry(api).update; unlock(); UpdateGuard guard(updateMutex); lock(); MeshBackendSettings settings = getBackendSettings(api); unlock(); settings.network = *network_settings; return commitBackendSettings(api, settings); } error_t mesh_get_network_settings(const char* backend, MeshNetworkSettings* network_settings) { lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); error_t result = ERROR_NOT_FOUND; if (api != nullptr) { *network_settings = getBackendSettings(api).network; result = ERROR_NONE; } unlock(); return result; } error_t mesh_get_network_parameters(const char* backend, MeshNetworkSettings* parameters) { lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); error_t result = ERROR_NOT_FOUND; if (api != nullptr) { const MeshBackendSettings settings = getBackendSettings(api); *parameters = getNetwork(api, findPreset(api, settings.preset), settings.network); result = ERROR_NONE; } unlock(); return result; } error_t mesh_get_radio_parameters(const char* backend, MeshRadioSettings* parameters) { const bool applies = presetsApply(); Device* radio = findRadio(); const RadioRegion region = (radio != nullptr) ? radio_get_region(radio) : RADIO_REGION_UNSET; if (radio != nullptr) { device_put(radio); } lock(); ensureSettingsLoaded(); const MeshBackendApi* api = resolveBackend(backend); error_t result = ERROR_INVALID_STATE; if (api != nullptr && service != nullptr && service->api == api && service->backend != nullptr && service->state == MESH_STATE_ON && service->profile.modulation == RADIO_MODULATION_LORA) { // The running backend knows its own state, e.g. the frequency slot that its primary channel selects parameters->frequency = service->profile.frequency; parameters->bandwidth = service->profile.bandwidth; parameters->spreading_factor = service->profile.spreading_factor; parameters->coding_rate = service->profile.coding_rate; parameters->power = service->profile.power; result = ERROR_NONE; } else if (api != nullptr && applies && region != RADIO_REGION_UNSET) { const MeshBackendSettings settings = getBackendSettings(api); MeshRadioProfile profile {}; // Without a running backend there is no state, so a backend that depends on it uses its defaults result = getRadioProfile(api, nullptr, region, RADIO_MODULATION_LORA, findPreset(api, settings.preset), settings.radio_settings, &profile); if (result == ERROR_NONE) { parameters->frequency = profile.frequency; parameters->bandwidth = profile.bandwidth; parameters->spreading_factor = profile.spreading_factor; parameters->coding_rate = profile.coding_rate; parameters->power = profile.power; } } unlock(); return result; } error_t mesh_send_text(const MeshAddress* to, uint8_t channel, const char* text, uint32_t* seq) { if (text == nullptr || strlen(text) > MESH_TEXT_MAX_LENGTH) { return ERROR_OUT_OF_RANGE; } lock(); MeshHost* host = service; if (host == nullptr || host->state != MESH_STATE_ON) { unlock(); return ERROR_INVALID_STATE; } MeshMessage message {}; strncpy(message.backend, host->activeBackend, MESH_BACKEND_ID_MAX_LENGTH); message.outgoing = true; message.delivery = MESH_DELIVERY_QUEUED; if (to != nullptr) { message.peer = *to; } message.channel = channel; strncpy(message.sender_name, globals().settings.node_name, MESH_NAME_MAX_LENGTH); const int64_t now = (int64_t)time(nullptr); message.wall_time = (now >= MIN_VALID_WALL_TIME) ? now : 0; message.time_source = (now >= MIN_VALID_WALL_TIME) ? MESH_TIME_SOURCE_SYSTEM : MESH_TIME_SOURCE_NONE; message.uptime_ms = getMillis(); message.snr = NAN; strncpy(message.text, text, MESH_TEXT_MAX_LENGTH); const error_t result = host->store.isOpen() ? host->store.add(&message) : ERROR_INVALID_STATE; if (result == ERROR_NONE) { emitEvent(MESH_EVENT_MESSAGE, host->state, message.seq, MESH_DELIVERY_QUEUED); const uint32_t messageSeq = message.seq; post(host, [host, messageSeq] { sendStored(host, messageSeq); }); if (seq != nullptr) { *seq = message.seq; } } unlock(); return result; } error_t mesh_cancel(uint32_t seq) { lock(); MeshHost* host = service; if (host == nullptr) { unlock(); return ERROR_INVALID_STATE; } MeshMessage message; if (!host->store.isOpen()) { unlock(); return ERROR_INVALID_STATE; } if (host->store.get(seq, &message) != ERROR_NONE || !message.outgoing) { unlock(); return ERROR_NOT_FOUND; } if (message.delivery != MESH_DELIVERY_QUEUED && message.delivery != MESH_DELIVERY_BLOCKED) { unlock(); return ERROR_INVALID_STATE; } setDelivery(host, seq, MESH_DELIVERY_CANCELLED); char backend[MESH_BACKEND_ID_MAX_LENGTH + 1]; strncpy(backend, message.backend, sizeof(backend) - 1); backend[sizeof(backend) - 1] = '\0'; post(host, [host, seq, backend = std::string(backend)] { std::erase_if(host->txQueue, [seq](const Frame& frame) { return frame.seq == seq; }); if (host->api != nullptr && host->api->cancel_send != nullptr && backend == host->api->id) { host->api->cancel_send(host->backend, seq); } }); unlock(); return ERROR_NONE; } error_t mesh_raw_send(const char* backend, const uint8_t* data, size_t length) { if (length == 0 || length > RADIO_RX_MAX_PACKET_LENGTH) { return ERROR_OUT_OF_RANGE; } // The caller's buffers stay valid during this synchronous call error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api != nullptr && strcmp(backend, host->api->id) == 0) { result = mesh_host_transmit(host, data, length, 0); } }); return (callResult != ERROR_NONE) ? callResult : result; } error_t mesh_get_info(MeshInfo* info) { *info = {}; const error_t callResult = callOnServiceThread([&](MeshHost* host) { const uint64_t nowMs = getMillis(); const uint32_t dutyCycle = getDutyCyclePercent(host); info->region = host->appliedRegion; info->radio.frequency = host->profile.frequency; info->radio.bandwidth = host->profile.bandwidth; info->radio.spreading_factor = host->profile.spreading_factor; info->radio.coding_rate = host->profile.coding_rate; info->radio.power = host->profile.power; info->duty_cycle_percent = dutyCycle; info->duty_cycle_window_ms = DUTY_CYCLE_WINDOW_MS; info->airtime_used_ms = getAirtimeUsedMs(host, nowMs); info->airtime_budget_ms = dutyCycle < 100 ? static_cast(DUTY_CYCLE_WINDOW_MS * dutyCycle / 100) : 0; // Blocked now means the frame at the front of the queue doesn't fit the budget, by the check that pumpTx() makes info->duty_cycle_blocked = false; if (dutyCycle < 100 && !host->txQueue.empty() && !host->txInFlight) { const uint32_t frameAirtimeMs = mesh_airtime_estimate_ms(host->profile, host->txQueue.front().data.size()); info->duty_cycle_blocked = info->airtime_used_ms + frameAirtimeMs > info->airtime_budget_ms; } info->tx_queue_length = static_cast(host->txQueue.size()); info->frames_sent = host->framesSent; info->frames_failed = host->framesFailed; info->frames_received = host->framesReceived; info->frames_unreadable = host->framesUnreadable; lock(); info->state = host->state; strncpy(info->backend, host->activeBackend, MESH_BACKEND_ID_MAX_LENGTH); info->messages_total = static_cast(host->store.getMessageCount()); info->messages_received = static_cast(host->store.countDelivery(MESH_DELIVERY_RECEIVED)); info->messages_sent = static_cast(host->store.countDelivery(MESH_DELIVERY_SENT) + host->store.countDelivery(MESH_DELIVERY_REPEATED) + host->store.countDelivery(MESH_DELIVERY_DELIVERED)); info->messages_failed = static_cast(host->store.countDelivery(MESH_DELIVERY_FAILED)); info->nodes_heard = static_cast(host->nodes.size()); info->contacts = static_cast(host->contacts.size()); unlock(); }); return callResult; } error_t mesh_message_get(uint32_t seq, MeshMessage* message) { lock(); // A store that is still being read has no complete index yet const error_t result = (service != nullptr && service->store.isOpen()) ? service->store.get(seq, message) : ERROR_INVALID_STATE; unlock(); return result; } /** A selected backend whose store failed to open must not look like an empty history. Requires the global lock and a service. */ static bool isStorageUnavailable() { return getSelectedBackend() != nullptr && !service->store.isOpen(); } /** Contacts are unavailable when the store failed to open or the contacts failed to load. Requires the global lock and a service. */ static bool isContactsUnavailable() { return getSelectedBackend() != nullptr && (!service->store.isOpen() || !service->contactsLoaded); } error_t mesh_history_get(uint32_t before_seq, MeshMessage* messages, size_t max_count, size_t* count) { lock(); error_t result = ERROR_INVALID_STATE; if (service != nullptr && !isStorageUnavailable()) { *count = service->store.getHistory(before_seq, messages, max_count); result = ERROR_NONE; } unlock(); return result; } error_t mesh_conversation_get(const MeshAddress* peer, uint8_t channel, uint32_t before_seq, MeshMessage* messages, size_t max_count, size_t* count) { lock(); error_t result = ERROR_INVALID_STATE; if (service != nullptr && !isStorageUnavailable()) { *count = service->store.getConversation(service->storageBackend, peer, channel, before_seq, messages, max_count); result = ERROR_NONE; } unlock(); return result; } bool mesh_get_conversation_notifications(const MeshAddress* peer, uint8_t channel) { lock(); ensureSettingsLoaded(); // The first registered backend is the selected one when the user didn't choose const MeshBackendApi* backend = getSelectedBackend(); const bool enabled = backend == nullptr || !isMuted(mutedToken(backend->id, peer, channel)); unlock(); return enabled; } error_t mesh_set_conversation_notifications(const MeshAddress* peer, uint8_t channel, bool enabled) { // The preference is stored first and applied after that, so a failed save changes nothing that receiving uses mutex_lock(&mutedMutex.handle); lock(); ensureSettingsLoaded(); const MeshBackendApi* backend = getSelectedBackend(); if (backend == nullptr) { unlock(); mutex_unlock(&mutedMutex.handle); return ERROR_INVALID_STATE; } const std::string token = mutedToken(backend->id, peer, channel); unlock(); if (mesh_settings_save_muted(token.c_str(), !enabled) != ERROR_NONE) { mutex_unlock(&mutedMutex.handle); return ERROR_RESOURCE; } lock(); const bool wasMuted = isMuted(token); if (enabled && wasMuted) { globals().muted.erase(findMuted(token)); } else if (!enabled && !wasMuted) { globals().muted.push_back(token.c_str()); } if (service != nullptr) { // A notification that only muted conversations are left behind is removed MeshHost* host = service; post(host, [host] { refreshMessageNotification(host); }); } unlock(); mutex_unlock(&mutedMutex.handle); return ERROR_NONE; } uint32_t mesh_get_unread(const MeshAddress* peer, uint8_t channel) { lock(); uint32_t count = 0; if (service != nullptr && !isStorageUnavailable()) { const Globals::UnreadEntry* entry = findUnread(service->storageBackend, peer, channel); count = entry != nullptr ? entry->count : 0; } unlock(); return count; } /** * Sets the unread count of a conversation to 0, and tells who shows it. Requires the global lock. * The entry is removed, so a slot is free for another conversation. */ static void clearUnreadLocked(const MeshAddress* peer, uint8_t channel) { if (service == nullptr || isStorageUnavailable()) { return; } Globals::UnreadEntry* entry = findUnread(service->storageBackend, peer, channel); if (entry == nullptr || entry->count == 0) { return; } // Queued under the lock that changed the count, so the saves are written in the order of the changes queueUnreadSave(mutedToken(service->storageBackend, peer, channel), 0); globals().unread.erase(globals().unread.begin() + (entry - globals().unread.data())); emitEvent(MESH_EVENT_UNREAD, service->state, 0, MESH_DELIVERY_RECEIVED); // The notification shows the total, which changed MeshHost* host = service; post(host, [host] { refreshMessageNotification(host); }); } void mesh_mark_read(const MeshAddress* peer, uint8_t channel) { lock(); clearUnreadLocked(peer, channel); unlock(); } void mesh_mark_all_read(void) { lock(); if (service != nullptr && !isStorageUnavailable()) { bool cleared = false; for (size_t i = 0; i < globals().unread.size();) { const Globals::UnreadEntry& entry = globals().unread[i]; if (strncmp(entry.backend, service->storageBackend, MESH_BACKEND_ID_MAX_LENGTH) == 0) { if (entry.count > 0) { queueUnreadSave(mutedToken(entry.backend, entry.peer.length > 0 ? &entry.peer : nullptr, entry.channel), 0); cleared = true; } globals().unread.erase(globals().unread.begin() + i); } else { i++; } } if (cleared) { emitEvent(MESH_EVENT_UNREAD, service->state, 0, MESH_DELIVERY_RECEIVED); // The notification shows the total, which is 0 now MeshHost* host = service; post(host, [host] { refreshMessageNotification(host); }); } } unlock(); } error_t mesh_delete_conversation(const MeshAddress* peer, uint8_t channel) { lock(); error_t result = ERROR_INVALID_STATE; if (service != nullptr && !isStorageUnavailable()) { result = service->store.removeConversation(service->storageBackend, peer, channel); // Cleared under the same lock, so a message that arrives after the deletion starts a new count if (result == ERROR_NONE) { clearUnreadLocked(peer, channel); } } unlock(); return result; } error_t mesh_get_contacts(MeshContact* contacts, size_t max_count, size_t* count) { lock(); error_t result = ERROR_INVALID_STATE; if (service != nullptr && !isContactsUnavailable()) { *count = 0; for (const auto& contact : service->contacts) { if (*count < max_count && strncmp(contact.backend, service->storageBackend, MESH_BACKEND_ID_MAX_LENGTH) == 0) { contacts[(*count)++] = contact; } } result = ERROR_NONE; } unlock(); return result; } error_t mesh_add_contact(const MeshAddress* address, const char* name) { if (address->length == 0 || address->length > MESH_ADDRESS_MAX_LENGTH) { return ERROR_INVALID_ARGUMENT; } bool valid = true; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api != nullptr && host->api->is_valid_contact_address != nullptr) { valid = host->api->is_valid_contact_address(host->backend, address); } }); if (callResult != ERROR_NONE) { return callResult; } if (!valid) { return ERROR_INVALID_ARGUMENT; } lock(); error_t result = ERROR_INVALID_STATE; if (service != nullptr) { result = addContact(service, *address, name, true); } unlock(); return result; } error_t mesh_remove_contact(const MeshAddress* address) { lock(); error_t result = ERROR_INVALID_STATE; if (service != nullptr) { auto* contact = findContact(service, *address); if (!service->contactsLoaded) { result = ERROR_INVALID_STATE; } else if (contact == nullptr) { result = ERROR_NOT_FOUND; } else { service->contacts.erase(service->contacts.begin() + (contact - service->contacts.data())); saveContacts(service); emitEvent(MESH_EVENT_CONTACT, service->state, 0, MESH_DELIVERY_RECEIVED); // The backend can forget what it pinned for the node, as removing a contact is how the user resets it const MeshAddress removed = *address; MeshHost* host = service; post(host, [host, removed] { if (host->api != nullptr && host->api->on_contact_removed != nullptr) { host->api->on_contact_removed(host->backend, &removed); } }); result = ERROR_NONE; } } unlock(); return result; } error_t mesh_get_contact_uri(const MeshAddress* contact, char* uri, size_t uri_size) { char name[MESH_NAME_MAX_LENGTH + 1] = {}; lock(); if (service == nullptr) { unlock(); return ERROR_INVALID_STATE; } if (contact == nullptr) { strncpy(name, globals().settings.node_name, MESH_NAME_MAX_LENGTH); } else { const auto* saved = findContact(service, *contact); if (saved == nullptr) { unlock(); return ERROR_NOT_FOUND; } strncpy(name, saved->name, MESH_NAME_MAX_LENGTH); } unlock(); error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api == nullptr) { return; } result = (host->api->get_contact_uri != nullptr) ? host->api->get_contact_uri(host->backend, contact, name, uri, uri_size) : ERROR_NOT_SUPPORTED; }); return (callResult != ERROR_NONE) ? callResult : result; } error_t mesh_get_nodes(MeshNode* nodes, size_t max_count, size_t* count) { lock(); error_t result = ERROR_INVALID_STATE; if (service != nullptr) { *count = std::min(max_count, service->nodes.size()); std::copy_n(service->nodes.begin(), *count, nodes); result = ERROR_NONE; } unlock(); return result; } error_t mesh_get_channels(MeshChannel* channels, size_t max_count, size_t* count) { error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api == nullptr) { return; } result = (host->api->get_channels != nullptr) ? host->api->get_channels(host->backend, channels, max_count, count) : ERROR_NOT_SUPPORTED; }); return (callResult != ERROR_NONE) ? callResult : result; } /** Tells the subscribers that the channels changed, when the change succeeded */ static void emitChannelChanged(error_t result) { if (result != ERROR_NONE) { return; } lock(); if (service != nullptr) { emitEvent(MESH_EVENT_CHANNEL, service->state, 0, MESH_DELIVERY_RECEIVED); } unlock(); } error_t mesh_set_channel(const MeshChannel* channel) { error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api == nullptr) { return; } result = (host->api->set_channel != nullptr) ? host->api->set_channel(host->backend, channel) : ERROR_NOT_SUPPORTED; }); const error_t finalResult = (callResult != ERROR_NONE) ? callResult : result; emitChannelChanged(finalResult); return finalResult; } error_t mesh_remove_channel(uint8_t index) { error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api == nullptr) { return; } result = (host->api->remove_channel != nullptr) ? host->api->remove_channel(host->backend, index) : ERROR_NOT_SUPPORTED; }); const error_t finalResult = (callResult != ERROR_NONE) ? callResult : result; emitChannelChanged(finalResult); return finalResult; } /** Whether the contact is saved in the service, which includes contacts that were added before their advert was heard */ static bool isSavedContact(MeshHost* host, const MeshAddress* contact) { lock(); bool found = false; for (const auto& saved : host->contacts) { if (strncmp(saved.backend, host->storageBackend, MESH_BACKEND_ID_MAX_LENGTH) == 0 && saved.address.length == contact->length && memcmp(saved.address.bytes, contact->bytes, contact->length) == 0) { found = true; break; } } unlock(); return found; } error_t mesh_set_contact_path(const MeshAddress* contact, const uint8_t* hops, size_t hop_count, size_t hash_size) { if (hop_count == 0 || hash_size == 0 || hash_size > 4) { return ERROR_INVALID_ARGUMENT; } error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api == nullptr) { return; } if (!isSavedContact(host, contact)) { result = ERROR_NOT_FOUND; return; } result = (host->api->set_contact_path != nullptr) ? host->api->set_contact_path(host->backend, contact, hops, hop_count, hash_size) : ERROR_NOT_SUPPORTED; }); return (callResult != ERROR_NONE) ? callResult : result; } error_t mesh_get_contact_path(const MeshAddress* contact, MeshContactPath* path) { error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api == nullptr) { return; } if (!isSavedContact(host, contact)) { result = ERROR_NOT_FOUND; return; } result = (host->api->get_contact_path != nullptr) ? host->api->get_contact_path(host->backend, contact, path) : ERROR_NOT_SUPPORTED; }); return (callResult != ERROR_NONE) ? callResult : result; } error_t mesh_reset_contact_path(const MeshAddress* contact) { error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api == nullptr) { return; } if (!isSavedContact(host, contact)) { result = ERROR_NOT_FOUND; return; } result = (host->api->reset_contact_path != nullptr) ? host->api->reset_contact_path(host->backend, contact) : ERROR_NOT_SUPPORTED; }); return (callResult != ERROR_NONE) ? callResult : result; } error_t mesh_send_advert(MeshAdvertRoute route) { error_t result = ERROR_INVALID_STATE; const error_t callResult = callOnServiceThread([&](MeshHost* host) { if (host->api == nullptr) { return; } result = (host->api->send_advert != nullptr) ? host->api->send_advert(host->backend, route) : ERROR_NOT_SUPPORTED; }); return (callResult != ERROR_NONE) ? callResult : result; } // endregion // region Events error_t mesh_event_subscribe(MeshEventSubscription* sub, TaskEventGroup* event_group) { uint32_t bit; const error_t claimed = task_event_group_claim_bit(event_group, &bit); if (claimed != ERROR_NONE) { return claimed; } lock(); for (auto* existing = globals().subscriptions; existing != nullptr; existing = existing->internal.next) { if (existing == sub) { unlock(); task_event_group_release_bit(event_group, bit); return ERROR_INVALID_STATE; } } sub->bit = bit; sub->internal.event_group = event_group; sub->internal.head = 0; sub->internal.count = 0; sub->internal.next = globals().subscriptions; globals().subscriptions = sub; unlock(); return ERROR_NONE; } error_t mesh_event_unsubscribe(MeshEventSubscription* sub) { error_t result = ERROR_NOT_FOUND; lock(); for (auto** link = &globals().subscriptions; *link != nullptr; link = &(*link)->internal.next) { if (*link == sub) { *link = sub->internal.next; result = ERROR_NONE; break; } } unlock(); if (result == ERROR_NONE) { task_event_group_release_bit(sub->internal.event_group, sub->bit); } return result; } error_t mesh_event_poll(MeshEventSubscription* sub, MeshEvent* event) { lock(); const bool hasEvent = sub->internal.count > 0; if (hasEvent) { *event = sub->internal.queue[sub->internal.head]; sub->internal.head = (sub->internal.head + 1) % MESH_EVENT_QUEUE_CAPACITY; sub->internal.count--; } unlock(); return hasEvent ? ERROR_NONE : ERROR_TIMEOUT; } // endregion } // extern "C"