mmrelay 1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of mmrelay might be problematic. Click here for more details.
- mmrelay/__init__.py +9 -0
- mmrelay/cli.py +384 -0
- mmrelay/config.py +218 -0
- mmrelay/config_checker.py +133 -0
- mmrelay/db_utils.py +309 -0
- mmrelay/log_utils.py +107 -0
- mmrelay/main.py +281 -0
- mmrelay/matrix_utils.py +754 -0
- mmrelay/meshtastic_utils.py +569 -0
- mmrelay/plugin_loader.py +336 -0
- mmrelay/plugins/__init__.py +3 -0
- mmrelay/plugins/base_plugin.py +212 -0
- mmrelay/plugins/debug_plugin.py +17 -0
- mmrelay/plugins/drop_plugin.py +120 -0
- mmrelay/plugins/health_plugin.py +64 -0
- mmrelay/plugins/help_plugin.py +55 -0
- mmrelay/plugins/map_plugin.py +323 -0
- mmrelay/plugins/mesh_relay_plugin.py +134 -0
- mmrelay/plugins/nodes_plugin.py +92 -0
- mmrelay/plugins/ping_plugin.py +118 -0
- mmrelay/plugins/telemetry_plugin.py +179 -0
- mmrelay/plugins/weather_plugin.py +208 -0
- mmrelay/setup_utils.py +263 -0
- mmrelay-1.0.dist-info/METADATA +160 -0
- mmrelay-1.0.dist-info/RECORD +29 -0
- mmrelay-1.0.dist-info/WHEEL +5 -0
- mmrelay-1.0.dist-info/entry_points.txt +2 -0
- mmrelay-1.0.dist-info/licenses/LICENSE +21 -0
- mmrelay-1.0.dist-info/top_level.txt +1 -0
mmrelay/plugin_loader.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
# trunk-ignore-all(bandit)
|
|
2
|
+
import hashlib
|
|
3
|
+
import importlib.util
|
|
4
|
+
import os
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from mmrelay.config import get_app_path, get_base_dir
|
|
9
|
+
from mmrelay.log_utils import get_logger
|
|
10
|
+
|
|
11
|
+
# Global config variable that will be set from main.py
|
|
12
|
+
config = None
|
|
13
|
+
|
|
14
|
+
logger = get_logger(name="Plugins")
|
|
15
|
+
sorted_active_plugins = []
|
|
16
|
+
plugins_loaded = False
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_custom_plugin_dirs():
|
|
20
|
+
"""
|
|
21
|
+
Returns a list of directories to check for custom plugins in order of priority:
|
|
22
|
+
1. User directory (~/.mmrelay/plugins/custom)
|
|
23
|
+
2. Local directory (plugins/custom) for backward compatibility
|
|
24
|
+
"""
|
|
25
|
+
dirs = []
|
|
26
|
+
|
|
27
|
+
# Check user directory first (preferred location)
|
|
28
|
+
user_dir = os.path.join(get_base_dir(), "plugins", "custom")
|
|
29
|
+
os.makedirs(user_dir, exist_ok=True)
|
|
30
|
+
dirs.append(user_dir)
|
|
31
|
+
|
|
32
|
+
# Check local directory (backward compatibility)
|
|
33
|
+
local_dir = os.path.join(get_app_path(), "plugins", "custom")
|
|
34
|
+
dirs.append(local_dir)
|
|
35
|
+
|
|
36
|
+
return dirs
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def get_community_plugin_dirs():
|
|
40
|
+
"""
|
|
41
|
+
Returns a list of directories to check for community plugins in order of priority:
|
|
42
|
+
1. User directory (~/.mmrelay/plugins/community)
|
|
43
|
+
2. Local directory (plugins/community) for backward compatibility
|
|
44
|
+
"""
|
|
45
|
+
dirs = []
|
|
46
|
+
|
|
47
|
+
# Check user directory first (preferred location)
|
|
48
|
+
user_dir = os.path.join(get_base_dir(), "plugins", "community")
|
|
49
|
+
os.makedirs(user_dir, exist_ok=True)
|
|
50
|
+
dirs.append(user_dir)
|
|
51
|
+
|
|
52
|
+
# Check local directory (backward compatibility)
|
|
53
|
+
local_dir = os.path.join(get_app_path(), "plugins", "community")
|
|
54
|
+
dirs.append(local_dir)
|
|
55
|
+
|
|
56
|
+
return dirs
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def clone_or_update_repo(repo_url, tag, plugins_dir):
|
|
60
|
+
# Extract the repository name from the URL
|
|
61
|
+
repo_name = os.path.splitext(os.path.basename(repo_url.rstrip("/")))[0]
|
|
62
|
+
repo_path = os.path.join(plugins_dir, repo_name)
|
|
63
|
+
if os.path.isdir(repo_path):
|
|
64
|
+
try:
|
|
65
|
+
subprocess.check_call(["git", "-C", repo_path, "fetch"])
|
|
66
|
+
subprocess.check_call(["git", "-C", repo_path, "checkout", tag])
|
|
67
|
+
subprocess.check_call(["git", "-C", repo_path, "pull", "origin", tag])
|
|
68
|
+
logger.info(f"Updated repository {repo_name} to {tag}")
|
|
69
|
+
except subprocess.CalledProcessError as e:
|
|
70
|
+
logger.error(f"Error updating repository {repo_name}: {e}")
|
|
71
|
+
logger.error(
|
|
72
|
+
f"Please manually git clone the repository {repo_url} into {repo_path}"
|
|
73
|
+
)
|
|
74
|
+
sys.exit(1)
|
|
75
|
+
else:
|
|
76
|
+
try:
|
|
77
|
+
os.makedirs(plugins_dir, exist_ok=True)
|
|
78
|
+
subprocess.check_call(
|
|
79
|
+
["git", "clone", "--branch", tag, repo_url], cwd=plugins_dir
|
|
80
|
+
)
|
|
81
|
+
logger.info(f"Cloned repository {repo_name} from {repo_url} at {tag}")
|
|
82
|
+
except subprocess.CalledProcessError as e:
|
|
83
|
+
logger.error(f"Error cloning repository {repo_name}: {e}")
|
|
84
|
+
logger.error(
|
|
85
|
+
f"Please manually git clone the repository {repo_url} into {repo_path}"
|
|
86
|
+
)
|
|
87
|
+
sys.exit(1)
|
|
88
|
+
# Install requirements if requirements.txt exists
|
|
89
|
+
requirements_path = os.path.join(repo_path, "requirements.txt")
|
|
90
|
+
if os.path.isfile(requirements_path):
|
|
91
|
+
try:
|
|
92
|
+
# Use pip to install the requirements.txt
|
|
93
|
+
subprocess.check_call(
|
|
94
|
+
[sys.executable, "-m", "pip", "install", "-r", requirements_path]
|
|
95
|
+
)
|
|
96
|
+
logger.info(f"Installed requirements for plugin {repo_name}")
|
|
97
|
+
except subprocess.CalledProcessError as e:
|
|
98
|
+
logger.error(f"Error installing requirements for plugin {repo_name}: {e}")
|
|
99
|
+
logger.error(
|
|
100
|
+
f"Please manually install the requirements from {requirements_path}"
|
|
101
|
+
)
|
|
102
|
+
sys.exit(1)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def load_plugins_from_directory(directory, recursive=False):
|
|
106
|
+
plugins = []
|
|
107
|
+
if os.path.isdir(directory):
|
|
108
|
+
for root, _dirs, files in os.walk(directory):
|
|
109
|
+
for filename in files:
|
|
110
|
+
if filename.endswith(".py"):
|
|
111
|
+
plugin_path = os.path.join(root, filename)
|
|
112
|
+
module_name = (
|
|
113
|
+
"plugin_"
|
|
114
|
+
+ hashlib.sha256(plugin_path.encode("utf-8")).hexdigest()
|
|
115
|
+
)
|
|
116
|
+
spec = importlib.util.spec_from_file_location(
|
|
117
|
+
module_name, plugin_path
|
|
118
|
+
)
|
|
119
|
+
plugin_module = importlib.util.module_from_spec(spec)
|
|
120
|
+
try:
|
|
121
|
+
spec.loader.exec_module(plugin_module)
|
|
122
|
+
if hasattr(plugin_module, "Plugin"):
|
|
123
|
+
plugins.append(plugin_module.Plugin())
|
|
124
|
+
else:
|
|
125
|
+
logger.warning(
|
|
126
|
+
f"{plugin_path} does not define a Plugin class."
|
|
127
|
+
)
|
|
128
|
+
except Exception as e:
|
|
129
|
+
logger.error(f"Error loading plugin {plugin_path}: {e}")
|
|
130
|
+
if not recursive:
|
|
131
|
+
break
|
|
132
|
+
else:
|
|
133
|
+
if not plugins_loaded: # Only log the missing directory once
|
|
134
|
+
logger.debug(f"Directory {directory} does not exist.")
|
|
135
|
+
return plugins
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def load_plugins(passed_config=None):
|
|
139
|
+
global sorted_active_plugins
|
|
140
|
+
global plugins_loaded
|
|
141
|
+
global config
|
|
142
|
+
|
|
143
|
+
if plugins_loaded:
|
|
144
|
+
return sorted_active_plugins
|
|
145
|
+
|
|
146
|
+
logger.info("Checking plugin config...")
|
|
147
|
+
|
|
148
|
+
# Update the global config if a config is passed
|
|
149
|
+
if passed_config is not None:
|
|
150
|
+
config = passed_config
|
|
151
|
+
|
|
152
|
+
# Check if config is available
|
|
153
|
+
if config is None:
|
|
154
|
+
logger.error("No configuration available. Cannot load plugins.")
|
|
155
|
+
return []
|
|
156
|
+
|
|
157
|
+
# Import core plugins
|
|
158
|
+
from mmrelay.plugins.debug_plugin import Plugin as DebugPlugin
|
|
159
|
+
from mmrelay.plugins.drop_plugin import Plugin as DropPlugin
|
|
160
|
+
from mmrelay.plugins.health_plugin import Plugin as HealthPlugin
|
|
161
|
+
from mmrelay.plugins.help_plugin import Plugin as HelpPlugin
|
|
162
|
+
from mmrelay.plugins.map_plugin import Plugin as MapPlugin
|
|
163
|
+
from mmrelay.plugins.mesh_relay_plugin import Plugin as MeshRelayPlugin
|
|
164
|
+
from mmrelay.plugins.nodes_plugin import Plugin as NodesPlugin
|
|
165
|
+
from mmrelay.plugins.ping_plugin import Plugin as PingPlugin
|
|
166
|
+
from mmrelay.plugins.telemetry_plugin import Plugin as TelemetryPlugin
|
|
167
|
+
from mmrelay.plugins.weather_plugin import Plugin as WeatherPlugin
|
|
168
|
+
|
|
169
|
+
# Initial list of core plugins
|
|
170
|
+
core_plugins = [
|
|
171
|
+
HealthPlugin(),
|
|
172
|
+
MapPlugin(),
|
|
173
|
+
MeshRelayPlugin(),
|
|
174
|
+
PingPlugin(),
|
|
175
|
+
TelemetryPlugin(),
|
|
176
|
+
WeatherPlugin(),
|
|
177
|
+
HelpPlugin(),
|
|
178
|
+
NodesPlugin(),
|
|
179
|
+
DropPlugin(),
|
|
180
|
+
DebugPlugin(),
|
|
181
|
+
]
|
|
182
|
+
|
|
183
|
+
plugins = core_plugins.copy()
|
|
184
|
+
|
|
185
|
+
# Process and load custom plugins
|
|
186
|
+
custom_plugins_config = config.get("custom-plugins", {})
|
|
187
|
+
custom_plugin_dirs = get_custom_plugin_dirs()
|
|
188
|
+
|
|
189
|
+
active_custom_plugins = [
|
|
190
|
+
plugin_name
|
|
191
|
+
for plugin_name, plugin_info in custom_plugins_config.items()
|
|
192
|
+
if plugin_info.get("active", False)
|
|
193
|
+
]
|
|
194
|
+
|
|
195
|
+
if active_custom_plugins:
|
|
196
|
+
logger.debug(
|
|
197
|
+
f"Loading active custom plugins: {', '.join(active_custom_plugins)}"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
# Only load custom plugins that are explicitly enabled
|
|
201
|
+
for plugin_name in active_custom_plugins:
|
|
202
|
+
plugin_found = False
|
|
203
|
+
|
|
204
|
+
# Try each directory in order
|
|
205
|
+
for custom_dir in custom_plugin_dirs:
|
|
206
|
+
plugin_path = os.path.join(custom_dir, plugin_name)
|
|
207
|
+
if os.path.exists(plugin_path):
|
|
208
|
+
logger.debug(f"Loading custom plugin from: {plugin_path}")
|
|
209
|
+
plugins.extend(
|
|
210
|
+
load_plugins_from_directory(plugin_path, recursive=False)
|
|
211
|
+
)
|
|
212
|
+
plugin_found = True
|
|
213
|
+
break
|
|
214
|
+
|
|
215
|
+
if not plugin_found:
|
|
216
|
+
logger.warning(
|
|
217
|
+
f"Custom plugin '{plugin_name}' not found in any of the plugin directories"
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
# Process and download community plugins
|
|
221
|
+
community_plugins_config = config.get("community-plugins", {})
|
|
222
|
+
community_plugin_dirs = get_community_plugin_dirs()
|
|
223
|
+
|
|
224
|
+
# Get the first directory for cloning (prefer user directory)
|
|
225
|
+
community_plugins_dir = community_plugin_dirs[
|
|
226
|
+
-1
|
|
227
|
+
] # Use the user directory for new clones
|
|
228
|
+
|
|
229
|
+
# Create community plugins directory if needed
|
|
230
|
+
active_community_plugins = [
|
|
231
|
+
plugin_name
|
|
232
|
+
for plugin_name, plugin_info in community_plugins_config.items()
|
|
233
|
+
if plugin_info.get("active", False)
|
|
234
|
+
]
|
|
235
|
+
|
|
236
|
+
if active_community_plugins:
|
|
237
|
+
# Ensure all community plugin directories exist
|
|
238
|
+
for dir_path in community_plugin_dirs:
|
|
239
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
240
|
+
|
|
241
|
+
logger.debug(
|
|
242
|
+
f"Loading active community plugins: {', '.join(active_community_plugins)}"
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
# Only process community plugins if config section exists and is a dictionary
|
|
246
|
+
if isinstance(community_plugins_config, dict):
|
|
247
|
+
for plugin_name, plugin_info in community_plugins_config.items():
|
|
248
|
+
if not plugin_info.get("active", False):
|
|
249
|
+
logger.debug(
|
|
250
|
+
f"Skipping community plugin {plugin_name} - not active in config"
|
|
251
|
+
)
|
|
252
|
+
continue
|
|
253
|
+
|
|
254
|
+
repo_url = plugin_info.get("repository")
|
|
255
|
+
tag = plugin_info.get("tag", "master")
|
|
256
|
+
if repo_url:
|
|
257
|
+
# Clone to the user directory by default
|
|
258
|
+
clone_or_update_repo(repo_url, tag, community_plugins_dir)
|
|
259
|
+
else:
|
|
260
|
+
logger.error("Repository URL not specified for a community plugin")
|
|
261
|
+
logger.error("Please specify the repository URL in config.yaml")
|
|
262
|
+
sys.exit(1)
|
|
263
|
+
|
|
264
|
+
# Only load community plugins that are explicitly enabled
|
|
265
|
+
for plugin_name in active_community_plugins:
|
|
266
|
+
plugin_info = community_plugins_config[plugin_name]
|
|
267
|
+
repo_url = plugin_info.get("repository")
|
|
268
|
+
if repo_url:
|
|
269
|
+
# Extract repository name from URL
|
|
270
|
+
repo_name = os.path.splitext(os.path.basename(repo_url.rstrip("/")))[0]
|
|
271
|
+
|
|
272
|
+
# Try each directory in order
|
|
273
|
+
plugin_found = False
|
|
274
|
+
for dir_path in community_plugin_dirs:
|
|
275
|
+
plugin_path = os.path.join(dir_path, repo_name)
|
|
276
|
+
if os.path.exists(plugin_path):
|
|
277
|
+
logger.debug(f"Loading community plugin from: {plugin_path}")
|
|
278
|
+
plugins.extend(
|
|
279
|
+
load_plugins_from_directory(plugin_path, recursive=True)
|
|
280
|
+
)
|
|
281
|
+
plugin_found = True
|
|
282
|
+
break
|
|
283
|
+
|
|
284
|
+
if not plugin_found:
|
|
285
|
+
logger.warning(
|
|
286
|
+
f"Community plugin '{repo_name}' not found in any of the plugin directories"
|
|
287
|
+
)
|
|
288
|
+
else:
|
|
289
|
+
logger.error(
|
|
290
|
+
f"Repository URL not specified for community plugin: {plugin_name}"
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
# Filter and sort active plugins by priority
|
|
294
|
+
active_plugins = []
|
|
295
|
+
for plugin in plugins:
|
|
296
|
+
plugin_name = getattr(plugin, "plugin_name", plugin.__class__.__name__)
|
|
297
|
+
|
|
298
|
+
# Determine if the plugin is active based on the configuration
|
|
299
|
+
if plugin in core_plugins:
|
|
300
|
+
# Core plugins: default to inactive unless specified otherwise
|
|
301
|
+
plugin_config = config.get("plugins", {}).get(plugin_name, {})
|
|
302
|
+
is_active = plugin_config.get("active", False)
|
|
303
|
+
else:
|
|
304
|
+
# Custom and community plugins: default to inactive unless specified
|
|
305
|
+
if plugin_name in config.get("custom-plugins", {}):
|
|
306
|
+
plugin_config = config.get("custom-plugins", {}).get(plugin_name, {})
|
|
307
|
+
elif plugin_name in community_plugins_config:
|
|
308
|
+
plugin_config = community_plugins_config.get(plugin_name, {})
|
|
309
|
+
else:
|
|
310
|
+
plugin_config = {}
|
|
311
|
+
|
|
312
|
+
is_active = plugin_config.get("active", False)
|
|
313
|
+
|
|
314
|
+
if is_active:
|
|
315
|
+
plugin.priority = plugin_config.get(
|
|
316
|
+
"priority", getattr(plugin, "priority", 100)
|
|
317
|
+
)
|
|
318
|
+
active_plugins.append(plugin)
|
|
319
|
+
try:
|
|
320
|
+
plugin.start()
|
|
321
|
+
except Exception as e:
|
|
322
|
+
logger.error(f"Error starting plugin {plugin_name}: {e}")
|
|
323
|
+
|
|
324
|
+
sorted_active_plugins = sorted(active_plugins, key=lambda plugin: plugin.priority)
|
|
325
|
+
|
|
326
|
+
# Log all loaded plugins
|
|
327
|
+
if sorted_active_plugins:
|
|
328
|
+
plugin_names = [
|
|
329
|
+
getattr(plugin, "plugin_name", plugin.__class__.__name__)
|
|
330
|
+
for plugin in sorted_active_plugins
|
|
331
|
+
]
|
|
332
|
+
logger.info(f"Plugins loaded: {', '.join(plugin_names)}")
|
|
333
|
+
else:
|
|
334
|
+
logger.info("Plugins loaded: none")
|
|
335
|
+
|
|
336
|
+
plugins_loaded = True # Set the flag to indicate that plugins have been load
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import threading
|
|
2
|
+
import time
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
import markdown
|
|
6
|
+
import schedule
|
|
7
|
+
|
|
8
|
+
from mmrelay.db_utils import (
|
|
9
|
+
delete_plugin_data,
|
|
10
|
+
get_plugin_data,
|
|
11
|
+
get_plugin_data_for_node,
|
|
12
|
+
store_plugin_data,
|
|
13
|
+
)
|
|
14
|
+
from mmrelay.log_utils import get_logger
|
|
15
|
+
|
|
16
|
+
# Global config variable that will be set from main.py
|
|
17
|
+
config = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BasePlugin(ABC):
|
|
21
|
+
# Class-level default attributes
|
|
22
|
+
plugin_name = None # Must be overridden in subclasses
|
|
23
|
+
max_data_rows_per_node = 100
|
|
24
|
+
priority = 10
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def description(self):
|
|
28
|
+
return ""
|
|
29
|
+
|
|
30
|
+
def __init__(self) -> None:
|
|
31
|
+
# IMPORTANT NOTE FOR PLUGIN DEVELOPERS:
|
|
32
|
+
# When creating a plugin that inherits from BasePlugin, you MUST set
|
|
33
|
+
# self.plugin_name in your __init__ method BEFORE calling super().__init__()
|
|
34
|
+
# Example:
|
|
35
|
+
# def __init__(self):
|
|
36
|
+
# self.plugin_name = "your_plugin_name" # Set this FIRST
|
|
37
|
+
# super().__init__() # Then call parent
|
|
38
|
+
#
|
|
39
|
+
# Failure to do this will cause command recognition issues and other problems.
|
|
40
|
+
|
|
41
|
+
super().__init__()
|
|
42
|
+
|
|
43
|
+
# Verify plugin_name is properly defined
|
|
44
|
+
if not hasattr(self, "plugin_name") or self.plugin_name is None:
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"{self.__class__.__name__} is missing plugin_name definition. "
|
|
47
|
+
f"Make sure to set self.plugin_name BEFORE calling super().__init__()"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
self.logger = get_logger(f"Plugin:{self.plugin_name}")
|
|
51
|
+
self.config = {"active": False}
|
|
52
|
+
global config
|
|
53
|
+
plugin_levels = ["plugins", "community-plugins", "custom-plugins"]
|
|
54
|
+
|
|
55
|
+
# Check if config is available
|
|
56
|
+
if config is not None:
|
|
57
|
+
for level in plugin_levels:
|
|
58
|
+
if level in config and self.plugin_name in config[level]:
|
|
59
|
+
self.config = config[level][self.plugin_name]
|
|
60
|
+
break
|
|
61
|
+
|
|
62
|
+
# Get the list of mapped channels
|
|
63
|
+
self.mapped_channels = [
|
|
64
|
+
room.get("meshtastic_channel")
|
|
65
|
+
for room in config.get("matrix_rooms", [])
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
# Get the channels specified for this plugin, or default to all mapped channels
|
|
69
|
+
self.channels = self.config.get("channels", self.mapped_channels)
|
|
70
|
+
|
|
71
|
+
# Ensure channels is a list
|
|
72
|
+
if not isinstance(self.channels, list):
|
|
73
|
+
self.channels = [self.channels]
|
|
74
|
+
|
|
75
|
+
# Validate the channels
|
|
76
|
+
invalid_channels = [
|
|
77
|
+
ch for ch in self.channels if ch not in self.mapped_channels
|
|
78
|
+
]
|
|
79
|
+
if invalid_channels:
|
|
80
|
+
self.logger.warning(
|
|
81
|
+
f"Plugin '{self.plugin_name}': Channels {invalid_channels} are not mapped in configuration."
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
# Get the response delay from the meshtastic config only
|
|
85
|
+
self.response_delay = 3 # Default value
|
|
86
|
+
if config is not None:
|
|
87
|
+
self.response_delay = config.get("meshtastic", {}).get(
|
|
88
|
+
"plugin_response_delay", self.response_delay
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def start(self):
|
|
92
|
+
if "schedule" not in self.config or (
|
|
93
|
+
"at" not in self.config["schedule"]
|
|
94
|
+
and "hours" not in self.config["schedule"]
|
|
95
|
+
and "minutes" not in self.config["schedule"]
|
|
96
|
+
):
|
|
97
|
+
self.logger.debug(f"Started with priority={self.priority}")
|
|
98
|
+
return
|
|
99
|
+
|
|
100
|
+
# Schedule the background job based on the configuration
|
|
101
|
+
if "at" in self.config["schedule"] and "hours" in self.config["schedule"]:
|
|
102
|
+
schedule.every(self.config["schedule"]["hours"]).hours.at(
|
|
103
|
+
self.config["schedule"]["at"]
|
|
104
|
+
).do(self.background_job)
|
|
105
|
+
elif "at" in self.config["schedule"] and "minutes" in self.config["schedule"]:
|
|
106
|
+
schedule.every(self.config["schedule"]["minutes"]).minutes.at(
|
|
107
|
+
self.config["schedule"]["at"]
|
|
108
|
+
).do(self.background_job)
|
|
109
|
+
elif "hours" in self.config["schedule"]:
|
|
110
|
+
schedule.every(self.config["schedule"]["hours"]).hours.do(
|
|
111
|
+
self.background_job
|
|
112
|
+
)
|
|
113
|
+
elif "minutes" in self.config["schedule"]:
|
|
114
|
+
schedule.every(self.config["schedule"]["minutes"]).minutes.do(
|
|
115
|
+
self.background_job
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
# Function to execute the scheduled tasks
|
|
119
|
+
def run_schedule():
|
|
120
|
+
while True:
|
|
121
|
+
schedule.run_pending()
|
|
122
|
+
time.sleep(1)
|
|
123
|
+
|
|
124
|
+
# Create a thread for executing the scheduled tasks
|
|
125
|
+
schedule_thread = threading.Thread(target=run_schedule)
|
|
126
|
+
|
|
127
|
+
# Start the thread
|
|
128
|
+
schedule_thread.start()
|
|
129
|
+
self.logger.debug(f"Scheduled with priority={self.priority}")
|
|
130
|
+
|
|
131
|
+
# trunk-ignore(ruff/B027)
|
|
132
|
+
def background_job(self):
|
|
133
|
+
pass # Implement in subclass if needed
|
|
134
|
+
|
|
135
|
+
def strip_raw(self, data):
|
|
136
|
+
if isinstance(data, dict):
|
|
137
|
+
data.pop("raw", None)
|
|
138
|
+
for k, v in data.items():
|
|
139
|
+
data[k] = self.strip_raw(v)
|
|
140
|
+
elif isinstance(data, list):
|
|
141
|
+
data = [self.strip_raw(item) for item in data]
|
|
142
|
+
return data
|
|
143
|
+
|
|
144
|
+
def get_response_delay(self):
|
|
145
|
+
return self.response_delay
|
|
146
|
+
|
|
147
|
+
# Modified method to accept is_direct_message parameter
|
|
148
|
+
def is_channel_enabled(self, channel, is_direct_message=False):
|
|
149
|
+
if is_direct_message:
|
|
150
|
+
return True # Always respond to DMs if the plugin is active
|
|
151
|
+
else:
|
|
152
|
+
return channel in self.channels
|
|
153
|
+
|
|
154
|
+
def get_matrix_commands(self):
|
|
155
|
+
return [self.plugin_name]
|
|
156
|
+
|
|
157
|
+
async def send_matrix_message(self, room_id, message, formatted=True):
|
|
158
|
+
from mmrelay.matrix_utils import connect_matrix
|
|
159
|
+
|
|
160
|
+
matrix_client = await connect_matrix()
|
|
161
|
+
|
|
162
|
+
return await matrix_client.room_send(
|
|
163
|
+
room_id=room_id,
|
|
164
|
+
message_type="m.room.message",
|
|
165
|
+
content={
|
|
166
|
+
"msgtype": "m.text",
|
|
167
|
+
"format": "org.matrix.custom.html" if formatted else None,
|
|
168
|
+
"body": message,
|
|
169
|
+
"formatted_body": markdown.markdown(message) if formatted else None,
|
|
170
|
+
},
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
def get_mesh_commands(self):
|
|
174
|
+
return []
|
|
175
|
+
|
|
176
|
+
def store_node_data(self, meshtastic_id, node_data):
|
|
177
|
+
data = self.get_node_data(meshtastic_id=meshtastic_id)
|
|
178
|
+
data = data[-self.max_data_rows_per_node :]
|
|
179
|
+
if isinstance(node_data, list):
|
|
180
|
+
data.extend(node_data)
|
|
181
|
+
else:
|
|
182
|
+
data.append(node_data)
|
|
183
|
+
store_plugin_data(self.plugin_name, meshtastic_id, data)
|
|
184
|
+
|
|
185
|
+
def set_node_data(self, meshtastic_id, node_data):
|
|
186
|
+
node_data = node_data[-self.max_data_rows_per_node :]
|
|
187
|
+
store_plugin_data(self.plugin_name, meshtastic_id, node_data)
|
|
188
|
+
|
|
189
|
+
def delete_node_data(self, meshtastic_id):
|
|
190
|
+
return delete_plugin_data(self.plugin_name, meshtastic_id)
|
|
191
|
+
|
|
192
|
+
def get_node_data(self, meshtastic_id):
|
|
193
|
+
return get_plugin_data_for_node(self.plugin_name, meshtastic_id)
|
|
194
|
+
|
|
195
|
+
def get_data(self):
|
|
196
|
+
return get_plugin_data(self.plugin_name)
|
|
197
|
+
|
|
198
|
+
def matches(self, event):
|
|
199
|
+
from mmrelay.matrix_utils import bot_command
|
|
200
|
+
|
|
201
|
+
# Pass the entire event to bot_command
|
|
202
|
+
return bot_command(self.plugin_name, event)
|
|
203
|
+
|
|
204
|
+
@abstractmethod
|
|
205
|
+
async def handle_meshtastic_message(
|
|
206
|
+
self, packet, formatted_message, longname, meshnet_name
|
|
207
|
+
):
|
|
208
|
+
pass # Implement in subclass
|
|
209
|
+
|
|
210
|
+
@abstractmethod
|
|
211
|
+
async def handle_room_message(self, room, event, full_message):
|
|
212
|
+
pass # Implement in subclass
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from mmrelay.plugins.base_plugin import BasePlugin
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Plugin(BasePlugin):
|
|
5
|
+
plugin_name = "debug"
|
|
6
|
+
priority = 1
|
|
7
|
+
|
|
8
|
+
async def handle_meshtastic_message(
|
|
9
|
+
self, packet, formatted_message, longname, meshnet_name
|
|
10
|
+
):
|
|
11
|
+
packet = self.strip_raw(packet)
|
|
12
|
+
|
|
13
|
+
self.logger.debug(f"Packet received: {packet}")
|
|
14
|
+
return False
|
|
15
|
+
|
|
16
|
+
async def handle_room_message(self, room, event, full_message):
|
|
17
|
+
return False
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from haversine import haversine
|
|
4
|
+
|
|
5
|
+
from mmrelay.meshtastic_utils import connect_meshtastic
|
|
6
|
+
from mmrelay.plugins.base_plugin import BasePlugin
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Plugin(BasePlugin):
|
|
10
|
+
plugin_name = "drop"
|
|
11
|
+
special_node = "!NODE_MSGS!"
|
|
12
|
+
|
|
13
|
+
def __init__(self):
|
|
14
|
+
self.plugin_name = "drop"
|
|
15
|
+
super().__init__()
|
|
16
|
+
|
|
17
|
+
def get_position(self, meshtastic_client, node_id):
|
|
18
|
+
for _node, info in meshtastic_client.nodes.items():
|
|
19
|
+
if info["user"]["id"] == node_id:
|
|
20
|
+
if "position" in info:
|
|
21
|
+
return info["position"]
|
|
22
|
+
else:
|
|
23
|
+
return None
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
async def handle_meshtastic_message(
|
|
27
|
+
self, packet, formatted_message, longname, meshnet_name
|
|
28
|
+
):
|
|
29
|
+
meshtastic_client = connect_meshtastic()
|
|
30
|
+
nodeInfo = meshtastic_client.getMyNodeInfo()
|
|
31
|
+
|
|
32
|
+
# Attempt message drop to packet originator if not relay
|
|
33
|
+
if "fromId" in packet and packet["fromId"] != nodeInfo["user"]["id"]:
|
|
34
|
+
position = self.get_position(meshtastic_client, packet["fromId"])
|
|
35
|
+
if position and "latitude" in position and "longitude" in position:
|
|
36
|
+
packet_location = (
|
|
37
|
+
position["latitude"],
|
|
38
|
+
position["longitude"],
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
self.logger.debug(f"Packet originates from: {packet_location}")
|
|
42
|
+
messages = self.get_node_data(self.special_node)
|
|
43
|
+
unsent_messages = []
|
|
44
|
+
for message in messages:
|
|
45
|
+
# You cannot pickup what you dropped
|
|
46
|
+
if (
|
|
47
|
+
"originator" in message
|
|
48
|
+
and message["originator"] == packet["fromId"]
|
|
49
|
+
):
|
|
50
|
+
unsent_messages.append(message)
|
|
51
|
+
continue
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
distance_km = haversine(
|
|
55
|
+
(packet_location[0], packet_location[1]),
|
|
56
|
+
message["location"],
|
|
57
|
+
)
|
|
58
|
+
except (ValueError, TypeError):
|
|
59
|
+
distance_km = 1000
|
|
60
|
+
radius_km = (
|
|
61
|
+
self.config["radius_km"] if "radius_km" in self.config else 5
|
|
62
|
+
)
|
|
63
|
+
if distance_km <= radius_km:
|
|
64
|
+
target_node = packet["fromId"]
|
|
65
|
+
self.logger.debug(f"Sending dropped message to {target_node}")
|
|
66
|
+
meshtastic_client.sendText(
|
|
67
|
+
text=message["text"], destinationId=target_node
|
|
68
|
+
)
|
|
69
|
+
else:
|
|
70
|
+
unsent_messages.append(message)
|
|
71
|
+
self.set_node_data(self.special_node, unsent_messages)
|
|
72
|
+
total_unsent_messages = len(unsent_messages)
|
|
73
|
+
if total_unsent_messages > 0:
|
|
74
|
+
self.logger.debug(f"{total_unsent_messages} message(s) remaining")
|
|
75
|
+
|
|
76
|
+
# Attempt to drop a message
|
|
77
|
+
if (
|
|
78
|
+
"decoded" in packet
|
|
79
|
+
and "portnum" in packet["decoded"]
|
|
80
|
+
and packet["decoded"]["portnum"] == "TEXT_MESSAGE_APP"
|
|
81
|
+
):
|
|
82
|
+
text = packet["decoded"]["text"] if "text" in packet["decoded"] else None
|
|
83
|
+
if f"!{self.plugin_name}" not in text:
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
match = re.search(r"!drop\s+(.+)$", text)
|
|
87
|
+
if not match:
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
drop_message = match.group(1)
|
|
91
|
+
|
|
92
|
+
position = {}
|
|
93
|
+
for _node, info in meshtastic_client.nodes.items():
|
|
94
|
+
if info["user"]["id"] == packet["fromId"]:
|
|
95
|
+
if "position" in info:
|
|
96
|
+
position = info["position"]
|
|
97
|
+
else:
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
if "latitude" not in position or "longitude" not in position:
|
|
101
|
+
self.logger.debug(
|
|
102
|
+
"Position of dropping node is not known. Skipping ..."
|
|
103
|
+
)
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
self.store_node_data(
|
|
107
|
+
self.special_node,
|
|
108
|
+
{
|
|
109
|
+
"location": (position["latitude"], position["longitude"]),
|
|
110
|
+
"text": drop_message,
|
|
111
|
+
"originator": packet["fromId"],
|
|
112
|
+
},
|
|
113
|
+
)
|
|
114
|
+
self.logger.debug(f"Dropped a message: {drop_message}")
|
|
115
|
+
return True
|
|
116
|
+
|
|
117
|
+
async def handle_room_message(self, room, event, full_message):
|
|
118
|
+
# Pass the event to matches() instead of full_message
|
|
119
|
+
if self.matches(event):
|
|
120
|
+
return True
|