update noisegate #9

Closed
logan wants to merge 30 commits from master into NoiseGateV2
11 changed files with 155 additions and 275 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

@@ -1,130 +0,0 @@
import pyaudio
import struct
import numpy
import time
from threading import Thread
sound_buffer = []
class AudioSteam(Thread):
def __init__(self, _channels: int = 1, _sample_rate: int = 48000, _frames_per_buffer: int = 2048,
_input_device_index: int = None, _output_device_index: int = None, _input: bool = True,
_output: bool = True):
super(AudioSteam, self).__init__()
self.paInstance_kwargs = {
'format': pyaudio.paFloat32,
'channels': _channels,
'rate': _sample_rate,
'input': _input,
'output': _output,
'frames_per_buffer': _frames_per_buffer,
'stream_callback': callback
}
if _input_device_index:
if _input:
self.paInstance_kwargs['input_device_index'] = _input_device_index
else:
print(f"[AudioStream.__init__]:\tInput was not enabled."
f" Reinitialize with '_input=True'")
if _output_device_index:
if _output:
self.paInstance_kwargs['output_device_index'] = _output_device_index
else:
print(f"[AudioStream.__init__]:\tOutput was not enabled."
f" Reinitialize with '_output=True'")
# Init PyAudio instance
self.paInstance = pyaudio.PyAudio()
# Define and initialize stream object if we have been passed a device ID (pyaudio.open)
self.stream = None
if _output_device_index and _input_device_index:
self.init_stream()
# temp section
def init_stream(self, _new_output_device_index: int = None, _new_input_device_index: int = None):
# Check what device was asked to be changed (or set)
if _new_input_device_index:
if self.paInstance_kwargs['input']:
self.paInstance_kwargs['input_device_index'] = _new_input_device_index
else:
print(f"[AudioStream.init_stream]:\tInput was not enabled when initialized."
f" Reinitialize with '_input=True'")
if _new_output_device_index:
if self.paInstance_kwargs['output']:
self.paInstance_kwargs['output_device_index'] = _new_output_device_index
else:
print(f"[AudioStream.init_stream]:\tOutput was not enabled when initialized."
f" Reinitialize with '_output=True'")
self.close_if_open()
# Reopen the stream
self.stream = self.paInstance.open(**self.paInstance_kwargs)
def close_if_open(self):
# Stop the stream if it is started
if self.stream:
if self.stream.is_active():
self.stream.stop_stream()
self.stream.close()
print(f"[ReopenStream.close_if_open]:\t Stream was open; It was closed.")
def list_devices(self, _show_input_devices: bool = True, _show_output_devices: bool = True):
info = self.paInstance.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
for i in range(0, numdevices):
if (self.paInstance.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
if _show_input_devices:
print("Input Device id ", i, " - ",
self.paInstance.get_device_info_by_host_api_device_index(0, i).get('name'))
if (self.paInstance.get_device_info_by_host_api_device_index(0, i).get('maxOutputChannels')) > 0:
if _show_output_devices:
print("Output Device id ", i, " - ",
self.paInstance.get_device_info_by_host_api_device_index(0, i).get('name'))
class NoiseGate(AudioSteam):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def run(self) -> None:
# Start the audio stream
self.stream.start_stream()
global sound_buffer
# While the stream is running, display the stream buffer in floats?
while self.stream.is_active():
if len(sound_buffer) > 0:
for buffer in sound_buffer:
volume_normalization = numpy.linalg.norm(numpy.fromstring(buffer)) * 10
print(str(float(volume_normalization)))
self.stream.stop_stream()
self.stream.close()
self.paInstance.terminate()
def callback(in_data, frame_count, time_info, status):
global sound_buffer
sound_buffer.append(in_data)
return in_data, pyaudio.paContinue
if __name__ == '__main__':
input_index = int(input("Input:\t"))
output_index = int(input("Output:\t"))
ng = NoiseGate(_input_device_index=input_index, _output_device_index=output_index)
ng.start()

View File

@@ -1,67 +0,0 @@
import threading
import time
import numpy as np
import discord
import sounddevice as sd
from threading import Thread, Event
noise_gate_trigger = 0 # Set this value for the trigger on the noise-gate
voice_connection = None
audio_stream = None
last_callback_value = 0
class NoiseGate(Thread):
def __init__(self, trigger_value: int = 700):
global noise_gate_trigger
super(NoiseGate, self).__init__()
self.stream = None
self.stop_NG = threading.Event()
self.NG_Started = threading.Event()
noise_gate_trigger = trigger_value
def init_stream(self, num, _voice_connection, _audio_stream):
global voice_connection, audio_stream
self.stream = sd.InputStream(device=num, callback=stream_callback)
voice_connection = _voice_connection
audio_stream = _audio_stream
def run(self) -> None:
self.NG_Started.set()
self.stream.start()
while not self.stop_NG.is_set():
#print("Main loop start")
if last_callback_value >= noise_gate_trigger:
trigger_noise_gate(True)
while last_callback_value >= noise_gate_trigger:
time.sleep(6)
trigger_noise_gate(False)
#print("Main loop end")
self.stream.stop()
self.stream.close()
self.NG_Started.clear()
voice_connection.stop()
print('Thread #%s stopped' % self.ident)
def stream_callback(indata, *args):
global last_callback_value
volume_normalization = np.linalg.norm(indata) * 10
last_callback_value = int(volume_normalization)
#print(f"Callback Value: {last_callback_value}")
def trigger_noise_gate(triggered: bool):
if triggered:
if not voice_connection.is_playing():
voice_connection.play(discord.PCMAudio(audio_stream))
# print("|" * int(volume_normalization / 4))
print("Noise Gate was Triggered")
#time.sleep(10)
else:
if voice_connection.is_playing():
print("Noise Gate stopped")
voice_connection.pause()
# try disconnecting and reconnecting

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