Files
firmware/src/mesh/MeshModule.cpp

314 lines
13 KiB
C++
Raw Normal View History

#include "MeshModule.h"
#include "Channels.h"
2020-12-07 10:18:11 +08:00
#include "MeshService.h"
2021-03-05 11:44:45 +08:00
#include "NodeDB.h"
2023-01-21 14:34:29 +01:00
#include "configuration.h"
#include "modules/RoutingModule.h"
#include <algorithm>
#include <assert.h>
std::vector<MeshModule *> *MeshModule::modules;
const meshtastic_MeshPacket *MeshModule::currentRequest;
uint8_t MeshModule::numPeriodicModules = 0;
2020-12-13 12:57:37 +08:00
2021-03-05 11:44:45 +08:00
/**
* If any of the current chain of modules has already sent a reply, it will be here. This is useful to allow
* the RoutingModule to avoid sending redundant acks
2021-03-05 11:44:45 +08:00
*/
meshtastic_MeshPacket *MeshModule::currentReply;
2021-03-05 11:44:45 +08:00
MeshModule::MeshModule(const char *_name) : name(_name)
{
// Can't trust static initializer order, so we check each time
2022-02-27 01:49:24 -08:00
if (!modules)
modules = new std::vector<MeshModule *>();
2022-02-27 01:49:24 -08:00
modules->push_back(this);
}
void MeshModule::setup() {}
MeshModule::~MeshModule()
{
auto it = std::find(modules->begin(), modules->end(), this);
assert(it != modules->end());
modules->erase(it);
}
// ⚠️ **Only call once** to set the initial delay before a module starts broadcasting periodically
int32_t MeshModule::setStartDelay()
{
int32_t startDelay = MESHMODULE_MIN_BROADCAST_DELAY_MS + numPeriodicModules * MESHMODULE_BROADCAST_SPACING_MS;
numPeriodicModules++;
return startDelay;
}
meshtastic_MeshPacket *MeshModule::allocAckNak(meshtastic_Routing_Error err, NodeNum to, PacketId idFrom, ChannelIndex chIndex,
uint8_t hopLimit)
{
meshtastic_Routing c = meshtastic_Routing_init_default;
c.error_reason = err;
c.which_variant = meshtastic_Routing_error_reason_tag;
// Now that we have moded sendAckNak up one level into the class hierarchy we can no longer assume we are a RoutingModule
// So we manually call pb_encode_to_bytes and specify routing port number
// auto p = allocDataProtobuf(c);
meshtastic_MeshPacket *p = router->allocForSending();
p->decoded.portnum = meshtastic_PortNum_ROUTING_APP;
2023-01-21 18:39:58 +01:00
p->decoded.payload.size =
pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &meshtastic_Routing_msg, &c);
p->priority = meshtastic_MeshPacket_Priority_ACK;
p->hop_limit = hopLimit; // Flood ACK back to original sender
p->to = to;
p->decoded.request_id = idFrom;
p->channel = chIndex;
if (err != meshtastic_Routing_Error_NONE)
LOG_WARN("Alloc an err=%d,to=0x%x,idFrom=0x%x,id=0x%x", err, to, idFrom, p->id);
return p;
}
meshtastic_MeshPacket *MeshModule::allocErrorResponse(meshtastic_Routing_Error err, const meshtastic_MeshPacket *p)
{
// If the original packet couldn't be decoded, use the primary channel
uint8_t channelIndex =
p->which_payload_variant == meshtastic_MeshPacket_decoded_tag ? p->channel : channels.getPrimaryIndex();
auto r = allocAckNak(err, getFrom(p), p->id, channelIndex);
setReplyTo(r, *p);
return r;
}
void MeshModule::callModules(meshtastic_MeshPacket &mp, RxSource src)
{
// LOG_DEBUG("In call modules");
2022-02-27 02:21:02 -08:00
bool moduleFound = false;
2021-02-17 19:04:41 +08:00
// We now allow **encrypted** packets to pass through the modules
bool isDecoded = mp.which_payload_variant == meshtastic_MeshPacket_decoded_tag;
2021-02-17 19:04:41 +08:00
2021-03-05 11:44:45 +08:00
currentReply = NULL; // No reply yet
bool ignoreRequest = false; // No module asked to ignore the request yet
2021-02-17 19:04:41 +08:00
// Was this message directed to us specifically? Will be false if we are sniffing someone elses packets
auto ourNodeNum = nodeDB->getNodeNum();
bool toUs = isBroadcast(mp.to) || isToUs(&mp);
2022-02-27 01:49:24 -08:00
for (auto i = modules->begin(); i != modules->end(); ++i) {
auto &pi = **i;
2020-12-13 12:57:37 +08:00
pi.currentRequest = &mp;
2021-02-17 19:04:41 +08:00
/// We only call modules that are interested in the packet (and the message is destined to us or we are promiscious)
bool wantsPacket = (isDecoded || pi.encryptedOk) && (pi.isPromiscuous || toUs) && pi.wantPacket(&mp);
2021-03-23 12:07:04 +08:00
if ((src == RX_SRC_LOCAL) && !(pi.loopbackOk)) {
// new case, monitor separately for now, then FIXME merge above
wantsPacket = false;
}
assert(!pi.myReply); // If it is !null it means we have a bug, because it should have been sent the previous time
2021-03-23 12:07:04 +08:00
if (wantsPacket) {
LOG_DEBUG("Module '%s' wantsPacket=%d", pi.name, wantsPacket);
2022-02-27 02:21:02 -08:00
moduleFound = true;
2020-12-13 15:59:26 +08:00
/// received channel (or NULL if not decoded)
meshtastic_Channel *ch = isDecoded ? &channels.getByIndex(mp.channel) : NULL;
2021-03-23 12:07:04 +08:00
/// Is the channel this packet arrived on acceptable? (security check)
/// Note: we can't know channel names for encrypted packets, so those are NEVER sent to boundChannel modules
2023-01-21 14:34:29 +01:00
/// Also: if a packet comes in on the local PC interface, we don't check for bound channels, because it is TRUSTED and
/// it needs to to be able to fetch the initial admin packets without yet knowing any channels.
bool rxChannelOk = !pi.boundChannel || (mp.from == 0) || (ch && strcasecmp(ch->settings.name, pi.boundChannel) == 0);
2021-03-23 12:07:04 +08:00
if (!rxChannelOk) {
// no one should have already replied!
assert(!currentReply);
2021-02-26 20:10:41 +08:00
if (isDecoded && mp.decoded.want_response) {
printPacket("packet on wrong channel, returning error", &mp);
currentReply = pi.allocErrorResponse(meshtastic_Routing_Error_NOT_AUTHORIZED, &mp);
2021-03-23 12:07:04 +08:00
} else
printPacket("packet on wrong channel, but can't respond", &mp);
2021-03-05 11:44:45 +08:00
} else {
ProcessMessage handled = pi.handleReceived(mp);
2021-03-23 12:07:04 +08:00
pi.alterReceived(mp);
2021-03-23 12:07:04 +08:00
// Possibly send replies (but only if the message was directed to us specifically, i.e. not for promiscious
// sniffing) also: we only let the one module send a reply, once that happens, remaining modules are not
2021-03-23 12:07:04 +08:00
// considered
// NOTE: we send a reply *even if the (non broadcast) request was from us* which is unfortunate but necessary
// because currently when the phone sends things, it sends things using the local node ID as the from address. A
// better solution (FIXME) would be to let phones have their own distinct addresses and we 'route' to them like
// any other node.
if (isDecoded && mp.decoded.want_response && toUs && (!isFromUs(&mp) || isToUs(&mp)) && !currentReply) {
2021-03-23 12:07:04 +08:00
pi.sendResponse(mp);
ignoreRequest = ignoreRequest || pi.ignoreRequest; // If at least one module asks it, we may ignore a request
LOG_INFO("Asked module '%s' to send a response", pi.name);
2021-03-23 12:07:04 +08:00
} else {
LOG_DEBUG("Module '%s' considered", pi.name);
2021-03-23 12:07:04 +08:00
}
// If the requester didn't ask for a response we might need to discard unused replies to prevent memory leaks
if (pi.myReply) {
LOG_DEBUG("Discard an unneeded response");
packetPool.release(pi.myReply);
pi.myReply = NULL;
}
if (handled == ProcessMessage::STOP) {
LOG_DEBUG("Module '%s' handled and skipped other processing", pi.name);
2021-03-23 12:07:04 +08:00
break;
}
2021-02-17 19:04:41 +08:00
}
}
2021-03-05 11:44:45 +08:00
2020-12-13 12:57:37 +08:00
pi.currentRequest = NULL;
}
2020-12-13 15:59:26 +08:00
if (isDecoded && mp.decoded.want_response && toUs) {
2021-03-12 14:10:36 +08:00
if (currentReply) {
printPacket("Send response", currentReply);
service->sendToMesh(currentReply);
2021-03-12 14:10:36 +08:00
currentReply = NULL;
} else if (mp.from != ourNodeNum && !ignoreRequest) {
// Note: if the message started with the local node or a module asked to ignore the request, we don't want to send a
// no response reply
2021-05-03 10:53:06 +08:00
// No one wanted to reply to this request, tell the requster that happened
LOG_DEBUG("No one responded, send a nak");
2021-04-05 08:56:11 +08:00
// SECURITY NOTE! I considered sending back a different error code if we didn't find the psk (i.e. !isDecoded)
// but opted NOT TO. Because it is not a good idea to let remote nodes 'probe' to find out which PSKs were "good" vs
// bad.
routingModule->sendAckNak(meshtastic_Routing_Error_NO_RESPONSE, getFrom(&mp), mp.id, mp.channel,
routingModule->getHopLimitForResponse(mp.hop_start, mp.hop_limit));
2021-03-12 14:10:36 +08:00
}
2021-03-05 11:44:45 +08:00
}
if (!moduleFound && isDecoded) {
LOG_DEBUG("No modules interested in portnum=%d, src=%s", mp.decoded.portnum, (src == RX_SRC_LOCAL) ? "LOCAL" : "REMOTE");
}
2020-12-07 10:18:11 +08:00
}
meshtastic_MeshPacket *MeshModule::allocReply()
{
auto r = myReply;
myReply = NULL; // Only use each reply once
return r;
}
2020-12-07 10:18:11 +08:00
/** Messages can be received that have the want_response bit set. If set, this callback will be invoked
* so that subclasses can (optionally) send a response back to the original sender. Implementing this method
* is optional
*/
void MeshModule::sendResponse(const meshtastic_MeshPacket &req)
2021-03-05 11:44:45 +08:00
{
2020-12-07 10:18:11 +08:00
auto r = allocReply();
2021-03-05 11:44:45 +08:00
if (r) {
2020-12-07 10:18:11 +08:00
setReplyTo(r, req);
currentReply = r;
2021-03-05 11:44:45 +08:00
} else {
// Ignore - this is now expected behavior for routing module (because it ignores some replies)
// LOG_WARN("Client requested response but this module did not provide");
2020-12-07 10:18:11 +08:00
}
}
2021-03-05 11:44:45 +08:00
/** set the destination and packet parameters of packet p intended as a reply to a particular "to" packet
2020-12-07 10:18:11 +08:00
* This ensures that if the request packet was sent reliably, the reply is sent that way as well.
2021-03-05 11:44:45 +08:00
*/
void setReplyTo(meshtastic_MeshPacket *p, const meshtastic_MeshPacket &to)
2021-03-05 11:44:45 +08:00
{
assert(p->which_payload_variant == meshtastic_MeshPacket_decoded_tag); // Should already be set by now
p->to = getFrom(&to); // Make sure that if we are sending to the local node, we use our local node addr, not 0
p->channel = to.channel; // Use the same channel that the request came in on
p->hop_limit = routingModule->getHopLimitForResponse(to.hop_start, to.hop_limit);
// No need for an ack if we are just delivering locally (it just generates an ignored ack)
p->want_ack = (to.from != 0) ? to.want_ack : false;
if (p->priority == meshtastic_MeshPacket_Priority_UNSET)
p->priority = meshtastic_MeshPacket_Priority_RELIABLE;
2021-02-26 20:36:22 +08:00
p->decoded.request_id = to.id;
}
std::vector<MeshModule *> MeshModule::GetMeshModulesWithUIFrames(int startIndex)
2021-03-05 11:44:45 +08:00
{
std::vector<MeshModule *> modulesWithUIFrames;
// Fill with nullptr up to startIndex
modulesWithUIFrames.resize(startIndex, nullptr);
2022-02-27 01:49:24 -08:00
if (modules) {
for (auto i = modules->begin(); i != modules->end(); ++i) {
auto &pi = **i;
if (pi.wantUIFrame()) {
LOG_DEBUG("%s wants a UI Frame", pi.name);
2022-02-27 02:21:02 -08:00
modulesWithUIFrames.push_back(&pi);
}
}
}
2022-02-27 02:21:02 -08:00
return modulesWithUIFrames;
}
2022-01-13 09:19:36 +01:00
2023-01-21 14:34:29 +01:00
void MeshModule::observeUIEvents(Observer<const UIFrameEvent *> *observer)
2022-01-13 09:19:36 +01:00
{
2022-02-27 01:49:24 -08:00
if (modules) {
for (auto i = modules->begin(); i != modules->end(); ++i) {
auto &pi = **i;
2023-01-21 14:34:29 +01:00
Observable<const UIFrameEvent *> *observable = pi.getUIFrameObservable();
if (observable != NULL) {
LOG_DEBUG("%s wants a UI Frame", pi.name);
observer->observe(observable);
}
}
}
}
AdminMessageHandleResult MeshModule::handleAdminMessageForAllModules(const meshtastic_MeshPacket &mp,
2023-01-21 18:39:58 +01:00
meshtastic_AdminMessage *request,
meshtastic_AdminMessage *response)
{
AdminMessageHandleResult handled = AdminMessageHandleResult::NOT_HANDLED;
2022-02-27 01:49:24 -08:00
if (modules) {
for (auto i = modules->begin(); i != modules->end(); ++i) {
auto &pi = **i;
2022-02-27 02:21:02 -08:00
AdminMessageHandleResult h = pi.handleAdminMessageForModule(mp, request, response);
2023-01-21 14:34:29 +01:00
if (h == AdminMessageHandleResult::HANDLED_WITH_RESPONSE) {
// In case we have a response it always has priority.
LOG_DEBUG("Reply prepared by module '%s' of variant: %d", pi.name, response->which_payload_variant);
handled = h;
2023-01-21 14:34:29 +01:00
} else if ((handled != AdminMessageHandleResult::HANDLED_WITH_RESPONSE) && (h == AdminMessageHandleResult::HANDLED)) {
// In case the message is handled it should be populated, but will not overwrite
// a result with response.
handled = h;
}
2022-01-13 09:19:36 +01:00
}
}
return handled;
Show specific frame when updating screen (#4264) * Updated setFrames in Screen.cpp Added code to attempt to revert back to the same frame that user was on prior to setFrame reload. * Space added Screen.cpp * Update Screen.cpp Make screen to revert to Frame 0 if the originally displayed frame is no longer there. * Update Screen.cpp Inserted boolean holdPosition into setFrames to indicate the requirement to stay on the same frame ( if =true) or else it will switch to new frame . Only Screen::handleStatusUpdate calls with setFrame(true). ( For Node Updates) All other types of updates call as before setFrame(), so it will change focus as needed. * Hold position, even if number of frames increases * Hold position, if handling an outgoing text message * Update Screen.cpp * Reverted chnages related to devicestate.has_rx_text_message * Reset to master * CannedMessages only handles routing packets when waiting for ACK Previously, this was calling Screen::setFrames at unexpected times * Gather position info about screen frames while regenerating * Make admin module observable Notify only when relevant. Currently: only to handle remove_nodenum. * Optionally specify which frame to focus when setFrames runs * UIFrameEvent uses enum instead of multiple booleans * Allow modules to request their own frame to be focussed This is done internally by calling MeshModule::requestFocus() Easier this way, insteady of passing the info in the UIFrameEvent: * Modules don't always know whether they should be focussed until after the UIFrameEvent has been raised, in dramFrame * Don't have to pass reference to module instance as parameter though several methods * E-Ink screensaver uses FOCUS_PRESERVE Previously, it had its own basic implementation of this. * Spelling: regional variant * trunk * Fix HAS_SCREEN guarding * More HAS_SCREEN guarding --------- Co-authored-by: BIST <77391720+slash-bit@users.noreply.github.com> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> Co-authored-by: slash-bit <v-b2@live.com>
2024-07-12 11:51:26 +12:00
}
#if HAS_SCREEN
// Would our module like its frame to be focused after Screen::setFrames has regenerated the list of frames?
// Only considered if setFrames is triggered by a UIFrameEvent
bool MeshModule::isRequestingFocus()
{
if (_requestingFocus) {
_requestingFocus = false; // Consume the request
return true;
} else
return false;
}
#endif