Update Noisegate Branch #7
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,8 +1,7 @@
|
||||
/.idea/
|
||||
/Releases/
|
||||
/Old/
|
||||
/__pycache__/
|
||||
*/__pycache__/
|
||||
**/__pycache__/
|
||||
/venv/
|
||||
*.7z
|
||||
*.bat
|
||||
|
||||
@@ -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
|
||||
|
||||
130
NoiseGate-v2.py
130
NoiseGate-v2.py
@@ -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()
|
||||
67
NoiseGate.py
67
NoiseGate.py
@@ -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
|
||||
4
TODO.md
4
TODO.md
@@ -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
|
||||
|
||||
17
bot.py
17
bot.py
@@ -2,7 +2,6 @@ import asyncio
|
||||
import os
|
||||
import platform
|
||||
import discord
|
||||
|
||||
import BotResources
|
||||
import sound
|
||||
import configparser
|
||||
@@ -254,10 +253,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 +268,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:
|
||||
@@ -481,13 +476,3 @@ class Bot(commands.Bot):
|
||||
message_body += f"Squelch: {self.squelch}"
|
||||
|
||||
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
|
||||
|
||||
@@ -43,6 +43,7 @@ class GQRXHandler():
|
||||
tel_conn.close()
|
||||
|
||||
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
34
main.py
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
24
modules/ModuleProbe/cog.py
Normal file
24
modules/ModuleProbe/cog.py
Normal 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))
|
||||
@@ -2,6 +2,7 @@ import threading
|
||||
import subprocess
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
|
||||
|
||||
class OP25Handler: #(threading.Thread):
|
||||
@@ -12,12 +13,16 @@ class OP25Handler: #(threading.Thread):
|
||||
|
||||
self.Frequency = None
|
||||
|
||||
self.HTTP_ENABLED = False
|
||||
|
||||
def start(self) -> None:
|
||||
self.open_op25()
|
||||
|
||||
def set_op25_parameters(self, _frequency):
|
||||
def set_op25_parameters(self, _frequency, _http_enabled: bool = True):
|
||||
self.Frequency = _frequency
|
||||
|
||||
self.HTTP_ENABLED = _http_enabled
|
||||
|
||||
def open_op25(self):
|
||||
if self.OP25Proc is not None:
|
||||
self.close_op25()
|
||||
@@ -25,15 +30,17 @@ 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"])
|
||||
|
||||
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"])
|
||||
|
||||
os.chdir(cwd)
|
||||
|
||||
@@ -48,7 +55,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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user