Merge branch 'master' into NoiseGateV2

This commit is contained in:
Logan Cusano
2022-03-20 03:15:37 -04:00
9 changed files with 155 additions and 78 deletions

3
.gitignore vendored
View File

@@ -1,8 +1,7 @@
/.idea/
/Releases/
/Old/
/__pycache__/
*/__pycache__/
**/__pycache__/
/venv/
*.7z
*.bat

View File

@@ -191,3 +191,14 @@ def check_negative(s):
return False
except ValueError:
return False
# Check if message is a ping request and respond even if it is a bot
async def check_and_reply_to_ping(bot, message):
if "check_modules" in message.content:
ctx = await bot.get_context(message)
await bot.invoke(ctx)
return True
else:
await bot.process_commands(message)
return False

View File

@@ -4,8 +4,8 @@
- *May* have been fixed with the noise gate?
- [ ] Fix bug that shows different index number for audio device selection on linux
- [x] Add more proper help text with real examples for discord commands
- [ ] Add command line args with argparse for main bot
- [ ] Add method for user to change audio device without redoing entire config file
- [x] Add command line args with argparse for main bot
- [x] Add method for user to change audio device without redoing entire config file
- [ ] Clean up code
- [ ] Transcode radio transmissions to text
### Modules

66
bot.py
View File

