Skip to content

Commit

Permalink
Merge pull request #51 from geoffwhittington/shortnames
Browse files Browse the repository at this point in the history
Shortname support
  • Loading branch information
jeremiah-k authored Jun 9, 2023
2 parents aa84c2a + fe336f9 commit ed9f3a7
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 8 deletions.
30 changes: 29 additions & 1 deletion db_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ def initialize_database():
cursor.execute(
"CREATE TABLE IF NOT EXISTS longnames (meshtastic_id TEXT PRIMARY KEY, longname TEXT)"
)
cursor.execute(
"CREATE TABLE IF NOT EXISTS shortnames (meshtastic_id TEXT PRIMARY KEY, shortname TEXT)"
)
cursor.execute(
"CREATE TABLE IF NOT EXISTS plugin_data (plugin_name TEXT, meshtastic_id TEXT, data TEXT, PRIMARY KEY (plugin_name, meshtastic_id))"
)
Expand Down Expand Up @@ -81,7 +84,6 @@ def save_longname(meshtastic_id, longname):
)
conn.commit()


def update_longnames(nodes):
if nodes:
for node in nodes.values():
Expand All @@ -90,3 +92,29 @@ def update_longnames(nodes):
meshtastic_id = user["id"]
longname = user.get("longName", "N/A")
save_longname(meshtastic_id, longname)

def get_shortname(meshtastic_id):
with sqlite3.connect("meshtastic.sqlite") as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT shortname FROM shortnames WHERE meshtastic_id=?", (meshtastic_id,))
result = cursor.fetchone()
return result[0] if result else None

def save_shortname(meshtastic_id, shortname):
with sqlite3.connect("meshtastic.sqlite") as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO shortnames (meshtastic_id, shortname) VALUES (?, ?)",
(meshtastic_id, shortname),
)
conn.commit()

def update_shortnames(nodes):
if nodes:
for node in nodes.values():
user = node.get("user")
if user:
meshtastic_id = user["id"]
shortname = user.get("shortName", "N/A")
save_shortname(meshtastic_id, shortname)
7 changes: 4 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
)
from pubsub import pub
from typing import List
from db_utils import initialize_database, update_longnames
from db_utils import initialize_database, update_longnames, update_shortnames
from matrix_utils import (
connect_matrix,
join_matrix_room,
Expand Down Expand Up @@ -70,16 +70,17 @@ async def main():
# Start the Matrix client
while True:
try:
# Update longnames
# Update longnames & shortnames
update_longnames(meshtastic_interface.nodes)
update_shortnames(meshtastic_interface.nodes)

matrix_logger.info("Syncing with server...")
await matrix_client.sync_forever(timeout=30000)
matrix_logger.info("Sync completed.")
except Exception as e:
matrix_logger.error(f"Error syncing with server: {e}")

await asyncio.sleep(60) # Update longnames every 60 seconds
await asyncio.sleep(60) # Update longnames & shortnames every 60 seconds


asyncio.run(main())
10 changes: 7 additions & 3 deletions matrix_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,14 @@ async def join_matrix_room(matrix_client, room_id_or_alias: str) -> None:


# Send message to the Matrix room
async def matrix_relay(room_id, message, longname, meshnet_name):
async def matrix_relay(room_id, message, longname, shortname, meshnet_name):
matrix_client = await connect_matrix()
try:
content = {
"msgtype": "m.text",
"body": message,
"meshtastic_longname": longname,
"meshtastic_shortname": shortname,
"meshtastic_meshnet": meshnet_name,
}
await asyncio.wait_for(
Expand Down Expand Up @@ -156,6 +157,7 @@ async def on_room_message(
text = event.body.strip()

longname = event.source["content"].get("meshtastic_longname")
shortname = event.source["content"].get("meshtastic_shortname", None)
meshnet_name = event.source["content"].get("meshtastic_meshnet")
suppress = event.source["content"].get("mmrelay_suppress")
local_meshnet_name = relay_config["meshtastic"]["meshnet_name"]
Expand All @@ -168,9 +170,11 @@ async def on_room_message(
full_display_name = f"{longname}/{meshnet_name}"
if meshnet_name != local_meshnet_name:
logger.info(f"Processing message from remote meshnet: {text}")
short_longname = longname[:3]
short_meshnet_name = meshnet_name[:4]
prefix = f"{short_longname}/{short_meshnet_name}: "
# If shortname is None, truncate the longname to 3 characters
if shortname is None:
shortname = longname[:3]
prefix = f"{shortname}/{short_meshnet_name}: "
text = re.sub(
rf"^\[{full_display_name}\]: ", "", text
) # Remove the original prefix from the text
Expand Down
4 changes: 3 additions & 1 deletion meshtastic_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from config import relay_config
from log_utils import get_logger
from db_utils import get_longname
from db_utils import get_longname, get_shortname
from plugin_loader import load_plugins

matrix_rooms: List[dict] = relay_config["matrix_rooms"]
Expand Down Expand Up @@ -115,6 +115,7 @@ def on_meshtastic_message(packet, loop=None):
)

longname = get_longname(sender) or sender
shortname = get_shortname(sender) or sender
meshnet_name = relay_config["meshtastic"]["meshnet_name"]

formatted_message = f"[{longname}/{meshnet_name}]: {text}"
Expand Down Expand Up @@ -149,6 +150,7 @@ def on_meshtastic_message(packet, loop=None):
room["id"],
formatted_message,
longname,
shortname,
meshnet_name,
),
loop=loop,
Expand Down

0 comments on commit ed9f3a7

Please sign in to comment.