trunk roundhouse kick

This commit is contained in:
Thomas Göttgens
2023-01-21 14:34:29 +01:00
parent 6cf18b7d07
commit 51b2c431d9
234 changed files with 4989 additions and 5101 deletions

View File

@@ -3,8 +3,7 @@
#include "ProtobufModule.h"
#include "input/InputBroker.h"
enum cannedMessageModuleRunState
{
enum cannedMessageModuleRunState {
CANNED_MESSAGE_RUN_STATE_DISABLED,
CANNED_MESSAGE_RUN_STATE_INACTIVE,
CANNED_MESSAGE_RUN_STATE_ACTIVE,
@@ -15,27 +14,23 @@ enum cannedMessageModuleRunState
CANNED_MESSAGE_RUN_STATE_ACTION_DOWN,
};
#define CANNED_MESSAGE_MODULE_MESSAGE_MAX_COUNT 50
/**
* Sum of CannedMessageModuleConfig part sizes.
*/
#define CANNED_MESSAGE_MODULE_MESSAGES_SIZE 800
class CannedMessageModule :
public SinglePortModule,
public Observable<const UIFrameEvent *>,
private concurrency::OSThread
class CannedMessageModule : public SinglePortModule, public Observable<const UIFrameEvent *>, private concurrency::OSThread
{
CallbackObserver<CannedMessageModule, const InputEvent *> inputObserver =
CallbackObserver<CannedMessageModule, const InputEvent *>(
this, &CannedMessageModule::handleInputEvent);
CallbackObserver<CannedMessageModule, const InputEvent *>(this, &CannedMessageModule::handleInputEvent);
public:
CannedMessageModule();
const char* getCurrentMessage();
const char* getPrevMessage();
const char* getNextMessage();
const char* getNodeName(NodeNum node);
const char *getCurrentMessage();
const char *getPrevMessage();
const char *getNextMessage();
const char *getNodeName(NodeNum node);
bool shouldDraw();
void eventUp();
void eventDown();
@@ -47,13 +42,9 @@ class CannedMessageModule :
String drawWithCursor(String text, int cursor);
protected:
virtual int32_t runOnce() override;
void sendText(
NodeNum dest,
const char* message,
bool wantReplies);
void sendText(NodeNum dest, const char *message, bool wantReplies);
int splitConfiguredMessages();
int getNextIndex();
@@ -61,11 +52,10 @@ class CannedMessageModule :
int handleInputEvent(const InputEvent *event);
virtual bool wantUIFrame() override { return this->shouldDraw(); }
virtual Observable<const UIFrameEvent *>* getUIFrameObservable() override { return this; }
virtual void drawFrame(
OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override;
virtual AdminMessageHandleResult handleAdminMessageForModule(
const MeshPacket &mp, AdminMessage *request, AdminMessage *response) override;
virtual Observable<const UIFrameEvent *> *getUIFrameObservable() override { return this; }
virtual void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override;
virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request,
AdminMessage *response) override;
void loadProtoForModule();
bool saveProtoForModule();
@@ -76,11 +66,11 @@ class CannedMessageModule :
cannedMessageModuleRunState runState = CANNED_MESSAGE_RUN_STATE_INACTIVE;
char payload = 0x00;
unsigned int cursor = 0;
String freetext = ""; // Text Buffer for Freetext Editor
String freetext = ""; // Text Buffer for Freetext Editor
bool destSelect = false; // Freetext Editor Mode
NodeNum dest = NODENUM_BROADCAST;
char messageStore[CANNED_MESSAGE_MODULE_MESSAGES_SIZE+1];
char messageStore[CANNED_MESSAGE_MODULE_MESSAGES_SIZE + 1];
char *messages[CANNED_MESSAGE_MODULE_MESSAGE_MAX_COUNT];
int messagesCount = 0;
unsigned long lastTouchMillis = 0;

View File

@@ -7,13 +7,13 @@
#include <NonBlockingRtttl.h>
#else
// Noop class for portduino.
class rtttl
class rtttl
{
public:
explicit rtttl() {}
static bool isPlaying() { return false; }
static void play() {}
static void begin(byte a, const char * b) {};
static void begin(byte a, const char *b){};
static void stop() {}
static bool done() { return true; }
};
@@ -27,7 +27,7 @@ class rtttl
*/
class ExternalNotificationModule : public SinglePortModule, private concurrency::OSThread
{
uint32_t output = 0;
uint32_t output = 0;
public:
ExternalNotificationModule();
@@ -45,7 +45,8 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency:
protected:
/** Called to handle a particular incoming message
@return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it
@return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for
it
*/
virtual ProcessMessage handleReceived(const MeshPacket &mp) override;
@@ -53,7 +54,8 @@ class ExternalNotificationModule : public SinglePortModule, private concurrency:
bool isNagging = false;
virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request, AdminMessage *response) override;
virtual AdminMessageHandleResult handleAdminMessageForModule(const MeshPacket &mp, AdminMessage *request,
AdminMessage *response) override;
};
extern ExternalNotificationModule *externalNotificationModule;

View File

@@ -18,9 +18,9 @@
#include "modules/Telemetry/EnvironmentTelemetry.h"
#endif
#ifdef ARCH_ESP32
#include "modules/esp32/AudioModule.h"
#include "modules/esp32/RangeTestModule.h"
#include "modules/esp32/StoreForwardModule.h"
#include "modules/esp32/AudioModule.h"
#endif
#if defined(ARCH_ESP32) || defined(ARCH_NRF52)
#include "modules/ExternalNotificationModule.h"
@@ -42,7 +42,7 @@ void setupModules()
waypointModule = new WaypointModule();
textMessageModule = new TextMessageModule();
traceRouteModule = new TraceRouteModule();
// Note: if the rest of meshtastic doesn't need to explicitly use your module, you do not need to assign the instance
// to a global variable.

View File

@@ -54,7 +54,8 @@ NodeInfoModule::NodeInfoModule()
: ProtobufModule("nodeinfo", PortNum_NODEINFO_APP, &User_msg), concurrency::OSThread("NodeInfoModule")
{
isPromiscuous = true; // We always want to update our nodedb, even if we are sniffing on others
setIntervalFromNow(30 * 1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup)
setIntervalFromNow(30 *
1000); // Send our initial owner announcement 30 seconds after we start (to give network time to setup)
}
int32_t NodeInfoModule::runOnce()

View File

@@ -8,14 +8,15 @@ class NodeInfoModule : public ProtobufModule<User>, private concurrency::OSThrea
{
/// The id of the last packet we sent, to allow us to cancel it if we make something fresher
PacketId prevPacketId = 0;
uint32_t currentGeneration = 0;
public:
/** Constructor
* name is for debugging output
*/
NodeInfoModule();
/**
* Send our NodeInfo into the mesh
*/

View File

@@ -33,10 +33,10 @@ bool PositionModule::handleReceivedProtobuf(const MeshPacket &mp, Position *pptr
// Log packet size and list of fields
LOG_INFO("POSITION node=%08x l=%d %s%s%s%s%s%s%s%s%s%s%s%s%s\n", getFrom(&mp), mp.decoded.payload.size,
p.latitude_i ? "LAT " : "", p.longitude_i ? "LON " : "", p.altitude ? "MSL " : "", p.altitude_hae ? "HAE " : "",
p.altitude_geoidal_separation ? "GEO " : "", p.PDOP ? "PDOP " : "", p.HDOP ? "HDOP " : "", p.VDOP ? "VDOP " : "",
p.sats_in_view ? "SIV " : "", p.fix_quality ? "FXQ " : "", p.fix_type ? "FXT " : "", p.timestamp ? "PTS " : "",
p.time ? "TIME " : "");
p.latitude_i ? "LAT " : "", p.longitude_i ? "LON " : "", p.altitude ? "MSL " : "", p.altitude_hae ? "HAE " : "",
p.altitude_geoidal_separation ? "GEO " : "", p.PDOP ? "PDOP " : "", p.HDOP ? "HDOP " : "", p.VDOP ? "VDOP " : "",
p.sats_in_view ? "SIV " : "", p.fix_quality ? "FXQ " : "", p.fix_type ? "FXT " : "", p.timestamp ? "PTS " : "",
p.time ? "TIME " : "");
if (p.time) {
struct timeval tv;
@@ -140,7 +140,8 @@ int32_t PositionModule::runOnce()
// We limit our GPS broadcasts to a max rate
uint32_t now = millis();
uint32_t intervalMs = config.position.position_broadcast_secs > 0 ? config.position.position_broadcast_secs * 1000 : default_broadcast_interval_secs * 1000;
uint32_t intervalMs = config.position.position_broadcast_secs > 0 ? config.position.position_broadcast_secs * 1000
: default_broadcast_interval_secs * 1000;
if (lastGpsSend == 0 || (now - lastGpsSend) >= intervalMs) {
// Only send packets if the channel is less than 40% utilized.
@@ -193,7 +194,7 @@ int32_t PositionModule::runOnce()
currentGeneration = radioGeneration;
LOG_INFO("Sending smart pos@%x:6 to mesh (wantReplies=%d, d=%d, dtt=%d, tt=%d)\n", node2->position.timestamp,
requestReplies, distance, distanceTravelThreshold, timeTravel);
requestReplies, distance, distanceTravelThreshold, timeTravel);
sendOurPosition(NODENUM_BROADCAST, requestReplies);
// Set the current coords as our last ones, after we've compared distance with current and decided to send

View File

@@ -25,14 +25,13 @@ class PositionModule : public ProtobufModule<Position>, private concurrency::OST
* name is for debugging output
*/
PositionModule();
/**
* Send our position into the mesh
*/
void sendOurPosition(NodeNum dest = NODENUM_BROADCAST, bool wantReplies = false);
protected:
/** Called to handle a particular incoming message
@return true if you've guaranteed you've handled this message and no other handlers should be considered for it

View File

@@ -1,9 +1,9 @@
#include "configuration.h"
#include "RemoteHardwareModule.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "RTC.h"
#include "Router.h"
#include "configuration.h"
#include "main.h"
#define NUM_GPIOS 64
@@ -32,7 +32,7 @@ static uint64_t digitalReads(uint64_t mask)
// The Arduino docs show to run pinMode(). But, when testing, found it is best not to.
// If the line below is uncommented, read will flip the pin to the default of the second
// argument in pinModes(), which will make the read turn the PIN "on".
//pinModes(mask, INPUT_PULLUP);
// pinModes(mask, INPUT_PULLUP);
for (uint64_t i = 0; i < NUM_GPIOS; i++) {
uint64_t m = 1 << i;
@@ -48,7 +48,7 @@ static uint64_t digitalReads(uint64_t mask)
RemoteHardwareModule::RemoteHardwareModule()
: ProtobufModule("remotehardware", PortNum_REMOTE_HARDWARE_APP, &HardwareMessage_msg), concurrency::OSThread(
"RemoteHardwareModule")
"RemoteHardwareModule")
{
}
@@ -93,9 +93,10 @@ bool RemoteHardwareModule::handleReceivedProtobuf(const MeshPacket &req, Hardwar
case HardwareMessage_Type_WATCH_GPIOS: {
watchGpios = p.gpio_mask;
lastWatchMsec = 0; // Force a new publish soon
previousWatch = ~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish)
enabled = true; // Let our thread run at least once
lastWatchMsec = 0; // Force a new publish soon
previousWatch =
~watchGpios; // generate a 'previous' value which is guaranteed to not match (to force an initial publish)
enabled = true; // Let our thread run at least once
LOG_INFO("Now watching GPIOs 0x%llx\n", watchGpios);
break;
}

View File

@@ -1,6 +1,6 @@
#include "configuration.h"
#include "ReplyModule.h"
#include "MeshService.h"
#include "configuration.h"
#include "main.h"
#include <assert.h>
@@ -16,7 +16,7 @@ MeshPacket *ReplyModule::allocReply()
screen->print("Sending reply\n");
const char *replyStr = "Message Received";
auto reply = allocDataPacket(); // Allocate a packet for sending
auto reply = allocDataPacket(); // Allocate a packet for sending
reply->decoded.payload.size = strlen(replyStr); // You must specify how many bytes are in the reply
memcpy(reply->decoded.payload.bytes, replyStr, reply->decoded.payload.size);

View File

@@ -1,7 +1,6 @@
#pragma once
#include "SinglePortModule.h"
/**
* A simple example module that just replies with "Message received" to any message it receives.
*/
@@ -14,9 +13,8 @@ class ReplyModule : public SinglePortModule
ReplyModule() : SinglePortModule("reply", PortNum_REPLY_APP) {}
protected:
/** For reply module we do all of our processing in the (normally optional)
* want_replies handling
*/
*/
virtual MeshPacket *allocReply() override;
};

View File

@@ -1,8 +1,8 @@
#include "configuration.h"
#include "RoutingModule.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "Router.h"
#include "configuration.h"
#include "main.h"
RoutingModule *routingModule;

View File

@@ -1,6 +1,6 @@
#pragma once
#include "ProtobufModule.h"
#include "Channels.h"
#include "ProtobufModule.h"
/**
* Routing module for router control messages

View File

@@ -1,8 +1,8 @@
#include "SerialModule.h"
#include "MeshService.h"
#include "NMEAWPL.h"
#include "NodeDB.h"
#include "RTC.h"
#include "NMEAWPL.h"
#include "Router.h"
#include "configuration.h"
#include <Arduino.h>
@@ -67,19 +67,18 @@ size_t serialPayloadSize;
SerialModuleRadio::SerialModuleRadio() : MeshModule("SerialModuleRadio")
{
switch (moduleConfig.serial.mode)
{
case ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG:
ourPortNum = PortNum_TEXT_MESSAGE_APP;
break;
case ModuleConfig_SerialConfig_Serial_Mode_NMEA:
ourPortNum = PortNum_POSITION_APP;
break;
default:
ourPortNum = PortNum_SERIAL_APP;
// restrict to the serial channel for rx
boundChannel = Channels::serialChannel;
break;
switch (moduleConfig.serial.mode) {
case ModuleConfig_SerialConfig_Serial_Mode_TEXTMSG:
ourPortNum = PortNum_TEXT_MESSAGE_APP;
break;
case ModuleConfig_SerialConfig_Serial_Mode_NMEA:
ourPortNum = PortNum_POSITION_APP;
break;
default:
ourPortNum = PortNum_SERIAL_APP;
// restrict to the serial channel for rx
boundChannel = Channels::serialChannel;
break;
}
}
@@ -161,7 +160,7 @@ int32_t SerialModule::runOnce()
baud = 921600;
}
#ifdef ARCH_ESP32
#ifdef ARCH_ESP32
Serial2.setRxBufferSize(RX_BUFFER);
if (moduleConfig.serial.rxd && moduleConfig.serial.txd) {

View File

@@ -1,11 +1,11 @@
#pragma once
#include "MeshModule.h"
#include "Router.h"
#include "SinglePortModule.h"
#include "concurrency/OSThread.h"
#include "configuration.h"
#include <Arduino.h>
#include "MeshModule.h"
#include "Router.h"
#include <functional>
#if (defined(ARCH_ESP32) || defined(ARCH_NRF52)) && !defined(TTGO_T_ECHO) && !defined(CONFIG_IDF_TARGET_ESP32S2)
@@ -50,7 +50,8 @@ class SerialModuleRadio : public MeshModule
/** Called to handle a particular incoming message
@return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it
@return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for
it
*/
virtual ProcessMessage handleReceived(const MeshPacket &mp) override;
@@ -66,7 +67,6 @@ class SerialModuleRadio : public MeshModule
return p;
}
};
extern SerialModuleRadio *serialModuleRadio;

