Skip to content

Commit

Permalink
Merge pull request #108 from jeremiah-k/update-plugins
Browse files Browse the repository at this point in the history
"Playful ping" - Update core ping plugin
  • Loading branch information
jeremiah-k authored Nov 28, 2024
2 parents 952186b + a1d65d9 commit 9f57b02
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 41 deletions.
15 changes: 8 additions & 7 deletions .trunk/trunk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ cli:
plugins:
sources:
- id: trunk
ref: v1.6.4
ref: v1.6.5
uri: https://github.com/trunk-io/plugins
# Many linters and tools depend on runtimes - configure them here. (https://docs.trunk.io/runtimes)
runtimes:
Expand All @@ -17,17 +17,18 @@ runtimes:
# This is the section where you manage your linters. (https://docs.trunk.io/check/configuration)
lint:
enabled:
- [email protected]
- [email protected]
- bandit@1.7.10
- bandit@1.8.0
- [email protected]
- [email protected].287
- [email protected].317
- git-diff-check
- [email protected]
- markdownlint@0.42.0
- markdownlint@0.43.0
- [email protected]
- prettier@3.3.3
- ruff@0.7.3
- trufflehog@3.83.6
- prettier@3.4.1
- ruff@0.8.0
- trufflehog@3.84.1
- [email protected]
actions:
disabled:
Expand Down
14 changes: 11 additions & 3 deletions log_utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import logging
import os
from logging.handlers import RotatingFileHandler

from config import relay_config


def get_logger(name):
logger = logging.getLogger(name=name)
log_level = getattr(logging, relay_config["logging"]["level"].upper())
Expand Down Expand Up @@ -31,9 +33,15 @@ def get_logger(name):
os.makedirs(log_dir, exist_ok=True)

# Set up size-based log rotation
max_bytes = relay_config["logging"].get("max_log_size", 10 * 1024 * 1024) # Default 10 MB
backup_count = relay_config["logging"].get("backup_count", 1) # Default to 1 backup
file_handler = RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count)
max_bytes = relay_config["logging"].get(
"max_log_size", 10 * 1024 * 1024
) # Default 10 MB
backup_count = relay_config["logging"].get(
"backup_count", 1
) # Default to 1 backup
file_handler = RotatingFileHandler(
log_file, maxBytes=max_bytes, backupCount=backup_count
)

file_handler.setFormatter(
logging.Formatter(
Expand Down
14 changes: 4 additions & 10 deletions meshtastic_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,7 @@ def connect_meshtastic(force_connect=False):
)
time.sleep(wait_time)
else:
logger.error(
f"Could not connect after {retry_limit} attempts: {e}"
)
logger.error(f"Could not connect after {retry_limit} attempts: {e}")
return None

return meshtastic_client
Expand Down Expand Up @@ -191,9 +189,7 @@ def on_lost_meshtastic_connection(interface=None):
meshtastic_client = None

if event_loop:
reconnect_task = asyncio.run_coroutine_threadsafe(
reconnect(), event_loop
)
reconnect_task = asyncio.run_coroutine_threadsafe(reconnect(), event_loop)


async def reconnect():
Expand All @@ -210,9 +206,7 @@ async def reconnect():
)
await asyncio.sleep(backoff_time)
if shutting_down:
logger.info(
"Shutdown in progress. Aborting reconnection attempts."
)
logger.info("Shutdown in progress. Aborting reconnection attempts.")
break
meshtastic_client = connect_meshtastic(force_connect=True)
if meshtastic_client:
Expand Down Expand Up @@ -247,7 +241,7 @@ def on_meshtastic_message(packet, interface):

loop = event_loop

sender = packet.get('fromId') or packet.get('from')
sender = packet.get("fromId") or packet.get("from")

decoded = packet.get("decoded", {})
text = decoded.get("text")
Expand Down
3 changes: 2 additions & 1 deletion plugins/map_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@

import s2sphere
import staticmaps
from log_utils import get_logger
from nio import AsyncClient, UploadResponse
from PIL import Image, ImageFont

from log_utils import get_logger
from plugins.base_plugin import BasePlugin

logger = get_logger(__name__)


class TextLabel(staticmaps.Object):
def __init__(self, latlng: s2sphere.LatLng, text: str, fontSize: int = 12) -> None:
staticmaps.Object.__init__(self)
Expand Down
64 changes: 47 additions & 17 deletions plugins/ping_plugin.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,62 @@
import re
import string

from plugins.base_plugin import BasePlugin

def match_case(source, target):
return ''.join(
c.upper() if s.isupper() else c.lower()
for s, c in zip(source, target)
)

class Plugin(BasePlugin):
plugin_name = "ping"
punctuation = string.punctuation

@property
def description(self):
return "Check connectivity with the relay"
return "Check connectivity with the relay or respond to pings over the mesh"

async def handle_meshtastic_message(
self, packet, formatted_message, longname, meshnet_name
):
if (
"decoded" in packet
and "portnum" in packet["decoded"]
and packet["decoded"]["portnum"] == "TEXT_MESSAGE_APP"
and "text" in packet["decoded"]
):
message = packet["decoded"]["text"]
message = message.strip()
if f"!{self.plugin_name}" not in message:
return

from meshtastic_utils import connect_meshtastic

meshtastic_client = connect_meshtastic()
meshtastic_client.sendText(text="pong!", destinationId=packet["fromId"])
return True
if "decoded" in packet and "text" in packet["decoded"]:
message = packet["decoded"]["text"].strip()

# Updated regex to match optional punctuation before and after "ping"
match = re.search(
r"(?<!\w)([!?]*)(ping)([!?]*)(?!\w)", message, re.IGNORECASE
)
if match:
from meshtastic_utils import connect_meshtastic

meshtastic_client = connect_meshtastic()
channel = packet.get(
"channel", 0
) # Default to channel 0 if not provided

# Extract matched text and punctuation
pre_punc = match.group(1)
matched_text = match.group(2)
post_punc = match.group(3)

total_punc_length = len(pre_punc) + len(post_punc)

# Define the base response
base_response = "pong"

# Adjust base_response to match the case pattern of matched_text
base_response = match_case(matched_text, base_response)

# Construct the reply message
if total_punc_length > 5:
reply_message = "Pong..."
else:
reply_message = pre_punc + base_response + post_punc

# Send the reply back to the same channel
meshtastic_client.sendText(text=reply_message, channelIndex=channel)
return True

def get_matrix_commands(self):
return [self.plugin_name]
Expand Down
5 changes: 2 additions & 3 deletions sample_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@ logging:
#log_to_file: true # Default is false
#filename: logs/mmrelay.log # Default location
#max_log_size: 10485760 # 10 MB default if omitted
#backup_count: 3 # Keeps 1 backup as the default if omitted
#backup_count: 1 # Keeps 1 backup as the default if omitted

#Note: Some plugins are experimental and some need maintenance.
#These are core Plugins - Note: Some plugins are experimental and some need maintenance.
plugins:
health:
active: true
nodes:
active: true
# Other core plugins..

#community-plugins: # Note: Community plugins are a new feature. Please report any issues.
# sample_plugin:
Expand Down

0 comments on commit 9f57b02

Please sign in to comment.