+8



![github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>](/assets/img/avatar_default.png)





Tom Fifield
GitHub
Mike
Ben Meadors
Mike G
github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
thebentern
GUVWAF
Warren Guy
todd-herbert
geeksville
Jonathan Bennett
Alexander
Thomas Göttgens
quimnut
Manuel
Agent Blu, 006 <blu006@ucr.edu>
Mark Trevor Birss
d97e6b86b8
* Fix protobuf structs handling (#4140) * Fix protobuf structs handling * Log instead of assert --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * BLE based logging (#4146) * WIP log characteristic * Bluetooth logging plumbing * Characteristic * Callback * Check for nullptr * Esp32 bluetooth impl * Formatting * Add thread name and log level * Add settings guard * Remove comments * Field name * Fixes esp32 * Open it up * Whoops * Move va_end past our logic * Use `upload_protocol = esptool` as with the other heltec devices instead of `esp-builtin` (#4151) * Standardize lat/lon position logs (#4156) * Standardize lat/lon position logs * Missed sone and condensed logs * [create-pull-request] automated change (#4157) Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> * Pause BLE logging during want_config flow (#4162) * Update NimBLE to 1.4.2 (#4163) * Implement replies for all telemetry types based on variant tag (#4164) * Implement replies for all telemetry types based on variant tag * Remove check for `ignoreRequest`: modules can set this, don't need to check --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Esptool is better * Explicitly set characteristic * fix INA3221 sensor (#4168) - pass wire to begin() - remove redundant setAddr() (already set in header) * Show compass on waypoint frame; clear when waypoint deleted (#4116) * Clear expired or deleted waypoint frame * Return 0 to CallbackObserver * Add a missing comment * Draw compass for waypoint frame * Display our own waypoints * [create-pull-request] automated change (#4171) Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> * Add semihosting support for nrf52 devices (#4137) * Turn off vscode cmake prompt - we don't use cmake on meshtastic * Add rak4631_dap variant for debugging with NanoDAP debug probe device. * The rak device can also run freertos (which is underneath nrf52 arduino) * Add semihosting support for nrf52840 devices Initial platformio.ini file only supports rak4630 Default to non TCP for the semihosting log output for now... Fixes https://github.com/meshtastic/firmware/issues/4135 * fix my botched merge - keep board_level = extra flag for rak3631_dbg --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * [create-pull-request] automated change (#4174) Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> * Display alerts (#4170) * Move static functions into Screen.h, show compass during calibration * Move to _fontHeight macro to avoid collision * Move some alert functions to new alert handler * Catch missed reboot code * ESP32 fixes * Bump esp8266-oled-ssd1306 * Fixes for when a device has no screen * Use new startAlert(char*) helper class * Add EINK bits back to alert handling * Add noop class for no-display devices --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Send file system manifest up on want_config (#4176) * Send file system manifest up on want_config * Platform specific methods * Helps to actually make the change * Clear * tell vscode, if formatting, use whatever our trunk formatter wants (#4186) without this flag if the user has set some other formatter (clang) in their user level settings, it will be looking in the wrong directory for the clang options (we want the options in .trunk/clang) Note: formatOnSave is true in master, which means a bunch of our older files are non compliant and if you edit them it will generate lots of formatting related diffs. I guess I'll start letting that happen with my future commits ;-). * fix the build - would loop forever if there were no files to send (#4188) * Show owner.short_name on boot (and E-Ink sleep screen) (#4134) * Show owner.short_name on boot and sleep screen (on e-ink) * Update Screen.cpp - new line for short_name Boot screen short_name now below the region setting. Looks better on small screens. * Draw short_name on right --------- Co-authored-by: Thomas Göttgens <tgoettgens@gmail.com> Co-authored-by: todd-herbert <herbert.todd@gmail.com> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * nrf52 soft device will watchdog if you use ICE while BT on... (#4189) so have debugger disable bluetooth. * correct xiao_ble build preventing sx1262 init (#4191) * Force a compile time failur if FromRadio or ToRadio get larger than (#4190) a BLE packet size. We are actually very close to this threshold so important to make sure we don't accidentally pass it. * Clear vector after complete config state (#4194) * Clear after complete config * Don't collect . entries * Log file name and size * [create-pull-request] automated change (#4200) Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> * Make the logs Colorful! (#4199) * Squash needlessly static functions (#4183) * Trim extra vprintf and filter for unprintable characters * Deprecate Router Client role (and make it Client) (#4201) * [create-pull-request] automated change (#4205) Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> * Move waypoint (#4202) * Move waypoint screen draw into the waypoint module * Get the observer set up for the waypoint screen draw * Static squashing: screen dimensions Macros moved back to Screen.cpp, as a band-aid until we eventually move all those static functions into the Screen class. * Move getCompassDiam into Screen class (supress compiler warnings) At this stage, the method is still static, because it's used by drawNodeInfo, which has no tidy reference to our screen instance. This is probably just another band-aid until these static functions all move. * Use new getCompassDiam function in AccelerometerThread * Properly gate display code in WaypointModule --------- Co-authored-by: Todd Herbert <herbert.todd@gmail.com> * Fix flakey phone api transition from file manifest to complete (#4209) * Try fix flakey phone api transition from file manifest to complete * Skip * enable colors in platformio serial monitor (#4217) * When talking via serial, encapsulate log messages in protobufs if necessary (#4187) * clean up RedirectablePrint::log so it doesn't have three very different implementations inline. * remove NoopPrint - it is no longer needed * when talking to API clients via serial, don't turn off log msgs instead encapsuate them * fix the build - would loop forever if there were no files to send * don't use Segger code if not talking to a Segger debugger * when encapsulating logs, make sure the strings always has nul terminators * nrf52 soft device will watchdog if you use ICE while BT on... so have debugger disable bluetooth. * Important to not print debug messages while writing to the toPhone scratch buffer * don't include newlines if encapsulating log records as protobufs --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * [create-pull-request] automated change (#4218) Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> * Fix SHT41 support (#4222) * Add SHT41 Serial to I2c Detection Code On the Seeed Wio-WM1110 Dev Kit board, the SHT41 chip was being incorrectly detected as SHT31. This patch adds the necessary serial number for the SHT41 chip to be correctly detected. fixes meshtastic/firmware#4221 * Add missing sensor read for SHT41 * Typo fix in logs - mhz - MHz (#4225) As reported by karamo, a few different places in our logs had incorrect capitalization of MHz. fixes meshtastic/firmware#4126 * New new BLE logging characteristic with LogRecord protos (#4220) * New UUID * New log radio characteristic with LogRecord protobuf * LogRecord * Merge derp * How did you get there * Trunk * Fix length * Remove assert * minor cleanup proposal (#4169) * MESHTASTIC_EXCLUDE_WIFI and HAS_WIFI cleanup... Our code was checking HAS_WIFI and the new MESHTASTIC_EXCLUDE_WIFI flags in various places (even though EXCLUDE_WIFI forces HAS_WIFI to 0). Instead just check HAS_WIFI, only use EXCLUDE_WIFI inside configuration.h * cleanup: use HAS_NETWORKING instead of HAS_WIFI || HAS_ETHERNET We already had HAS_NETWORKING as flag in MQTT to mean 'we have tcpip'. Generallize that and move it into configuration.h so that we can use it elsewhere. * Use #pragma once, because supported by gcc and all modern compilers instead of #ifdef DOTHFILE_H etc... --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> * Add PowerMon support (#4155) * Turn off vscode cmake prompt - we don't use cmake on meshtastic * Add rak4631_dap variant for debugging with NanoDAP debug probe device. * The rak device can also run freertos (which is underneath nrf52 arduino) * Add semihosting support for nrf52840 devices Initial platformio.ini file only supports rak4630 Default to non TCP for the semihosting log output for now... Fixes https://github.com/meshtastic/firmware/issues/4135 * powermon WIP (for https://github.com/meshtastic/firmware/issues/4136 ) * oops - mean't to mark the _dbg variant as an 'extra' board. * powermon wip * Make serial port on wio-sdk-wm1110 board work By disabling the (inaccessible) adafruit USB * Instrument (radiolib only for now) lora for powermon per https://github.com/meshtastic/firmware/issues/4136 * powermon gps support https://github.com/meshtastic/firmware/issues/4136 * Add CPU deep and light sleep powermon states https://github.com/meshtastic/firmware/issues/4136 * Change the board/swversion bootstring so it is a new "structured" log msg. * powermon wip * add example script for getting esp S3 debugging working Not yet used but I didn't want these nasty tricks to get lost yet. * Add PowerMon reporting for screen and bluetooth pwr. * make power.powermon_enables config setting work. * update to latest protobufs * fix bogus shellcheck warning * make powermon optional (but default enabled because tiny and no runtime impact) * tell vscode, if formatting, use whatever our trunk formatter wants without this flag if the user has set some other formatter (clang) in their user level settings, it will be looking in the wrong directory for the clang options (we want the options in .trunk/clang) Note: formatOnSave is true in master, which means a bunch of our older files are non compliant and if you edit them it will generate lots of formatting related diffs. I guess I'll start letting that happen with my future commits ;-). * add PowerStress module * nrf52 arduino is built upon freertos, so let platformio debug it * don't accidentally try to Segger ICE if we are using another ICE * clean up RedirectablePrint::log so it doesn't have three very different implementations inline. * remove NoopPrint - it is no longer needed * when talking to API clients via serial, don't turn off log msgs instead encapsuate them * fix the build - would loop forever if there were no files to send * don't use Segger code if not talking to a Segger debugger * when encapsulating logs, make sure the strings always has nul terminators * nrf52 soft device will watchdog if you use ICE while BT on... so have debugger disable bluetooth. * Important to not print debug messages while writing to the toPhone scratch buffer * don't include newlines if encapsulating log records as protobufs * update to latest protobufs (needed for powermon goo) * PowerStress WIP * fix linter warning * Cleanup buffer * Merge hex for wm1110 target(s) * Only sdk * Sudo * Fix exclude macros (#4233) * fix MESHTASTIC_EXCLUDE_BLUETOOTH * fix HAS_SCREEN=0 * fix MESHTASTIC_EXCLUDE_GPS * fix typo in build-nrf52.sh (#4231) chmod is the command, '+x' is the argument. * Tidy Wireless Paper variant files (#4238) * Quick tidy of pins_arduino.h Matches requests made at https://github.com/meshtastic/firmware/pull/4226#discussion_r1664183480) * Tidy variant.h * Change deprecated ADC attenuation parameter From 11dB to 12dB. Resolves compiler warning. Allegly, no impact on function: `This is deprecated, it behaves the same as `ADC_ATTEN_DB_12` * Updated raspbian CI to update apt repository ahead of libbluetooth. (#4243) * Fix BLE logging on nrf52 (#4244) * allow ble logrecords to be fetched either by NOTIFY or INDICATE ble types This allows 'lossless' log reading. If client has requested INDICATE (rather than NOTIFY) each log record emitted via log() will have to fetched by the client device before the meshtastic node can continue. * Fix serious problem with nrf52 BLE logging. When doing notifies of LogRecords it is important to use the binary write routines - writing using the 'string' write won't work. Because protobufs can contain \0 nuls inside of them which if being parsed as a string will cause only a portion of the protobuf to be sent. I noticed this because some log messages were not getting through. --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Fix build when HAS_NETWORKING is false on nrf52 (#4237) (tested on a rak4631 by setting HAS_ETHERNET false when shrinking image) * If `toPhoneQueue` is full, still increment `fromNum` to avoid client never getting packets (#4246) * Update to SoftDevice 7.3.0 for wio-sdk-wm1110 and wio-tracker-wm1110 (#4248) * Update variant.h * Update wio-tracker-wm1110.json * Update wio-sdk-wm1110.json * Update platformio.ini * Update platformio.ini * Add files via upload * Add files via upload * Update variant.h --------- Co-authored-by: Mike <mikhael.skvortsov@gmail.com> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> Co-authored-by: Mike G <mkgin@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: thebentern <9000580+thebentern@users.noreply.github.com> Co-authored-by: GUVWAF <78759985+GUVWAF@users.noreply.github.com> Co-authored-by: Warren Guy <5602790+warrenguy@users.noreply.github.com> Co-authored-by: todd-herbert <herbert.todd@gmail.com> Co-authored-by: geeksville <kevinh@geeksville.com> Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Alexander <156134901+Dorn8010@users.noreply.github.com> Co-authored-by: Thomas Göttgens <tgoettgens@gmail.com> Co-authored-by: quimnut <github@dopegoat.com> Co-authored-by: Manuel <71137295+mverch67@users.noreply.github.com> Co-authored-by: Agent Blu, 006 <blu006@ucr.edu> Co-authored-by: Mark Trevor Birss <markbirss@gmail.com>
458 lines
20 KiB
C++
458 lines
20 KiB
C++
#if !MESHTASTIC_EXCLUDE_GPS
|
|
#include "PositionModule.h"
|
|
#include "Default.h"
|
|
#include "GPS.h"
|
|
#include "MeshService.h"
|
|
#include "NodeDB.h"
|
|
#include "RTC.h"
|
|
#include "Router.h"
|
|
#include "TypeConversions.h"
|
|
#include "airtime.h"
|
|
#include "configuration.h"
|
|
#include "gps/GeoCoord.h"
|
|
#include "main.h"
|
|
#include "meshtastic/atak.pb.h"
|
|
#include "sleep.h"
|
|
#include "target_specific.h"
|
|
|
|
extern "C" {
|
|
#include "mesh/compression/unishox2.h"
|
|
#include <Throttle.h>
|
|
}
|
|
|
|
PositionModule *positionModule;
|
|
|
|
PositionModule::PositionModule()
|
|
: ProtobufModule("position", meshtastic_PortNum_POSITION_APP, &meshtastic_Position_msg),
|
|
concurrency::OSThread("PositionModule")
|
|
{
|
|
precision = 0; // safe starting value
|
|
isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others
|
|
if (config.device.role != meshtastic_Config_DeviceConfig_Role_TRACKER &&
|
|
config.device.role != meshtastic_Config_DeviceConfig_Role_TAK_TRACKER)
|
|
setIntervalFromNow(60 * 1000);
|
|
|
|
// Power saving trackers should clear their position on startup to avoid waking up and sending a stale position
|
|
if ((config.device.role == meshtastic_Config_DeviceConfig_Role_TRACKER ||
|
|
config.device.role == meshtastic_Config_DeviceConfig_Role_TAK_TRACKER) &&
|
|
config.power.is_power_saving) {
|
|
LOG_DEBUG("Clearing position on startup for sleepy tracker (ー。ー) zzz\n");
|
|
nodeDB->clearLocalPosition();
|
|
}
|
|
}
|
|
|
|
bool PositionModule::handleReceivedProtobuf(const meshtastic_MeshPacket &mp, meshtastic_Position *pptr)
|
|
{
|
|
auto p = *pptr;
|
|
|
|
// If inbound message is a replay (or spoof!) of our own messages, we shouldn't process
|
|
// (why use second-hand sources for our own data?)
|
|
|
|
// FIXME this can in fact happen with packets sent from EUD (src=RX_SRC_USER)
|
|
// to set fixed location, EUD-GPS location or just the time (see also issue #900)
|
|
bool isLocal = false;
|
|
if (nodeDB->getNodeNum() == getFrom(&mp)) {
|
|
isLocal = true;
|
|
if (config.position.fixed_position) {
|
|
LOG_DEBUG("Ignore incoming position update from myself except for time, because position.fixed_position is true\n");
|
|
|
|
#ifdef T_WATCH_S3
|
|
// Since we return early if position.fixed_position is true, set the T-Watch's RTC to the time received from the
|
|
// client device here
|
|
if (p.time && channels.getByIndex(mp.channel).role == meshtastic_Channel_Role_PRIMARY) {
|
|
trySetRtc(p, isLocal, true);
|
|
}
|
|
#endif
|
|
|
|
nodeDB->setLocalPosition(p, true);
|
|
return false;
|
|
} else {
|
|
LOG_DEBUG("Incoming update from MYSELF\n");
|
|
nodeDB->setLocalPosition(p);
|
|
}
|
|
}
|
|
|
|
// Log packet size and data fields
|
|
LOG_DEBUG("POSITION node=%08x l=%d lat=%d lon=%d msl=%d hae=%d geo=%d pdop=%d hdop=%d vdop=%d siv=%d fxq=%d fxt=%d pts=%d "
|
|
"time=%d\n",
|
|
getFrom(&mp), mp.decoded.payload.size, p.latitude_i, p.longitude_i, p.altitude, p.altitude_hae,
|
|
p.altitude_geoidal_separation, p.PDOP, p.HDOP, p.VDOP, p.sats_in_view, p.fix_quality, p.fix_type, p.timestamp,
|
|
p.time);
|
|
|
|
if (p.time && channels.getByIndex(mp.channel).role == meshtastic_Channel_Role_PRIMARY) {
|
|
bool force = false;
|
|
|
|
#ifdef T_WATCH_S3
|
|
// The T-Watch appears to "pause" its RTC when shut down, such that the time it reads upon powering on is the same as when
|
|
// it was shut down. So we need to force the update here, since otherwise RTC::perhapsSetRTC will ignore it because it
|
|
// will always be an equivalent or lesser RTCQuality (RTCQualityNTP or RTCQualityNet).
|
|
force = true;
|
|
#endif
|
|
|
|
// Set from phone RTC Quality to RTCQualityNTP since it should be approximately so
|
|
trySetRtc(p, isLocal, force);
|
|
}
|
|
|
|
nodeDB->updatePosition(getFrom(&mp), p);
|
|
if (channels.getByIndex(mp.channel).settings.has_module_settings) {
|
|
precision = channels.getByIndex(mp.channel).settings.module_settings.position_precision;
|
|
} else if (channels.getByIndex(mp.channel).role == meshtastic_Channel_Role_PRIMARY) {
|
|
precision = 32;
|
|
} else {
|
|
precision = 0;
|
|
}
|
|
|
|
return false; // Let others look at this message also if they want
|
|
}
|
|
|
|
void PositionModule::alterReceivedProtobuf(meshtastic_MeshPacket &mp, meshtastic_Position *p)
|
|
{
|
|
// Phone position packets need to be truncated to the channel precision
|
|
if (nodeDB->getNodeNum() == getFrom(&mp) && (precision < 32 && precision > 0)) {
|
|
LOG_DEBUG("Truncating phone position to channel precision %i\n", precision);
|
|
p->latitude_i = p->latitude_i & (UINT32_MAX << (32 - precision));
|
|
p->longitude_i = p->longitude_i & (UINT32_MAX << (32 - precision));
|
|
|
|
// We want the imprecise position to be the middle of the possible location, not
|
|
p->latitude_i += (1 << (31 - precision));
|
|
p->longitude_i += (1 << (31 - precision));
|
|
|
|
mp.decoded.payload.size =
|
|
pb_encode_to_bytes(mp.decoded.payload.bytes, sizeof(mp.decoded.payload.bytes), &meshtastic_Position_msg, p);
|
|
}
|
|
}
|
|
|
|
void PositionModule::trySetRtc(meshtastic_Position p, bool isLocal, bool forceUpdate)
|
|
{
|
|
struct timeval tv;
|
|
uint32_t secs = p.time;
|
|
|
|
tv.tv_sec = secs;
|
|
tv.tv_usec = 0;
|
|
perhapsSetRTC(isLocal ? RTCQualityNTP : RTCQualityFromNet, &tv, forceUpdate);
|
|
}
|
|
|
|
meshtastic_MeshPacket *PositionModule::allocReply()
|
|
{
|
|
if (precision == 0) {
|
|
LOG_DEBUG("Skipping location send because precision is set to 0!\n");
|
|
return nullptr;
|
|
}
|
|
|
|
meshtastic_NodeInfoLite *node = service.refreshLocalMeshNode(); // should guarantee there is now a position
|
|
assert(node->has_position);
|
|
|
|
// configuration of POSITION packet
|
|
// consider making this a function argument?
|
|
uint32_t pos_flags = config.position.position_flags;
|
|
|
|
// Populate a Position struct with ONLY the requested fields
|
|
meshtastic_Position p = meshtastic_Position_init_default; // Start with an empty structure
|
|
// if localPosition is totally empty, put our last saved position (lite) in there
|
|
if (localPosition.latitude_i == 0 && localPosition.longitude_i == 0) {
|
|
nodeDB->setLocalPosition(TypeConversions::ConvertToPosition(node->position));
|
|
}
|
|
localPosition.seq_number++;
|
|
|
|
if (localPosition.latitude_i == 0 && localPosition.longitude_i == 0) {
|
|
LOG_WARN("Skipping position send because lat/lon are zero!\n");
|
|
return nullptr;
|
|
}
|
|
|
|
// lat/lon are unconditionally included - IF AVAILABLE!
|
|
LOG_DEBUG("Sending location with precision %i\n", precision);
|
|
if (precision < 32 && precision > 0) {
|
|
p.latitude_i = localPosition.latitude_i & (UINT32_MAX << (32 - precision));
|
|
p.longitude_i = localPosition.longitude_i & (UINT32_MAX << (32 - precision));
|
|
|
|
// We want the imprecise position to be the middle of the possible location, not
|
|
p.latitude_i += (1 << (31 - precision));
|
|
p.longitude_i += (1 << (31 - precision));
|
|
} else {
|
|
p.latitude_i = localPosition.latitude_i;
|
|
p.longitude_i = localPosition.longitude_i;
|
|
}
|
|
p.precision_bits = precision;
|
|
p.time = localPosition.time;
|
|
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_ALTITUDE) {
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_ALTITUDE_MSL)
|
|
p.altitude = localPosition.altitude;
|
|
else
|
|
p.altitude_hae = localPosition.altitude_hae;
|
|
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_GEOIDAL_SEPARATION)
|
|
p.altitude_geoidal_separation = localPosition.altitude_geoidal_separation;
|
|
}
|
|
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_DOP) {
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_HVDOP) {
|
|
p.HDOP = localPosition.HDOP;
|
|
p.VDOP = localPosition.VDOP;
|
|
} else
|
|
p.PDOP = localPosition.PDOP;
|
|
}
|
|
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_SATINVIEW)
|
|
p.sats_in_view = localPosition.sats_in_view;
|
|
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_TIMESTAMP)
|
|
p.timestamp = localPosition.timestamp;
|
|
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_SEQ_NO)
|
|
p.seq_number = localPosition.seq_number;
|
|
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_HEADING)
|
|
p.ground_track = localPosition.ground_track;
|
|
|
|
if (pos_flags & meshtastic_Config_PositionConfig_PositionFlags_SPEED)
|
|
p.ground_speed = localPosition.ground_speed;
|
|
|
|
// Strip out any time information before sending packets to other nodes - to keep the wire size small (and because other
|
|
// nodes shouldn't trust it anyways) Note: we allow a device with a local GPS or NTP to include the time, so that devices
|
|
// without can get time.
|
|
if (getRTCQuality() < RTCQualityNTP) {
|
|
LOG_INFO("Stripping time %u from position send\n", p.time);
|
|
p.time = 0;
|
|
} else {
|
|
p.time = getValidTime(RTCQualityNTP);
|
|
LOG_INFO("Providing time to mesh %u\n", p.time);
|
|
}
|
|
|
|
LOG_INFO("Position reply: time=%i lat=%i lon=%i\n", p.time, p.latitude_i, p.longitude_i);
|
|
|
|
// TAK Tracker devices should send their position in a TAK packet over the ATAK port
|
|
if (config.device.role == meshtastic_Config_DeviceConfig_Role_TAK_TRACKER)
|
|
return allocAtakPli();
|
|
|
|
return allocDataProtobuf(p);
|
|
}
|
|
|
|
meshtastic_MeshPacket *PositionModule::allocAtakPli()
|
|
{
|
|
LOG_INFO("Sending TAK PLI packet\n");
|
|
meshtastic_MeshPacket *mp = allocDataPacket();
|
|
mp->decoded.portnum = meshtastic_PortNum_ATAK_PLUGIN;
|
|
|
|
meshtastic_TAKPacket takPacket = {.is_compressed = true,
|
|
.has_contact = true,
|
|
.contact = {0},
|
|
.has_group = true,
|
|
.group = {meshtastic_MemberRole_TeamMember, meshtastic_Team_Cyan},
|
|
.has_status = true,
|
|
.status =
|
|
{
|
|
.battery = powerStatus->getBatteryChargePercent(),
|
|
},
|
|
.which_payload_variant = meshtastic_TAKPacket_pli_tag,
|
|
{.pli = {
|
|
.latitude_i = localPosition.latitude_i,
|
|
.longitude_i = localPosition.longitude_i,
|
|
.altitude = localPosition.altitude_hae,
|
|
.speed = localPosition.ground_speed,
|
|
.course = static_cast<uint16_t>(localPosition.ground_track),
|
|
}}};
|
|
|
|
auto length = unishox2_compress_simple(owner.long_name, strlen(owner.long_name), takPacket.contact.device_callsign);
|
|
LOG_DEBUG("Uncompressed device_callsign '%s' - %d bytes\n", owner.long_name, strlen(owner.long_name));
|
|
LOG_DEBUG("Compressed device_callsign '%s' - %d bytes\n", takPacket.contact.device_callsign, length);
|
|
length = unishox2_compress_simple(owner.long_name, strlen(owner.long_name), takPacket.contact.callsign);
|
|
mp->decoded.payload.size =
|
|
pb_encode_to_bytes(mp->decoded.payload.bytes, sizeof(mp->decoded.payload.bytes), &meshtastic_TAKPacket_msg, &takPacket);
|
|
return mp;
|
|
}
|
|
|
|
void PositionModule::sendOurPosition()
|
|
{
|
|
bool requestReplies = currentGeneration != radioGeneration;
|
|
currentGeneration = radioGeneration;
|
|
|
|
// If we changed channels, ask everyone else for their latest info
|
|
LOG_INFO("Sending pos@%x:6 to mesh (wantReplies=%d)\n", localPosition.timestamp, requestReplies);
|
|
sendOurPosition(NODENUM_BROADCAST, requestReplies);
|
|
}
|
|
|
|
void PositionModule::sendOurPosition(NodeNum dest, bool wantReplies, uint8_t channel)
|
|
{
|
|
// cancel any not yet sent (now stale) position packets
|
|
if (prevPacketId) // if we wrap around to zero, we'll simply fail to cancel in that rare case (no big deal)
|
|
service.cancelSending(prevPacketId);
|
|
|
|
// Set's the class precision value for this particular packet
|
|
if (channels.getByIndex(channel).settings.has_module_settings) {
|
|
precision = channels.getByIndex(channel).settings.module_settings.position_precision;
|
|
} else if (channels.getByIndex(channel).role == meshtastic_Channel_Role_PRIMARY) {
|
|
precision = 32;
|
|
} else {
|
|
precision = 0;
|
|
}
|
|
|
|
meshtastic_MeshPacket *p = allocReply();
|
|
if (p == nullptr) {
|
|
LOG_DEBUG("allocReply returned a nullptr\n");
|
|
return;
|
|
}
|
|
|
|
p->to = dest;
|
|
p->decoded.want_response = config.device.role == meshtastic_Config_DeviceConfig_Role_TRACKER ? false : wantReplies;
|
|
if (config.device.role == meshtastic_Config_DeviceConfig_Role_TRACKER ||
|
|
config.device.role == meshtastic_Config_DeviceConfig_Role_TAK_TRACKER)
|
|
p->priority = meshtastic_MeshPacket_Priority_RELIABLE;
|
|
else
|
|
p->priority = meshtastic_MeshPacket_Priority_BACKGROUND;
|
|
prevPacketId = p->id;
|
|
|
|
if (channel > 0)
|
|
p->channel = channel;
|
|
|
|
service.sendToMesh(p, RX_SRC_LOCAL, true);
|
|
|
|
if ((config.device.role == meshtastic_Config_DeviceConfig_Role_TRACKER ||
|
|
config.device.role == meshtastic_Config_DeviceConfig_Role_TAK_TRACKER) &&
|
|
config.power.is_power_saving) {
|
|
LOG_DEBUG("Starting next execution in 5 seconds and then going to sleep.\n");
|
|
sleepOnNextExecution = true;
|
|
setIntervalFromNow(5000);
|
|
}
|
|
}
|
|
|
|
#define RUNONCE_INTERVAL 5000;
|
|
|
|
int32_t PositionModule::runOnce()
|
|
{
|
|
if (sleepOnNextExecution == true) {
|
|
sleepOnNextExecution = false;
|
|
uint32_t nightyNightMs = Default::getConfiguredOrDefaultMs(config.position.position_broadcast_secs);
|
|
LOG_DEBUG("Sleeping for %ims, then awaking to send position again.\n", nightyNightMs);
|
|
doDeepSleep(nightyNightMs, false);
|
|
}
|
|
|
|
meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeDB->getNodeNum());
|
|
if (node == nullptr)
|
|
return RUNONCE_INTERVAL;
|
|
|
|
// We limit our GPS broadcasts to a max rate
|
|
uint32_t now = millis();
|
|
uint32_t intervalMs =
|
|
Default::getConfiguredOrDefaultMs(config.position.position_broadcast_secs, default_broadcast_interval_secs);
|
|
uint32_t msSinceLastSend = now - lastGpsSend;
|
|
// Only send packets if the channel util. is less than 25% utilized or we're a tracker with less than 40% utilized.
|
|
if (!airTime->isTxAllowedChannelUtil(config.device.role != meshtastic_Config_DeviceConfig_Role_TRACKER &&
|
|
config.device.role != meshtastic_Config_DeviceConfig_Role_TAK_TRACKER)) {
|
|
return RUNONCE_INTERVAL;
|
|
}
|
|
|
|
if (lastGpsSend == 0 || msSinceLastSend >= intervalMs) {
|
|
if (hasValidPosition(node)) {
|
|
lastGpsSend = now;
|
|
|
|
lastGpsLatitude = node->position.latitude_i;
|
|
lastGpsLongitude = node->position.longitude_i;
|
|
|
|
sendOurPosition();
|
|
if (config.device.role == meshtastic_Config_DeviceConfig_Role_LOST_AND_FOUND) {
|
|
sendLostAndFoundText();
|
|
}
|
|
}
|
|
} else if (config.position.position_broadcast_smart_enabled) {
|
|
const meshtastic_NodeInfoLite *node2 = service.refreshLocalMeshNode(); // should guarantee there is now a position
|
|
|
|
if (hasValidPosition(node2)) {
|
|
// The minimum time (in seconds) that would pass before we are able to send a new position packet.
|
|
|
|
auto smartPosition = getDistanceTraveledSinceLastSend(node->position);
|
|
msSinceLastSend = now - lastGpsSend;
|
|
|
|
if (smartPosition.hasTraveledOverThreshold &&
|
|
Throttle::execute(
|
|
&lastGpsSend, minimumTimeThreshold, []() { positionModule->sendOurPosition(); },
|
|
[]() { LOG_DEBUG("Skipping send smart broadcast due to time throttling\n"); })) {
|
|
|
|
LOG_DEBUG("Sent smart pos@%x:6 to mesh (distanceTraveled=%fm, minDistanceThreshold=%im, timeElapsed=%ims, "
|
|
"minTimeInterval=%ims)\n",
|
|
localPosition.timestamp, smartPosition.distanceTraveled, smartPosition.distanceThreshold,
|
|
msSinceLastSend, minimumTimeThreshold);
|
|
|
|
// Set the current coords as our last ones, after we've compared distance with current and decided to send
|
|
lastGpsLatitude = node->position.latitude_i;
|
|
lastGpsLongitude = node->position.longitude_i;
|
|
}
|
|
}
|
|
}
|
|
|
|
return RUNONCE_INTERVAL; // to save power only wake for our callback occasionally
|
|
}
|
|
|
|
void PositionModule::sendLostAndFoundText()
|
|
{
|
|
meshtastic_MeshPacket *p = allocDataPacket();
|
|
p->to = NODENUM_BROADCAST;
|
|
char *message = new char[60];
|
|
sprintf(message, "🚨I'm lost! Lat / Lon: %f, %f\a", (lastGpsLatitude * 1e-7), (lastGpsLongitude * 1e-7));
|
|
p->decoded.portnum = meshtastic_PortNum_TEXT_MESSAGE_APP;
|
|
p->want_ack = false;
|
|
p->decoded.payload.size = strlen(message);
|
|
memcpy(p->decoded.payload.bytes, message, p->decoded.payload.size);
|
|
|
|
service.sendToMesh(p, RX_SRC_LOCAL, true);
|
|
delete[] message;
|
|
}
|
|
|
|
struct SmartPosition PositionModule::getDistanceTraveledSinceLastSend(meshtastic_PositionLite currentPosition)
|
|
{
|
|
// The minimum distance to travel before we are able to send a new position packet.
|
|
const uint32_t distanceTravelThreshold =
|
|
Default::getConfiguredOrDefault(config.position.broadcast_smart_minimum_distance, 100);
|
|
|
|
// Determine the distance in meters between two points on the globe
|
|
float distanceTraveledSinceLastSend = GeoCoord::latLongToMeter(
|
|
lastGpsLatitude * 1e-7, lastGpsLongitude * 1e-7, currentPosition.latitude_i * 1e-7, currentPosition.longitude_i * 1e-7);
|
|
|
|
#ifdef GPS_EXTRAVERBOSE
|
|
LOG_DEBUG("--------LAST POSITION------------------------------------\n");
|
|
LOG_DEBUG("lastGpsLatitude=%i, lastGpsLatitude=%i\n", lastGpsLatitude, lastGpsLongitude);
|
|
|
|
LOG_DEBUG("--------CURRENT POSITION---------------------------------\n");
|
|
LOG_DEBUG("currentPosition.latitude_i=%i, currentPosition.longitude_i=%i\n", lastGpsLatitude, lastGpsLongitude);
|
|
|
|
LOG_DEBUG("--------SMART POSITION-----------------------------------\n");
|
|
LOG_DEBUG("hasTraveledOverThreshold=%i, distanceTraveled=%f, distanceThreshold=%f\n",
|
|
abs(distanceTraveledSinceLastSend) >= distanceTravelThreshold, abs(distanceTraveledSinceLastSend),
|
|
distanceTravelThreshold);
|
|
|
|
if (abs(distanceTraveledSinceLastSend) >= distanceTravelThreshold) {
|
|
LOG_DEBUG("\n\n\nSMART SEEEEEEEEENDING\n\n\n");
|
|
}
|
|
#endif
|
|
|
|
return SmartPosition{.distanceTraveled = abs(distanceTraveledSinceLastSend),
|
|
.distanceThreshold = distanceTravelThreshold,
|
|
.hasTraveledOverThreshold = abs(distanceTraveledSinceLastSend) >= distanceTravelThreshold};
|
|
}
|
|
|
|
void PositionModule::handleNewPosition()
|
|
{
|
|
meshtastic_NodeInfoLite *node = nodeDB->getMeshNode(nodeDB->getNodeNum());
|
|
const meshtastic_NodeInfoLite *node2 = service.refreshLocalMeshNode(); // should guarantee there is now a position
|
|
// We limit our GPS broadcasts to a max rate
|
|
if (hasValidPosition(node2)) {
|
|
auto smartPosition = getDistanceTraveledSinceLastSend(node->position);
|
|
uint32_t msSinceLastSend = millis() - lastGpsSend;
|
|
if (smartPosition.hasTraveledOverThreshold &&
|
|
Throttle::execute(
|
|
&lastGpsSend, minimumTimeThreshold, []() { positionModule->sendOurPosition(); },
|
|
[]() { LOG_DEBUG("Skipping send smart broadcast due to time throttling\n"); })) {
|
|
LOG_DEBUG("Sent smart pos@%x:6 to mesh (distanceTraveled=%fm, minDistanceThreshold=%im, timeElapsed=%ims, "
|
|
"minTimeInterval=%ims)\n",
|
|
localPosition.timestamp, smartPosition.distanceTraveled, smartPosition.distanceThreshold, msSinceLastSend,
|
|
minimumTimeThreshold);
|
|
|
|
// Set the current coords as our last ones, after we've compared distance with current and decided to send
|
|
lastGpsLatitude = node->position.latitude_i;
|
|
lastGpsLongitude = node->position.longitude_i;
|
|
}
|
|
}
|
|
}
|
|
|
|
#endif
|