@@ -2,7 +2,6 @@ import asyncio
import os
import platform
import discord
import BotResources
import sound
import configparser
@@ -64,11 +63,16 @@ class Bot(commands.Bot):
# Add discord commands to the bot
def add_commands(self):
# Test command to see if the bot is on (help command can also be used)
@self.command(help="Use this to test if the bot is alive", brief="Sends a 'pong' in response")
async def ping(ctx):
if ctx.author.id != self.user.id:
await ctx.send('pong')
# Command to display what channel the bot is in
@self.command(help="Use this command to display what channel the bot is in",
brief="Where ya at?")
async def wya(ctx, member: discord.Member = None):
member = member or ctx.author.display_name
if self.Bot_Connected:
await ctx.send(f"Hey {str(member).capitalize()}, I'm in {ctx.voice_client.channel}")
else:
await ctx.send(f"{str(member).capitalize()}, I am not in any channel.")
# Command to join the bot the voice channel the user who called the command is in
@self.command(help="Use this command to join the bot to your channel",
@@ -147,16 +151,27 @@ class Bot(commands.Bot):
# Add commands for GQRX and OP25
if self.Handler in BotResources.PDB_ACCEPTABLE_HANDLERS.keys():
# Command to display the current config
@self.command(name='displayprofile',
@self.command(name='displaycurprofile',
help="Use this command to display the current configuration of the bot.\n"
"Example command:\n"
"\t@ displayprofile",
"\t@ displaycurprofile",
breif="Display current bot config")
async def _displayprofile(ctx, member: discord.Member = None):
async def _displaycurprofile(ctx, member: discord.Member = None):
member = member or ctx.author.display_name
message = self.display_current_radio_config()
await ctx.send(f"Ok {str(member).capitalize()},\n{message}")
# Command to display the current config
@self.command(name='displayprofiles',
help="Use this command to display the saved profiles.\n"
"Example command:\n"
"\t@ displayprofiles",
breif="Display current bot config")
async def _displayprofiles(ctx, member: discord.Member = None):
member = member or ctx.author.display_name
message = self.display_saved_radio_configs()
await ctx.send(f"Ok {str(member).capitalize()},\n{message}")
# Command to change the current frequency and mode
@self.command(name='chfreq', help="Use this command to change the frequency the bot is listening to.\n"
"Example GQRX command:\n"
@@ -254,10 +269,6 @@ class Bot(commands.Bot):
await self.check_for_modules()
print("Bot started!")
@self.event
async def on_message(message):
await self.check_and_reply_to_ping(message)
# Check to see if other bots are online
async def check_other_bots_online(self):
print('Checking if other bots are online')
@@ -273,7 +284,7 @@ class Bot(commands.Bot):
await self.wait_until_ready()
# Send the ping command with the prefix the current bot is using
await channel.send(f"{self.Command_Prefix}ping")
await channel.send(f"{self.Command_Prefix}check_modules")
seconds_waited = 0
while seconds_waited < 3:
@@ -301,6 +312,7 @@ class Bot(commands.Bot):
print("Starting OP25 handler")
from op25Handler import OP25Handler
self.OP25Handler = OP25Handler()
self.OP25Handler.start()
self.possible_modes = BotResources.PDB_ACCEPTABLE_HANDLERS['op25']['Modes']
# Load the proper OPUS library for the device being used
@@ -388,8 +400,7 @@ class Bot(commands.Bot):
self.GQRXHandler.set_all_settings(self.mode, self.squelch, self.freq)
elif self.Handler == 'op25':
self.OP25Handler.set_op25_parameters(self.freq)
self.OP25Handler.start()
self.OP25Handler.set_op25_parameters(self.freq, _start=True)
# Set the started variable for later checks
self.sdr_started = True
@@ -400,7 +411,7 @@ class Bot(commands.Bot):
# Wait for the running processes to close
# Close the OP25 handler
if self.Handler == 'op25':
self.OP25Handler.close_op25()
self.OP25Handler.set_op25_parameters(_stop=True)
# self.OP25Handler.join()
# Need a way to 'close' GQRX
self.sdr_started = False
@@ -482,12 +493,15 @@ class Bot(commands.Bot):
return message_body
# Check if message is a ping request and respond even if it is a bot
async def check_and_reply_to_ping(self, message):
if "ping" in message.content:
ctx = await self.get_context(message)
await self.invoke(ctx)
return True
else:
await self.process_commands(message)
return False
def display_saved_radio_configs(self):
message_body = f"Saved configs\n"
config = configparser.ConfigParser()
if os.path.exists('./profiles.ini'):
config.read('./profiles.ini')
for section in config.sections():
message_body += f"\n{section}:\n" \
f"\tMode:\t\t\t\t{config[section]['Mode']}\n" \
f"\tFrequency:\t\t{config[section]['Frequency']}\n" \
f"\tSquelch:\t\t\t{config[section]['Squelch']}\n"
return message_body

View File

@@ -7,42 +7,34 @@ class GQRXHandler():
self.hostname = hostname
self.port = port
self.telnet_connection = None
self.tel_conn = None
self.create_telnet_connection()
def create_telnet_connection(self):
print("Creating connection")
tel_conn = Telnet(self.hostname, self.port)
tel_conn.open(self.hostname, self.port)
return tel_conn
self.tel_conn = Telnet(self.hostname, self.port)
self.tel_conn.open(self.hostname, self.port)
def change_freq(self, freq):
tel_conn = self.create_telnet_connection()
print(f"Changing freq to {freq}")
tel_conn.write(bytes(f"F {int(freq)}", 'utf-8'))
sleep(1)
tel_conn.close()
self.tel_conn.write(bytes(f"F {int(freq)}", 'utf-8'))
self.tel_conn.read_until(b'RPRT 0')
def change_squelch(self, squelch):
tel_conn = self.create_telnet_connection()
if not check_negative(squelch):
squelch = float(-abs(squelch))
print(f"Changing squelch to {squelch}")
tel_conn.write(bytes(f"L SQL {float(squelch)}", 'utf-8'))
sleep(1)
tel_conn.close()
self.tel_conn.write(bytes(f"L SQL {float(squelch)}", 'utf-8'))
self.tel_conn.read_until(b'RPRT 0')
def change_mode(self, mode):
tel_conn = self.create_telnet_connection()
print(f"Changing mode to {mode}")
tel_conn.write(bytes(f"M {str(mode)}", 'utf-8'))
sleep(1)
tel_conn.close()
self.tel_conn.write(bytes(f"M {str(mode)}", 'utf-8'))
self.tel_conn.read_until(b'RPRT 0')
def set_all_settings(self, mode, squelch, freq):
self.change_squelch(0)
self.change_mode(mode)
self.change_freq(freq)
self.change_squelch(squelch)

34
main.py
View File

@@ -27,18 +27,21 @@ class BotDeviceNotFound(Exception):
def main(**passed_config):
print('Checking config file...')
if not check_if_config_exists():
print("No config file exists, please enter this information now")
write_config_file(init=True)
# Don't create a config if the user passed parameters
if len(passed_config.keys()) == 0:
print('Checking config file...')
if not check_if_config_exists():
print("No config file exists, please enter this information now")
write_config_file(init=True)
config = read_config_file()
# Overwrite config options if they were passed
for sub in config:
# checking if key present in other dictionary
if sub in passed_config and passed_config[sub]:
config[sub] = passed_config[sub]
if len(passed_config.keys()) == 0:
for sub in config:
# checking if key present in other dictionary
if sub in passed_config and passed_config[sub]:
config[sub] = passed_config[sub]
print('Starting Bot...')
@@ -106,20 +109,21 @@ def cmd_arguments():
return args
if __name__ == '__main__':
args = cmd_arguments()
if not all(args.values()):
if __name__ == '__main__':
cmd_args = cmd_arguments()
if not all(cmd_args.values()):
print("Passed arguments:")
for arg in args:
if args[arg]:
print(f"\t{arg}:\t{args[arg]}")
for arg in cmd_args:
if cmd_args[arg]:
print(f"\t{arg}:\t{cmd_args[arg]}")
try:
print('Starting...')
while True:
try:
main(**args)
main(**cmd_args)
except BotDeviceNotFound:
print("Restarting...")
time.sleep(2)

View File

@@ -2,7 +2,7 @@ import re
import discord
from discord.ext import commands
import random
from BotResources import PDB_KNOWN_BOT_IDS
from BotResources import PDB_KNOWN_BOT_IDS, check_and_reply_to_ping
regex_link = re.compile('(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)')
@@ -71,7 +71,7 @@ class LinkCop(commands.Cog):
print(f"Link Cop Error: '{err}'")
print(f"Bot or other non-user that has not been whitelisted sent a message")
await self.bot.check_and_reply_to_ping(ctx)
await check_and_reply_to_ping(self.bot, ctx)
async def send_message(self, message):
send_channel = self.bot.get_channel(id=self.reply_channel_id)

View File

@@ -0,0 +1,24 @@
from discord.ext import commands
from BotResources import check_and_reply_to_ping
class ModuleProbe(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.channel_id = 767303243285790721
self.add_events()
def add_events(self):
@self.bot.event
async def on_message(message):
await check_and_reply_to_ping(self.bot, message)
@commands.command(help="This command is used by other bots to test if there are any bots online with modules.")
async def check_modules(self, ctx):
if ctx.author.id != self.bot.user.id:
await ctx.send('pong')
def setup(bot: commands.Bot):
bot.add_cog(ModuleProbe(bot))

View File

@@ -2,9 +2,10 @@ import threading
import subprocess
import asyncio
import os
import time
class OP25Handler: #(threading.Thread):
class OP25Handler(threading.Thread):
def __init__(self):
super().__init__()
self.OP25Dir: str = "/home/pi/op25/op25/gr-op25_repeater/apps"
@@ -12,11 +13,39 @@ class OP25Handler: #(threading.Thread):
self.Frequency = None
def start(self) -> None:
self.open_op25()
self.HTTP_ENABLED = False
def set_op25_parameters(self, _frequency):
self.Frequency = _frequency
self.Start_OP25 = False
self.Stop_OP25 = False
def run(self) -> None:
while True:
if self.Start_OP25:
self.open_op25()
self.Start_OP25 = False
self.Stop_OP25 = False
while not self.Stop_OP25:
time.sleep(1)
self.close_op25()
time.sleep(.5)
def set_op25_parameters(self, _frequency: str = False, _http_enabled: bool = True, _start: bool = False, _stop: bool = False):
if _frequency:
self.Frequency = _frequency
if _start:
self.Start_OP25 = _start
if _stop:
self.Stop_OP25 = _stop
if _http_enabled:
self.HTTP_ENABLED = _http_enabled
def open_op25(self):
if self.OP25Proc is not None:
@@ -25,15 +54,19 @@ class OP25Handler: #(threading.Thread):
print(f"Starting OP25")
cwd = os.getcwd()
print(cwd)
os.chdir(self.OP25Dir)
print(os.getcwd())
if self.HTTP_ENABLED:
self.OP25Proc = subprocess.Popen([f"./rx.py", "--args", "rtl", "-N", "LNA:49", "-s",
"200000", "-o", "25600", "-U", "-f", f"{self.Frequency}e6", "-X", "-2",
"-l" "http:0.0.0.0:8080"], shell=False, stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
self.OP25Proc = subprocess.Popen([f"./rx.py", "--args", "rtl", "-N", "LNA:49", "-s",
"200000", "-o", "25600", "-U", "-f", f"{self.Frequency}e6", "-X", "-2",
"-l" "http:0.0.0.0:8080"])
else:
self.OP25Proc = subprocess.Popen([f"./rx.py", "--args", "rtl", "-N", "LNA:49", "-s",
"200000", "-o", "25600", "-U", "-f", f"{self.Frequency}e6", "-X", "-2"],
shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
os.chdir(cwd)
@@ -48,7 +81,7 @@ class OP25Handler: #(threading.Thread):
if seconds_waited % 5 == 0:
print("Terminating OP25")
self.OP25Proc.terminate()
asyncio.sleep(1000)
time.sleep(1)
print(f"Waited {seconds_waited} seconds")
seconds_waited += 1