View File

@@ -1,7 +1,7 @@
#include "configuration.h"
#include "TextMessageModule.h"
#include "NodeDB.h"
#include "PowerFSM.h"
#include "configuration.h"
TextMessageModule *textMessageModule;

View File

@@ -1,6 +1,6 @@
#pragma once
#include "SinglePortModule.h"
#include "Observer.h"
#include "SinglePortModule.h"
/**
* Text message handling for meshtastic - draws on the OLED display the most recent received message
@@ -14,10 +14,10 @@ class TextMessageModule : public SinglePortModule, public Observable<const MeshP
TextMessageModule() : SinglePortModule("text", PortNum_TEXT_MESSAGE_APP) {}
protected:
/** Called to handle a particular incoming message
@return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it
@return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for
it
*/
virtual ProcessMessage handleReceived(const MeshPacket &mp) override;
};

View File

@@ -1,26 +1,24 @@
#include "TraceRouteModule.h"
#include "MeshService.h"
#include "FloodingRouter.h"
#include "MeshService.h"
TraceRouteModule *traceRouteModule;
TraceRouteModule *traceRouteModule;
bool TraceRouteModule::handleReceivedProtobuf(const MeshPacket &mp, RouteDiscovery *r)
{
{
// Only handle a response
if (mp.decoded.request_id) {
printRoute(r, mp.to, mp.from);
}
return false; // let it be handled by RoutingModule
}
void TraceRouteModule::updateRoute(MeshPacket* p)
{
void TraceRouteModule::updateRoute(MeshPacket *p)
{
auto &incoming = p->decoded;
// Only append an ID for the request (one way)
if (!incoming.request_id) {
if (!incoming.request_id) {
RouteDiscovery scratch;
RouteDiscovery *updated = NULL;
memset(&scratch, 0, sizeof(scratch));
@@ -29,37 +27,38 @@ void TraceRouteModule::updateRoute(MeshPacket* p)
appendMyID(updated);
printRoute(updated, p->from, NODENUM_BROADCAST);
// Set updated route to the payload of the to be flooded packet
p->decoded.payload.size = pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &RouteDiscovery_msg, updated);
p->decoded.payload.size =
pb_encode_to_bytes(p->decoded.payload.bytes, sizeof(p->decoded.payload.bytes), &RouteDiscovery_msg, updated);
}
}
void TraceRouteModule::appendMyID(RouteDiscovery* updated)
void TraceRouteModule::appendMyID(RouteDiscovery *updated)
{
// Length of route array can normally not be exceeded due to the max. hop_limit of 7
if (updated->route_count < sizeof(updated->route)/sizeof(updated->route[0])) {
if (updated->route_count < sizeof(updated->route) / sizeof(updated->route[0])) {
updated->route[updated->route_count] = myNodeInfo.my_node_num;
updated->route_count += 1;
updated->route_count += 1;
} else {
LOG_WARN("Route exceeded maximum hop limit, are you bridging networks?\n");
}
}
void TraceRouteModule::printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest)
void TraceRouteModule::printRoute(RouteDiscovery *r, uint32_t origin, uint32_t dest)
{
LOG_INFO("Route traced:\n");
LOG_INFO("0x%x --> ", origin);
for (uint8_t i=0; i<r->route_count; i++) {
LOG_INFO("0x%x --> ", r->route[i]);
for (uint8_t i = 0; i < r->route_count; i++) {
LOG_INFO("0x%x --> ", r->route[i]);
}
if (dest != NODENUM_BROADCAST) LOG_INFO("0x%x\n", dest); else LOG_INFO("...\n");
if (dest != NODENUM_BROADCAST)
LOG_INFO("0x%x\n", dest);
else
LOG_INFO("...\n");
}
MeshPacket* TraceRouteModule::allocReply()
MeshPacket *TraceRouteModule::allocReply()
{
assert(currentRequest);
@@ -75,12 +74,12 @@ MeshPacket* TraceRouteModule::allocReply()
printRoute(updated, req.from, req.to);
// Create a MeshPacket with this payload and set it as the reply
MeshPacket* reply = allocDataProtobuf(*updated);
MeshPacket *reply = allocDataProtobuf(*updated);
return reply;
}
TraceRouteModule::TraceRouteModule() : ProtobufModule("traceroute", PortNum_TRACEROUTE_APP, &RouteDiscovery_msg) {
ourPortNum = PortNum_TRACEROUTE_APP;
TraceRouteModule::TraceRouteModule() : ProtobufModule("traceroute", PortNum_TRACEROUTE_APP, &RouteDiscovery_msg)
{
ourPortNum = PortNum_TRACEROUTE_APP;
}

View File

@@ -1,36 +1,34 @@
#pragma once
#include "ProtobufModule.h"
/**
* A module that traces the route to a certain destination node
*/
class TraceRouteModule : public ProtobufModule<RouteDiscovery>
{
public:
TraceRouteModule();
public:
TraceRouteModule();
// Let FloodingRouter call updateRoute upon rebroadcasting a TraceRoute request
friend class FloodingRouter;
// Let FloodingRouter call updateRoute upon rebroadcasting a TraceRoute request
friend class FloodingRouter;
protected:
bool handleReceivedProtobuf(const MeshPacket &mp, RouteDiscovery *r) override;
protected:
bool handleReceivedProtobuf(const MeshPacket &mp, RouteDiscovery *r) override;
virtual MeshPacket *allocReply() override;
virtual MeshPacket *allocReply() override;
/* Call before rebroadcasting a RouteDiscovery payload in order to update
the route array containing the IDs of nodes this packet went through */
void updateRoute(MeshPacket* p);
private:
// Call to add your ID to the route array of a RouteDiscovery message
void appendMyID(RouteDiscovery *r);
/* Call before rebroadcasting a RouteDiscovery payload in order to update
the route array containing the IDs of nodes this packet went through */
void updateRoute(MeshPacket *p);
/* Call to print the route array of a RouteDiscovery message.
Set origin to where the request came from.
Set dest to the ID of its destination, or NODENUM_BROADCAST if it has not yet arrived there. */
void printRoute(RouteDiscovery* r, uint32_t origin, uint32_t dest);
private:
// Call to add your ID to the route array of a RouteDiscovery message
void appendMyID(RouteDiscovery *r);
/* Call to print the route array of a RouteDiscovery message.
Set origin to where the request came from.
Set dest to the ID of its destination, or NODENUM_BROADCAST if it has not yet arrived there. */
void printRoute(RouteDiscovery *r, uint32_t origin, uint32_t dest);
};
extern TraceRouteModule *traceRouteModule;

View File

@@ -1,7 +1,7 @@
#include "configuration.h"
#include "WaypointModule.h"
#include "NodeDB.h"
#include "PowerFSM.h"
#include "configuration.h"
WaypointModule *waypointModule;
@@ -10,7 +10,6 @@ ProcessMessage WaypointModule::handleReceived(const MeshPacket &mp)
auto &p = mp.decoded;
LOG_INFO("Received waypoint msg from=0x%0x, id=0x%x, msg=%.*s\n", mp.from, mp.id, p.payload.size, p.payload.bytes);
notifyObservers(&mp);
return ProcessMessage::CONTINUE; // Let others look at this message also if they want

View File

@@ -1,6 +1,6 @@
#pragma once
#include "SinglePortModule.h"
#include "Observer.h"
#include "SinglePortModule.h"
/**
* Waypoint message handling for meshtastic
@@ -14,10 +14,10 @@ class WaypointModule : public SinglePortModule, public Observable<const MeshPack
WaypointModule() : SinglePortModule("waypoint", PortNum_WAYPOINT_APP) {}
protected:
/** Called to handle a particular incoming message
@return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it
@return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for
it
*/
virtual ProcessMessage handleReceived(const MeshPacket &mp) override;
};

View File

@@ -2,11 +2,11 @@
#include "configuration.h"
#if defined(ARCH_ESP32)
#include "AudioModule.h"
#include "FSCommon.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "RTC.h"
#include "Router.h"
#include "FSCommon.h"
#ifdef OLED_RU
#include "graphics/fonts/OLEDDisplayFontsRU.h"
@@ -17,14 +17,15 @@
A interface to send raw codec2 audio data over the mesh network. Based on the example code from the ESP32_codec2 project.
https://github.com/deulis/ESP32_Codec2
Codec 2 is a low-bitrate speech audio codec (speech coding)
Codec 2 is a low-bitrate speech audio codec (speech coding)
that is patent free and open source develop by David Grant Rowe.
http://www.rowetel.com/ and https://github.com/drowe67/codec2
Basic Usage:
1) Enable the module by setting audio.codec2_enabled to 1.
2) Set the pins for the I2S interface. Recommended on TLora is I2S_WS 13/I2S_SD 15/I2S_SIN 2/I2S_SCK 14
3) Set audio.bitrate to the desired codec2 rate (CODEC2_3200, CODEC2_2400, CODEC2_1600, CODEC2_1400, CODEC2_1300, CODEC2_1200, CODEC2_700, CODEC2_700B)
3) Set audio.bitrate to the desired codec2 rate (CODEC2_3200, CODEC2_2400, CODEC2_1600, CODEC2_1400, CODEC2_1300,
CODEC2_1200, CODEC2_700, CODEC2_700B)
KNOWN PROBLEMS
* Half Duplex
@@ -64,10 +65,10 @@ AudioModule *audioModule;
#define FONT_HEIGHT_MEDIUM fontHeight(FONT_MEDIUM)
#define FONT_HEIGHT_LARGE fontHeight(FONT_LARGE)
void run_codec2(void* parameter)
void run_codec2(void *parameter)
{
// 4 bytes of header in each frame hex c0 de c2 plus the bitrate
memcpy(audioModule->tx_encode_frame,&audioModule->tx_header,sizeof(audioModule->tx_header));
memcpy(audioModule->tx_encode_frame, &audioModule->tx_header, sizeof(audioModule->tx_header));
LOG_INFO("Starting codec2 task\n");
@@ -79,11 +80,11 @@ void run_codec2(void* parameter)
for (int i = 0; i < audioModule->adc_buffer_size; i++)
audioModule->speech[i] = (int16_t)hp_filter.Update((float)audioModule->speech[i]);
codec2_encode(audioModule->codec2, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index, audioModule->speech);
audioModule->tx_encode_frame_index += audioModule->encode_codec_size;
codec2_encode(audioModule->codec2, audioModule->tx_encode_frame + audioModule->tx_encode_frame_index,
audioModule->speech);
audioModule->tx_encode_frame_index += audioModule->encode_codec_size;
if (audioModule->tx_encode_frame_index == (audioModule->encode_frame_size + sizeof(audioModule->tx_header)))
{
if (audioModule->tx_encode_frame_index == (audioModule->encode_frame_size + sizeof(audioModule->tx_header))) {
LOG_INFO("Sending %d codec2 bytes\n", audioModule->encode_frame_size);
audioModule->sendPayload();
audioModule->tx_encode_frame_index = sizeof(audioModule->tx_header);
@@ -92,19 +93,18 @@ void run_codec2(void* parameter)
if (audioModule->radio_state == RadioState::rx) {
size_t bytesOut = 0;
if (memcmp(audioModule->rx_encode_frame, &audioModule->tx_header, sizeof(audioModule->tx_header)) == 0) {
for (int i = 4; i < audioModule->rx_encode_frame_index; i += audioModule->encode_codec_size)
{
for (int i = 4; i < audioModule->rx_encode_frame_index; i += audioModule->encode_codec_size) {
codec2_decode(audioModule->codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i);
i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500));
i2s_write(I2S_PORT, &audioModule->output_buffer, audioModule->adc_buffer_size, &bytesOut,
pdMS_TO_TICKS(500));
}
} else {
// if the buffer header does not match our own codec, make a temp decoding setup.
CODEC2* tmp_codec2 = codec2_create(audioModule->rx_encode_frame[3]);
CODEC2 *tmp_codec2 = codec2_create(audioModule->rx_encode_frame[3]);
codec2_set_lpc_post_filter(tmp_codec2, 1, 0, 0.8, 0.2);
int tmp_encode_codec_size = (codec2_bits_per_frame(tmp_codec2) + 7) / 8;
int tmp_adc_buffer_size = codec2_samples_per_frame(tmp_codec2);
for (int i = 4; i < audioModule->rx_encode_frame_index; i += tmp_encode_codec_size)
{
for (int i = 4; i < audioModule->rx_encode_frame_index; i += tmp_encode_codec_size) {
codec2_decode(tmp_codec2, audioModule->output_buffer, audioModule->rx_encode_frame + i);
i2s_write(I2S_PORT, &audioModule->output_buffer, tmp_adc_buffer_size, &bytesOut, pdMS_TO_TICKS(500));
}
@@ -125,16 +125,18 @@ AudioModule::AudioModule() : SinglePortModule("AudioModule", PortNum_AUDIO_APP),
// moduleConfig.audio.ptt_pin = 39;
if ((moduleConfig.audio.codec2_enabled) && (myRegion->audioPermitted)) {
LOG_INFO("Setting up codec2 in mode %u", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1);
LOG_INFO("Setting up codec2 in mode %u",
(moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1);
codec2 = codec2_create((moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1);
memcpy(tx_header.magic,c2_magic,sizeof(c2_magic));
memcpy(tx_header.magic, c2_magic, sizeof(c2_magic));
tx_header.mode = (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1;
codec2_set_lpc_post_filter(codec2, 1, 0, 0.8, 0.2);
encode_codec_size = (codec2_bits_per_frame(codec2) + 7) / 8;
encode_frame_num = (Constants_DATA_PAYLOAD_LEN - sizeof(tx_header)) / encode_codec_size;
encode_frame_size = encode_frame_num * encode_codec_size; // max 233 bytes + 4 header bytes
adc_buffer_size = codec2_samples_per_frame(codec2);
LOG_INFO(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size, encode_frame_size);
LOG_INFO(" using %d frames of %d bytes for a total payload length of %d bytes\n", encode_frame_num, encode_codec_size,
encode_frame_size);
xTaskCreate(&run_codec2, "codec2_task", 30000, NULL, 5, &codec2HandlerTask);
} else {
disable();
@@ -151,17 +153,18 @@ void AudioModule::drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int
display->setFont(FONT_SMALL);
display->fillRect(0 + x, 0 + y, x + display->getWidth(), y + FONT_HEIGHT_SMALL);
display->setColor(BLACK);
display->drawStringf(0 + x, 0 + y, buffer, "Codec2 Mode %d Audio", (moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1);
display->drawStringf(0 + x, 0 + y, buffer, "Codec2 Mode %d Audio",
(moduleConfig.audio.bitrate ? moduleConfig.audio.bitrate : AUDIO_MODULE_MODE) - 1);
display->setColor(WHITE);
display->setFont(FONT_LARGE);
display->setTextAlignment(TEXT_ALIGN_CENTER);
switch (radio_state) {
case RadioState::tx:
display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "PTT");
break;
default:
display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "Receive");
break;
case RadioState::tx:
display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "PTT");
break;
default:
display->drawString(display->getWidth() / 2 + x, (display->getHeight() - FONT_HEIGHT_SMALL) / 2 + y, "Receive");
break;
}
}
@@ -171,38 +174,37 @@ int32_t AudioModule::runOnce()
esp_err_t res;
if (firstTime) {
// Set up I2S Processor configuration. This will produce 16bit samples at 8 kHz instead of 12 from the ADC
LOG_INFO("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din, moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck);
i2s_config_t i2s_config = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) | (moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)),
.sample_rate = 8000,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S),
.intr_alloc_flags = 0,
.dma_buf_count = 8,
.dma_buf_len = adc_buffer_size, // 320 * 2 bytes
.use_apll = false,
.tx_desc_auto_clear = true,
.fixed_mclk = 0
};
LOG_INFO("Initializing I2S SD: %d DIN: %d WS: %d SCK: %d\n", moduleConfig.audio.i2s_sd, moduleConfig.audio.i2s_din,
moduleConfig.audio.i2s_ws, moduleConfig.audio.i2s_sck);
i2s_config_t i2s_config = {.mode = (i2s_mode_t)(I2S_MODE_MASTER | (moduleConfig.audio.i2s_sd ? I2S_MODE_RX : 0) |
(moduleConfig.audio.i2s_din ? I2S_MODE_TX : 0)),
.sample_rate = 8000,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_STAND_I2S),
.intr_alloc_flags = 0,
.dma_buf_count = 8,
.dma_buf_len = adc_buffer_size, // 320 * 2 bytes
.use_apll = false,
.tx_desc_auto_clear = true,
.fixed_mclk = 0};
res = i2s_driver_install(I2S_PORT, &i2s_config, 0, NULL);
if(res != ESP_OK)
if (res != ESP_OK)
LOG_ERROR("Failed to install I2S driver: %d\n", res);
const i2s_pin_config_t pin_config = {
.bck_io_num = moduleConfig.audio.i2s_sck,
.ws_io_num = moduleConfig.audio.i2s_ws,
.data_out_num = moduleConfig.audio.i2s_din ? moduleConfig.audio.i2s_din : I2S_PIN_NO_CHANGE,
.data_in_num = moduleConfig.audio.i2s_sd ? moduleConfig.audio.i2s_sd : I2S_PIN_NO_CHANGE
};
.data_in_num = moduleConfig.audio.i2s_sd ? moduleConfig.audio.i2s_sd : I2S_PIN_NO_CHANGE};
res = i2s_set_pin(I2S_PORT, &pin_config);
if(res != ESP_OK)
if (res != ESP_OK)
LOG_ERROR("Failed to set I2S pin config: %d\n", res);
res = i2s_start(I2S_PORT);
if(res != ESP_OK)
if (res != ESP_OK)
LOG_ERROR("Failed to start I2S: %d\n", res);
radio_state = RadioState::rx;
// Configure PTT input
@@ -237,13 +239,14 @@ int32_t AudioModule::runOnce()
if (radio_state == RadioState::tx) {
// Get I2S data from the microphone and place in data buffer
size_t bytesIn = 0;
res = i2s_read(I2S_PORT, adc_buffer + adc_buffer_index, adc_buffer_size - adc_buffer_index, &bytesIn, pdMS_TO_TICKS(40)); // wait 40ms for audio to arrive.
res = i2s_read(I2S_PORT, adc_buffer + adc_buffer_index, adc_buffer_size - adc_buffer_index, &bytesIn,
pdMS_TO_TICKS(40)); // wait 40ms for audio to arrive.
if (res == ESP_OK) {
adc_buffer_index += bytesIn;
if (adc_buffer_index == adc_buffer_size) {
adc_buffer_index = 0;
memcpy((void*)speech, (void*)adc_buffer, 2 * adc_buffer_size);
memcpy((void *)speech, (void *)adc_buffer, 2 * adc_buffer_size);
// Notify run_codec2 task that the buffer is ready.
radio_state = RadioState::tx;
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
@@ -258,7 +261,6 @@ int32_t AudioModule::runOnce()
} else {
return disable();
}
}
MeshPacket *AudioModule::allocReply()
@@ -281,7 +283,7 @@ void AudioModule::sendPayload(NodeNum dest, bool wantReplies)
p->to = dest;
p->decoded.want_response = wantReplies;
p->want_ack = false; // Audio is shoot&forget. No need to wait for ACKs.
p->want_ack = false; // Audio is shoot&forget. No need to wait for ACKs.
p->priority = MeshPacket_Priority_MAX; // Audio is important, because realtime
p->decoded.payload.size = tx_encode_frame_index;

View File

@@ -6,12 +6,12 @@
#if defined(ARCH_ESP32)
#include "NodeDB.h"
#include <Arduino.h>
#include <driver/i2s.h>
#include <functional>
#include <codec2.h>
#include <ButterworthFilter.h>
#include <OLEDDisplay.h>
#include <OLEDDisplayUi.h>
#include <codec2.h>
#include <driver/i2s.h>
#include <functional>
enum RadioState { standby, rx, tx };
@@ -47,7 +47,7 @@ class AudioModule : public SinglePortModule, public Observable<const UIFrameEven
int encode_frame_size = 0;
volatile RadioState radio_state = RadioState::rx;
struct CODEC2* codec2 = NULL;
struct CODEC2 *codec2 = NULL;
// int16_t sample;
AudioModule();
@@ -68,16 +68,16 @@ class AudioModule : public SinglePortModule, public Observable<const UIFrameEven
virtual MeshPacket *allocReply() override;
virtual bool wantUIFrame() override { return this->shouldDraw(); }
virtual Observable<const UIFrameEvent *>* getUIFrameObservable() override { return this; }
virtual Observable<const UIFrameEvent *> *getUIFrameObservable() override { return this; }
#if !HAS_SCREEN
void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y);
#else
virtual void drawFrame(
OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override;
#else
virtual void drawFrame(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) override;
#endif
/** Called to handle a particular incoming message
* @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered for it
* @return ProcessMessage::STOP if you've guaranteed you've handled this message and no other handlers should be considered
* for it
*/
virtual ProcessMessage handleReceived(const MeshPacket &mp) override;
};

View File

@@ -82,8 +82,6 @@ int32_t RangeTestModule::runOnce()
return disable();
// This thread does not need to run as a receiver
}
}
} else {
LOG_INFO("Range Test Module - Disabled\n");