120 Commits

Author SHA1 Message Date
d97e51d960 Merge pull request 'Noisegate V2' (#8) from NoiseGateV2 into master
Reviewed-on: http://git.vpn.cusano.net/Discord_Bot_Gang/Discord-Radio-Bot/pulls/8
2022-03-28 00:13:06 -04:00
Logan Cusano
8c5cc65a50 no new line at the end of display profiles 2022-03-27 15:05:46 -04:00
Logan Cusano
63ca0fec63 silly bug 2022-03-27 15:04:55 -04:00
Logan Cusano
8e191531d0 Reads profiles without noisegate sensitivity value 2022-03-27 15:03:41 -04:00
Logan Cusano
83c2971742 No spaces in profiles 2022-03-27 15:00:58 -04:00
Logan Cusano
1a705c2b6c KeyError instead of NameError ~507 bot.py 2022-03-27 14:56:56 -04:00
Logan Cusano
3a2d9531f9 Removing circular import 2022-03-27 14:55:11 -04:00
Logan Cusano
54e3a3a116 Remove dupe file 2022-03-27 14:50:42 -04:00
Logan Cusano
0d32d3fa7e rebase master into NoiseGateV2 2022-03-27 14:48:42 -04:00
Logan Cusano
05e81aea1d Better output 2022-03-27 14:48:40 -04:00
Logan Cusano
69c7d4d548 idk 2022-03-27 14:48:39 -04:00
Logan Cusano
79c651be30 idk 2022-03-27 14:48:38 -04:00
Logan Cusano
4eb73c3832 idk 2022-03-27 14:48:37 -04:00
Logan Cusano
f90c84184a idk 2022-03-27 14:48:36 -04:00
Logan Cusano
831c19e7e1 idk 2022-03-27 14:48:34 -04:00
Logan Cusano
97aed314ba idk 2022-03-27 14:48:33 -04:00
Logan Cusano
f64a3dc517 idk 2022-03-27 14:48:32 -04:00
Logan Cusano
5d7a3b2d0b idk 2022-03-27 14:48:31 -04:00
Logan Cusano
0c53e58fab idk 2022-03-27 14:48:30 -04:00
Logan Cusano
8c7075b76c idk 2022-03-27 14:48:28 -04:00
Logan Cusano
dd9643363b idk 2022-03-27 14:48:27 -04:00
Logan Cusano
7cca55a836 Trying to use pipe 2022-03-27 14:48:26 -04:00
Logan Cusano
5fe98bfe0e Trying to use stdin, executable and shell 2022-03-27 14:48:25 -04:00
Logan Cusano
6049af3a25 Trying to use stdout/stderr 2022-03-27 14:48:24 -04:00
Logan Cusano
c03521de7f Using a list with extend instead of append 2022-03-27 14:48:22 -04:00
Logan Cusano
e5b3359571 Using a list with extend instead of append 2022-03-27 14:48:21 -04:00
Logan Cusano
492026ed8c Using a list with extend instead of append 2022-03-27 14:48:20 -04:00
Logan Cusano
61f113c475 Using a list with extend instead of append 2022-03-27 14:48:19 -04:00
Logan Cusano
bbe461255a idk 2022-03-27 14:48:18 -04:00
Logan Cusano
7d161baeda no space in debug emendation 2022-03-27 14:48:16 -04:00
Logan Cusano
f68e794d02 popen needs string? 2022-03-27 14:48:15 -04:00
Logan Cusano
9986eadaaf popen needs string? 2022-03-27 14:48:14 -04:00
Logan Cusano
404ddfc773 Updated p25 opening 2022-03-27 14:48:13 -04:00
Logan Cusano
f94a900c44 Added profile commands for the bot 2022-03-27 14:43:33 -04:00
Logan Cusano
721ef932ce Better output 2022-03-27 14:18:16 -04:00
Logan Cusano
4ab14d2e5d idk 2022-03-27 14:08:53 -04:00
Logan Cusano
9635e11434 idk 2022-03-27 14:06:36 -04:00
Logan Cusano
8fa42d819a idk 2022-03-27 14:03:40 -04:00
Logan Cusano
5a8efa8884 idk 2022-03-27 14:01:49 -04:00
Logan Cusano
e0dba3be4e idk 2022-03-27 13:52:37 -04:00
Logan Cusano
4e839eecb4 idk 2022-03-27 13:50:24 -04:00
Logan Cusano
81dc305197 idk 2022-03-27 13:49:02 -04:00
Logan Cusano
203bee0734 idk 2022-03-27 13:48:07 -04:00
Logan Cusano
7e2cf932dc idk 2022-03-27 13:46:44 -04:00
Logan Cusano
102e0ae473 idk 2022-03-27 13:43:52 -04:00
Logan Cusano
33ea596ab4 idk 2022-03-27 13:40:00 -04:00
Logan Cusano
f965c5de05 Trying to use pipe 2022-03-27 13:32:49 -04:00
Logan Cusano
0bc0d8e031 Trying to use stdin, executable and shell 2022-03-27 13:29:15 -04:00
Logan Cusano
92ab4992cb Trying to use stdout/stderr 2022-03-27 13:19:29 -04:00
Logan Cusano
da29c0eaaa Using a list with extend instead of append 2022-03-27 13:12:25 -04:00
Logan Cusano
30d539312e Using a list with extend instead of append 2022-03-27 13:03:00 -04:00
Logan Cusano
9a225010be Using a list with extend instead of append 2022-03-27 13:00:31 -04:00
Logan Cusano
92bd4ffb1f Using a list with extend instead of append 2022-03-27 12:49:08 -04:00
Logan Cusano
bf8adda80b idk 2022-03-27 05:20:00 -04:00
Logan Cusano
f239e87b0a no space in debug emendation 2022-03-27 05:18:23 -04:00
Logan Cusano
136009c07e popen needs string? 2022-03-27 05:17:03 -04:00
Logan Cusano
5efb44164a popen needs string? 2022-03-27 05:11:49 -04:00
Logan Cusano
6fd30b9609 Updated p25 opening 2022-03-27 04:37:29 -04:00
Logan Cusano
c1084deadf Update requirements from Dan's Update 2022-03-27 01:24:36 -04:00
Logan Cusano
cf79050b96 Possible fix for Nonetype error on Greada 2022-03-27 01:16:53 -04:00
Logan Cusano
22d6d5d3d7 Added a function to allow users to change the noisegate threshold 2022-03-27 01:15:17 -04:00
Logan Cusano
24adc47109 Dan's Update
- New classes for noisegate & audio stream
- Ability to manipulate raw data in real-time
2022-03-27 00:50:42 -04:00
Logan Cusano
0329ff7a81 New attempt 2022-03-26 03:07:24 -04:00
Logan Cusano
48f6812f68 Printing volume value 2022-03-26 02:42:42 -04:00
Logan Cusano
b444236dc9 Printing volume value 2022-03-26 02:39:08 -04:00
Logan Cusano
287eb0e981 Merge remote-tracking branch 'origin/NoiseGateV2' into NoiseGateV2 2022-03-26 02:34:39 -04:00
Logan Cusano
7a9dbfb53a Actually connecting the noisegate 2022-03-26 02:34:01 -04:00
Logan Cusano
a13cf36e15 Actually connecting the noisegate 2022-03-26 02:24:06 -04:00
Logan Cusano
465c0e00ea Added noisegate to the 'sound' file and integrated it with its function 2022-03-26 01:35:02 -04:00
Logan Cusano
12aa4d6f51 Merge branch 'master' into NoiseGateV2 2022-03-20 03:15:37 -04:00
Logan Cusano
2dacab263b Rename to resolve conflict 2022-03-20 03:05:33 -04:00
Logan Cusano
126ba907af Testing OP25 Improvements
- New system of handling thread
2022-03-19 01:18:45 -04:00
Logan Cusano
4f230f8d33 Testing OP25 Improvements
- Introduced threading (again..)
2022-03-19 00:46:13 -04:00
Logan Cusano
1257b713fc Testing OP25 Improvements
- Disabled shell
2022-03-19 00:39:10 -04:00
Logan Cusano
4f7ec14807 Testing OP25 Improvements
- Changed output to be ignored
2022-03-19 00:32:03 -04:00
Logan Cusano
ec7880ed1e Testing OP25 Improvements 2022-03-19 00:27:55 -04:00
Logan Cusano
e4cb8647ee Replaced arbitrary sleep with a wait until response on all functions 2022-03-19 00:19:02 -04:00
Logan Cusano
a205bd2d8a BUG; Used string, not byte string 2022-03-19 00:17:36 -04:00
Logan Cusano
8355b98da5 Replaced arbitrary sleep with a wait until response 2022-03-19 00:16:24 -04:00
Logan Cusano
c3fb20f12e Increased sleep time 2022-03-19 00:07:06 -04:00
Logan Cusano
5ebbaca54b GQRX bug; Never created connection 2022-03-17 23:30:40 -04:00
Logan Cusano
efe8eda66f Improved GQRX handler speed 2022-03-17 23:28:59 -04:00
Logan Cusano
9f4473ffcc Improved the display of profiles 2022-03-17 23:21:29 -04:00
Logan Cusano
759f05eb0c Improved the display of profiles 2022-03-17 23:18:17 -04:00
Logan Cusano
0d51b47146 BUGFIX in display all profiles 2022-03-17 23:15:02 -04:00
Logan Cusano
ff26cbc0b1 Removed ping in favor of 'ModuleProbe' module 2022-03-17 23:13:07 -04:00
Logan Cusano
9456b91d09 Added WYA command to display where the bot is 2022-03-17 23:10:13 -04:00
Logan Cusano
b534e2b731 Typo 2022-03-17 22:41:37 -04:00
fdeb337ca5 Merge branch 'NoiseGateV2' into master 2022-03-17 16:52:12 -04:00
Logan Cusano
56a3bdd0ea Default the OP25 HTTP server to enabled, caused issues with the shell with it disabled.
Need to look into perhaps using the `shell=True` parameter
2022-03-17 00:12:15 -04:00
Logan Cusano
830d299a01 Update gitignore to ignore all pycache folders 2022-03-17 00:09:39 -04:00
676969a8fe Merge pull request 'Moved the startup ping response to a module, so it will only reply if the modules are enabled' (#6) from ModuleProbe into master
Reviewed-on: http://git.vpn.cusano.net/Discord_Bot_Gang/Discord-Radio-Bot/pulls/6
2022-03-17 00:00:46 -04:00
Logan Cusano
760ebd7e43 Added a call to set squelch to 0 as all settings are being changed, so there is no sudden burst of noise 2022-03-16 23:59:42 -04:00
Logan Cusano
c564a145b5 Moved the startup ping response to a module, so it will only reply if the modules are enabled 2022-03-16 23:52:17 -04:00
Logan Cusano
db0922bf68 Updated TODO 2022-03-16 02:20:47 -04:00
Logan Cusano
897e53d4c0 Changed the order of operations on boot so squelch is changed first 2022-03-16 02:20:35 -04:00
Logan Cusano
a1f9869e8e Undo revert 2022-03-16 01:34:02 -04:00
Logan Cusano
73fa560040 Removed noisegate (again) 2022-03-16 01:29:09 -04:00
Logan Cusano
1f30e05e46 Revert "Cleanup"
This reverts commit 78d9b9e307.
2022-03-16 01:26:24 -04:00
Logan Cusano
56ee57e96a Merge remote-tracking branch 'origin/master' 2022-03-16 01:15:47 -04:00
Logan Cusano
5cc8a8c118 Changed to sync sleep 2022-03-16 01:15:22 -04:00
26909bce0f Merge pull request 'Merge from master' (#5) from master into NoiseGateV2
Reviewed-on: http://git.vpn.cusano.net/Discord_Bot_Gang/Discord-Radio-Bot/pulls/5
2022-02-27 21:47:07 -05:00
fc1a742933 Merge branch 'NoiseGateV2' into master 2022-02-27 21:46:31 -05:00
Logan Cusano
78d9b9e307 Cleanup 2022-02-27 21:43:28 -05:00
Logan Cusano
ba237d2d53 Working on bug in leaving 2022-02-27 19:09:48 -05:00
Logan Cusano
6ad489183f Working on bug in leaving 2022-02-27 19:01:52 -05:00
Logan Cusano
b721fa3df4 Working on bug in leaving 2022-02-27 19:00:55 -05:00
Logan Cusano
7682d8c72c Working on bug in leaving 2022-02-27 18:44:02 -05:00
Logan Cusano
706f4a31df Working on bug in leaving 2022-02-27 18:40:36 -05:00
Logan Cusano
7fa11a4abe Working on bug in leaving 2022-02-27 18:36:18 -05:00
Logan Cusano
17c528c153 Working on bug in leaving 2022-02-27 17:29:08 -05:00
Logan Cusano
f9594e2afe Error catching
- PCMStream.clean_up
- PCMStream.read
2022-02-27 17:25:10 -05:00
Logan Cusano
167c06f331 Error catching
- PCMStream.clean_up
- PCMStream.read
2022-02-27 17:21:53 -05:00
Logan Cusano
137d0ae097 Error catching for cleaning up 2022-02-27 17:17:23 -05:00
Logan Cusano
002288d632 Error catching for cleaning up 2022-02-27 17:14:31 -05:00
Logan Cusano
59a3ca22ea Debug output for leaving 2022-02-27 17:11:59 -05:00
Logan Cusano
fdb9bb519c Grammar fix
Comma in `Ok <member>*,*\n<message>`
2022-02-27 17:09:06 -05:00
Logan Cusano
a5f0a4b193 BUGFIX appending to dict, fixed 2022-02-27 16:30:38 -05:00
Logan Cusano
62968654d2 v2.0.1
- Args
- Better configs
- Other shit too, idr
2022-02-27 13:40:21 -05:00
Logan Cusano
a3a592d854 New Noisegate attempt 2022-02-14 20:13:23 -05:00
15 changed files with 555 additions and 283 deletions

3
.gitignore vendored
View File

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

View File

@@ -1,9 +1,16 @@
import sound
import configparser
from os.path import exists
from NoiseGatev2 import AudioStream
PDB_ACCEPTABLE_HANDLERS = ['gqrx', 'op25']
PDB_KNOWN_BOT_IDS = [756327271597473863, 915064996994633729, 943742040255115304]
PDB_ACCEPTABLE_HANDLERS = {'gqrx': {
'Modes': ['wfm', 'fm']
},
'op25': {
'Modes': ['d', 'p25']
}}
PDB_KNOWN_BOT_IDS = {756327271597473863: "Greada", 915064996994633729: "Jorn", 943742040255115304: "Brent"}
DEFAULT_NOISEGATE_THRESHOLD = 50
def check_if_config_exists():
@@ -172,7 +179,8 @@ def get_handler():
handler = str(input(f"Please enter the name of the handler you would like to use:\t"))
if handler in PDB_ACCEPTABLE_HANDLERS:
return handler
elif handler == '':
elif handler == ['', "none"]:
handler = "None"
return handler
@@ -185,3 +193,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,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

185
NoiseGatev2.py Normal file
View File

@@ -0,0 +1,185 @@
import audioop
import math
import pyaudio
import discord
import numpy
voice_connection = None
class AudioStream:
def __init__(self, _channels: int = 2, _sample_rate: int = 48000, _frames_per_buffer: int = 1024,
_input_device_index: int = None, _output_device_index: int = None, _input: bool = True,
_output: bool = True, _init_on_startup: bool = True):
self.paInstance_kwargs = {
'format': pyaudio.paInt16,
'channels': _channels,
'rate': _sample_rate,
'input': _input,
'output': _output,
'frames_per_buffer': _frames_per_buffer
}
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'")
if _init_on_startup:
# Init PyAudio instance
print("Creating 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 or _input_device_index:
if _init_on_startup:
print("Init stream")
self.init_stream()
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()
# Open 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, _display_input_devices: bool = True, _display_output_devices: bool = True):
info = self.paInstance.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
devices = {
'Input': {},
'Output': {}
}
for i in range(0, numdevices):
if (self.paInstance.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
input_device = self.paInstance.get_device_info_by_host_api_device_index(0, i).get('name')
devices['Input'][i] = input_device
if _display_input_devices:
print("Input Device id ", i, " - ", input_device)
if (self.paInstance.get_device_info_by_host_api_device_index(0, i).get('maxOutputChannels')) > 0:
output_device = self.paInstance.get_device_info_by_host_api_device_index(0, i).get('name')
devices['Output'][i] = output_device
if _display_output_devices:
print("Output Device id ", i, " - ", output_device)
return devices
async def stop(self):
await voice_connection.disconnect()
self.close_if_open()
self.stream.close()
self.paInstance.terminate()
class NoiseGate(AudioStream):
def __init__(self, _voice_connection, _noise_gate_threshold: int, **kwargs):
super(NoiseGate, self).__init__(_init_on_startup=True, **kwargs)
global voice_connection
voice_connection = _voice_connection
self.THRESHOLD = _noise_gate_threshold
self.NGStream = NoiseGateStream(self)
def run(self) -> None:
global voice_connection
# Start the audio stream
self.stream.start_stream()
voice_connection.play(self.NGStream)
async def close(self):
await voice_connection.disconnect()
if self.stream.is_active:
self.stream.stop_stream()
class NoiseGateStream(discord.AudioSource):
def __init__(self, _stream):
super(NoiseGateStream, self).__init__()
self.stream = _stream # The actual audio stream object
self.NG_fadeout = 480/20 # Fadeout value used to hold the noisegate after de-triggering
self.NG_fadeout_count = 0 # A count set when the noisegate is triggered and was de-triggered
self.process_set_count = 0 # Counts how many processes have been made in order to limit the prints
def read(self):
try:
while voice_connection.is_connected():
curr_buffer = bytearray(self.stream.stream.read(960))
buffer_rms = audioop.rms(curr_buffer, 2)
if buffer_rms > 0:
buffer_decibel = 20 * math.log10(buffer_rms)
if self.process_set_count % 10 == 0:
print(f"{buffer_decibel} db")
if buffer_decibel >= self.stream.THRESHOLD:
self.NG_fadeout_count = self.NG_fadeout
self.process_set_count += 1
if curr_buffer:
return bytes(curr_buffer)
else:
if self.NG_fadeout_count > 0:
self.NG_fadeout_count -= 1
print(f"Frames in fadeout remaining: {self.NG_fadeout_count}")
self.process_set_count += 1
if curr_buffer:
return bytes(curr_buffer)
except OSError as e:
pass
def audio_datalist_set_volume(self, datalist, volume):
""" Change value of list of audio chunks """
sound_level = (volume / 100.)
for i in range(len(datalist)):
chunk = numpy.fromstring(datalist[i], numpy.int16)
chunk = chunk * sound_level
datalist[i] = chunk.astype(numpy.int16)
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.list_devices()
ng.start()

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

267
bot.py
View File

@@ -2,10 +2,9 @@ import asyncio
import os
import platform
import discord
import BotResources
import sound
import configparser
import NoiseGatev2
from discord.ext import commands
@@ -34,13 +33,16 @@ class Bot(commands.Bot):
self.Bot_Connected = False
# Init the audio devices list
self.Devices_List = sound.query_devices().items()
#self.Devices_List = sound.query_devices().items()
self.Devices_List = NoiseGatev2.AudioStream().list_devices(_display_input_devices=False,
_display_output_devices=False)
# Init radio parameters
self.profile_name = None
self.freq = "104700000"
self.mode = "wfm"
self.squelch = 0
self.noisegate_sensitivity = BotResources.DEFAULT_NOISEGATE_THRESHOLD
# Init SDR Variables
self.system_os_type = None
@@ -64,17 +66,23 @@ 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",
brief="Joins the voice channel that the caller is in")
async def join(ctx, *, member: discord.Member = None):
member = member or ctx.author.display_name
print(f"Join requested by {member}")
if not self.Bot_Connected:
# Wait for the bot to be ready to connect
@@ -85,52 +93,108 @@ class Bot(commands.Bot):
if discord.opus.is_loaded():
channel = ctx.author.voice.channel
print("Sending hello")
await ctx.send(f"Ok {str(member).capitalize()}, I'm joining {channel}")
# Join the voice channel with the audio stream
print('Joining')
voice_connection = await channel.connect()
# Create an audio stream from selected device
self.streamHandler = sound.PCMStream()
# Ensure the selected device is available and start the audio stream
self.streamHandler.change_device(self.DEVICE_ID)
# Play the stream
voice_connection.play(discord.PCMAudio(self.streamHandler))
print("Starting noisegate/stream handler")
self.streamHandler = NoiseGatev2.NoiseGate(_input_device_index=self.DEVICE_ID,
_voice_connection=voice_connection,
_noise_gate_threshold=self.noisegate_sensitivity)
# Start the audio stream
self.streamHandler.run()
# Start the SDR and begin playing to the audio stream
print("Starting SDR")
self.start_sdr()
# Change the activity to the channel and band-type being used
print("Changing presence")
await self.set_activity()
# 'Lock' the bot from connecting
print("Locking the bot")
self.Bot_Connected = True
else:
# Return that the opus library would not load
await ctx.send("Opus won't load")
print("OPUS didn't load properly")
else:
await ctx.send(f"{str(member).capitalize()}, I'm already connected")
print("Bot is already in a channel")
@self.command(help="Use this command to have the bot leave your channel",
brief="Leaves the current voice channel")
async def leave(ctx):
async def leave(ctx, member: discord.Member = None):
member = member or ctx.author.display_name
print(f"Leave requested by {member}")
if self.Bot_Connected:
# Stop the sound handlers
self.streamHandler.clean_up()
# Disconnect the client from the voice channel
await ctx.voice_client.disconnect()
print("Disconnecting")
await self.streamHandler.close()
print("Changing presence")
# Change the presence to away and '@ me'
await self.set_activity(False)
# Stop the SDR so it can cool off
print("Stopping SDR")
self.stop_sdr()
print("Unlocking the bot")
# 'Unlock' the bot
self.Bot_Connected = False
print("Sending Goodbye")
await ctx.send(f"Goodbye {str(member).capitalize()}.")
else:
await ctx.send(f"{str(member).capitalize()}, I'm not in a channel")
# Add command to change the NoiseGate threshold
@self.command(help="Use this command to change the threshold of the noisegate",
brief="Change noisegate sensitivity")
async def chngth(ctx, _threshold: int, member: discord.Member = None):
member = member or ctx.author.display_name
print(f"Change of NoiseGate threshold requested by {member}")
await ctx.send(f"Ok {str(member).capitalize()}, I'm changing the threshold from "
f"{self.streamHandler.THRESHOLD} to {_threshold}")
self.streamHandler.THRESHOLD = _threshold
if self.sdr_started:
await self.set_activity()
# Add commands for GQRX and OP25
if self.Handler == 'gqrx' or self.Handler == 'op25':
if self.Handler in BotResources.PDB_ACCEPTABLE_HANDLERS.keys():
# Command to display the current config
@self.command(name='displaycurprofile',
help="Use this command to display the current configuration of the bot.\n"
"Example command:\n"
"\t@ displaycurprofile",
breif="Display current bot config")
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"
"\tTune to 104.7Mhz Wideband FM (Radio) - '@ chfreq wfm 104700000\n"
@@ -140,21 +204,13 @@ class Bot(commands.Bot):
brief="Changes radio frequency")
async def chfreq(ctx, mode: str, freq: str, member: discord.Member = None):
# Possible band-types that can be used
possible_modes = []
if self.Handler == 'gqrx':
possible_modes = ['wfm', 'fm']
elif self.Handler == 'op25':
possible_modes = ['d', 'p25']
member = member or ctx.author.display_name
# Check to make sure the frequency input matches the syntax needed
if len(freq) >= 6:
self.freq = freq
# Check to make sure the selected mode is valid
if mode in possible_modes:
if mode in self.possible_modes:
self.mode = mode
await ctx.send(f"Ok {str(member).capitalize()}, I'm changing the mode to "
@@ -169,7 +225,7 @@ class Bot(commands.Bot):
await self.set_activity()
else:
await ctx.send(f"{str(member).capitalize()}, {mode} is not valid."
f" You may only enter {possible_modes}")
f" You may only enter {self.possible_modes}")
else:
await ctx.send(f"{str(member).capitalize()}, {freq} is not valid. "
f"Please refer to the help page '@ help chfreq'")
@@ -208,12 +264,6 @@ class Bot(commands.Bot):
else:
await ctx.send(f"{str(member).capitalize()}, there is no profile with the name '{profile_name}'")
@self.command(name='displayprofile', hidden=True)
async def _displayprofile(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}")
# Hidden admin commands
@self.command(name='reload', hidden=True)
async def _reload(ctx, module: str, member: discord.Member = None):
@@ -225,11 +275,11 @@ class Bot(commands.Bot):
await ctx.send(f"{str(member).capitalize()}, something went wrong. Please check the console")
@self.command(name='startsdr', hidden=True)
async def _startsdr(ctx, member: discord.Member = None):
async def _startsdr(*args):
self.start_sdr()
@self.command(name='stopsdr', hidden=True)
async def _stopsdr(ctx, member: discord.Member = None):
async def _stopsdr(*args):
self.stop_sdr()
# Add discord events to the bot
@@ -241,28 +291,25 @@ 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')
channel = self.get_channel(self.Default_Channel_ID)
print(f"Channel to be tested in: {channel}")
print(f"Testing in: {channel}")
bots_online = []
def verify_bot_msg(msg):
if msg.author.id in BotResources.PDB_KNOWN_BOT_IDS:
bots_online.append(msg.author.id)
if msg.author.id in BotResources.PDB_KNOWN_BOT_IDS.keys():
bots_online.append(BotResources.PDB_KNOWN_BOT_IDS[msg.author.id])
await self.wait_until_ready()
await channel.send(f"{self.Command_Prefix}ping")
# Send the ping command with the prefix the current bot is using
await channel.send(f"{self.Command_Prefix}check_modules")
seconds_waited = 0
while seconds_waited < 2:
while seconds_waited < 3:
try:
await self.wait_for("message", check=verify_bot_msg, timeout=1)
except asyncio.exceptions.TimeoutError:
@@ -281,35 +328,50 @@ class Bot(commands.Bot):
print("Starting GQRX handler")
from gqrxHandler import GQRXHandler
self.GQRXHandler = GQRXHandler()
self.possible_modes = BotResources.PDB_ACCEPTABLE_HANDLERS['gqrx']['Modes']
elif self.Handler == 'op25':
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
def load_opus(self):
# Check the system type and load the correct library
if self.system_os_type == 'Linux_32':
discord.opus.load_opus('./opus/libopus.so')
elif self.system_os_type == 'Linux_64':
# Linux ARM AARCH64 running 32bit OS
if self.system_os_type == 'Linux_ARMv7l':
print(f"Loaded OPUS library for {self.system_os_type}")
discord.opus.load_opus('./opus/libopus_armv7l.so')
# Linux ARM AARCH64 running 64bit OS
if self.system_os_type == 'Linux_AARCH64':
print(f"Loaded OPUS library for {self.system_os_type}")
discord.opus.load_opus('./opus/libopus_aarcch64.so')
elif self.system_os_type == 'Windows':
discord.opus.load_opus('./opus/libopus.dll')
# Windows 64bit
if self.system_os_type == 'Windows_x64':
print(f"Loaded OPUS library for {self.system_os_type}")
discord.opus.load_opus('./opus/libopus_amd64.dll')
# Check to make sure the selected device is still available and has not changed it's index
def check_device(self):
for device, index in self.Devices_List:
if int(index) == self.DEVICE_ID and str(device) == self.DEVICE_NAME:
return True
# Check to make sure the selected device is still available and has not changed its index
def check_device(self, _override):
# Check to see if an override has been passed
if not _override:
print(f"Device list {self.Devices_List}")
for device, index in self.Devices_List['Input']:
if int(index) == self.DEVICE_ID and str(device) == self.DEVICE_NAME:
return True
for device, index in self.Devices_List:
if str(device) == self.DEVICE_NAME:
self.DEVICE_ID = int(index)
return True
for device, index in self.Devices_List['Input']:
if str(device) == self.DEVICE_NAME:
self.DEVICE_ID = int(index)
return True
else:
return False
else:
return False
# If an override has been passed just reply true
return True
# Search the ./modules folder for any modules to load
async def check_for_modules(self):
@@ -337,18 +399,22 @@ class Bot(commands.Bot):
# Check and store the OS type of the system for later use
def check_os_type(self):
processor = platform.machine()
if os.name == 'nt':
self.system_os_type = 'Windows'
if processor == "AMD64":
self.system_os_type = 'Windows_x64'
print(f"OS/Arch is {self.system_os_type}")
else:
processor = platform.architecture()[0]
if processor == "64bit":
self.system_os_type = 'Linux_64'
elif processor == "32bit":
self.system_os_type = 'Linux_32'
if processor == "aarch64":
self.system_os_type = 'Linux_AARCH64'
print(f"OS/Arch is {self.system_os_type}")
elif processor == "armv7l":
self.system_os_type = 'Linux_ARMv7l'
print(f"OS/Arch is {self.system_os_type}")
# Check to see if there is only one frequency
def start_sdr(self):
if self.Handler in ['gqrx', 'op25']:
if self.Handler in BotResources.PDB_ACCEPTABLE_HANDLERS.keys():
if type(self.freq) == str:
# Single freq sent
# Stop the SDR if it is running
@@ -362,8 +428,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
@@ -372,8 +437,9 @@ class Bot(commands.Bot):
def stop_sdr(self):
if self.sdr_started:
# 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
@@ -381,7 +447,7 @@ class Bot(commands.Bot):
# Set the activity of the bot
async def set_activity(self, connected=True):
if connected:
if self.Handler in ['gqrx', 'op25']:
if self.Handler in BotResources.PDB_ACCEPTABLE_HANDLERS.keys():
if self.profile_name is None:
await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening,
name=f"{self.freq[:-1]}"
@@ -399,18 +465,22 @@ class Bot(commands.Bot):
await self.change_presence(activity=discord.Game(name=f"@ me"), status=discord.Status.idle)
# Save the current radio settings as a profile
async def save_radio_config(self, profile_name):
async def save_radio_config(self, _profile_name: str):
print(f"Saving profile {_profile_name}")
config = configparser.SafeConfigParser()
if os.path.exists('./profiles.ini'):
config.read('./profiles.ini')
profile_name = str(_profile_name).upper()
if not config.has_section(str(profile_name)):
config.add_section(str(profile_name))
config[str(profile_name)]['Frequency'] = self.freq
config[str(profile_name)]['Mode'] = self.mode
config[str(profile_name)]['Squelch'] = str(self.squelch)
config[str(profile_name)]['Noisegate_Sensitivity'] = str(self.noisegate_sensitivity)
with open('./profiles.ini', 'w+') as config_file:
config.write(config_file)
@@ -423,14 +493,22 @@ class Bot(commands.Bot):
# Load a saved profile into the current settings
async def load_radio_config(self, profile_name):
print(f"Loading profile {profile_name}")
config = configparser.ConfigParser()
if os.path.exists('./profiles.ini'):
config.read('./profiles.ini')
if config.has_section(str(profile_name)):
self.profile_name = profile_name
self.freq = config[str(profile_name)]['Frequency']
self.mode = config[str(profile_name)]['Mode']
self.squelch = float(config[str(profile_name)]['Squelch'])
if config.has_section(str(profile_name).upper()):
self.profile_name = str(profile_name).upper()
self.freq = config[self.profile_name]['Frequency']
self.mode = config[self.profile_name]['Mode']
self.squelch = float(config[self.profile_name]['Squelch'])
try:
self.noisegate_sensitivity = int(config[self.profile_name]['Noisegate_Sensitivity'])
except KeyError:
print(f"Config does not contain a 'noisegate sensitivity' value, "
f"creating one now with the default value: {BotResources.DEFAULT_NOISEGATE_THRESHOLD}")
self.noisegate_sensitivity = BotResources.DEFAULT_NOISEGATE_THRESHOLD
await self.save_radio_config(self.profile_name)
if self.sdr_started:
self.start_sdr()
@@ -445,20 +523,29 @@ class Bot(commands.Bot):
def display_current_radio_config(self):
message_body = ""
if self.profile_name:
message_body += f"Profile Name: {self.profile_name}\n"
message_body += f"Frequency: {self.freq}\n" \
f"Mode: {self.mode}\n"
message_body += f"Profile Name: {str(self.profile_name).upper()}\n"
message_body += f"\tMode:\t\t\t\t\t{self.mode}\n" \
f"\tFrequency:\t\t\t{self.freq}\n" \
f"\tNoisegate Sensitivity:\t{self.noisegate_sensitivity}"
if self.squelch:
message_body += f"Squelch: {self.squelch}"
message_body += f"\tSquelch:\t\t\t\t{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
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"\nProfile Name: {section}:\n" \
f"\tMode:\t\t\t\t\t{config[section]['Mode']}\n" \
f"\tFrequency:\t\t\t{config[section]['Frequency']}\n"
try:
message_body += f"\tNoisegate Sensitivity:\t{config[section]['Noisegate_Sensitivity']}\n"
except KeyError:
print(f"Config does not contain a 'noisegate sensitivity' value. Please load the profile")
message_body += f"\tSquelch:\t\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)

89
main.py
View File

@@ -27,38 +27,103 @@ 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, **passed_config)
# 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:
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...')
discord_bot_client = bot.Bot(Token=config['Bot Token'], Device_ID=config['Device ID'], Device_Name=config['Device Name'],
Mention_Group=config['Mention Group'], Channel_ID=config['Channel ID'], Handler=config['Handler'])
discord_bot_client = bot.Bot(Token=config['Bot Token'], Device_ID=config['Device ID'],
Device_Name=config['Device Name'], Mention_Group=config['Mention Group'],
Channel_ID=config['Channel ID'], Handler=config['Handler'])
print(f"Verifying audio device:\t{config['Device Name']}")
if not discord_bot_client.check_device():
if not discord_bot_client.check_device(_override=bool("Device ID" in passed_config.keys())):
raise BotDeviceNotFound(config['Device Name'])
discord_bot_client.start_bot()
def cmd_arguments():
parser = argparse.ArgumentParser(description='Discord Bot Gang - Premium Discord Bot\n'
'The more you listen, the less you can see')
# Add the arguments
# Arg to override bot token
parser.add_argument('-t', '--token',
metavar='Bot Token',
dest='Bot Token',
type=str,
help='Override saved bot token')
# Arg to override the input device in the config
parser.add_argument('-i', '--input_device_id',
metavar='Device ID',
dest='Device ID',
type=int,
help='Override saved input device')
# Arg to override mention group
parser.add_argument('-m', '--mention',
metavar='Mention Group',
dest='Mention Group',
type=str,
help='Override saved mention group')
# Arg to override default channel to send messages
parser.add_argument('-c', '--channel',
metavar='Channel ID',
dest='Channel ID',
type=int,
help='Override saved sending channel')
# Arg to override handler
parser.add_argument('-u', '--handler',
metavar='Handler',
dest='Handler',
type=str,
help='Override saved SDR handler')
# Arg to save the overridden arguments
#parser.add_argument('-s', '--save',
# metavar='save_overrides',
# dest='save_overrides',
# type=str,
# help='Save the overridden arguments passed')
# Retrieve the args
args = vars(parser.parse_args())
return args
if __name__ == '__main__':
cmd_args = cmd_arguments()
if not all(cmd_args.values()):
print("Passed arguments:")
for arg in cmd_args:
if cmd_args[arg]:
print(f"\t{arg}:\t{cmd_args[arg]}")
try:
print('Starting...')
while True:
try:
main()
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]))+)')
@@ -44,9 +44,7 @@ class LinkCop(commands.Cog):
# Bring in the known bot IDs from PDB bots
self.whitelisted_ID = PDB_KNOWN_BOT_IDS
self.whitelisted_ID.append([
235148962103951360 # Carl Bot
])
self.whitelisted_ID['Carl Bot'] = 235148962103951360
self.add_events()
@@ -73,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

@@ -1,41 +1,70 @@
import shutil
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"
self.OP25EXE: str = shutil.which("/home/pi/op25/op25/gr-op25_repeater/apps/rx.py")
self.OP25Proc = None
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:
self.close_op25()
p25_kwargs = [f"./rx.py", "--args", "rtl", "-N", "LNA:49", "-s", "200000", "-o", "25600", "-U", "-f",
f"{self.Frequency}e6", "-X", "-2"]
print(f"Starting OP25")
# Change the interpreter's working directory (idr why)
if self.HTTP_ENABLED:
p25_kwargs.extend(["-l", "http:0.0.0.0:8080"])
cwd = os.getcwd()
print(cwd)
print(f"OP25 Keyword Args: {p25_kwargs}")
os.chdir(self.OP25Dir)
print(os.getcwd())
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"])
os.chdir(cwd)
self.OP25Proc = subprocess.Popen(p25_kwargs, executable=self.OP25EXE, shell=False, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.OP25Dir)
def close_op25(self):
print(f"Closing OP25")
@@ -48,7 +77,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

View File

@@ -1,3 +1,6 @@
discord~=1.7.3
sounddevice~=0.4.3
pynacl~=1.5.0
numpy==1.22.3
scipy==1.8.0
matplotlib~=3.5.1
pyrtlsdr~=0.2.92
PyAudio~=0.2.11

View File

@@ -1,62 +0,0 @@
import sounddevice as sd
from pprint import pformat
DEFAULT = 0
sd.default.channels = 2
sd.default.dtype = "int16"
sd.default.latency = "low"
sd.default.samplerate = 48000
class PCMStream:
globals()
def __init__(self):
self.stream = None
def read(self, num_bytes):
# frame is 4 bytes
frames = int(num_bytes / 4)
data = self.stream.read(frames)[0]
# convert to pcm format
return bytes(data)
def change_device(self, device_ID):
self.clean_up()
self.stream = sd.RawInputStream(device=device_ID)
self.stream.start()
def clean_up(self):
if self.stream is not None:
self.stream.stop()
self.stream.close()
class DeviceNotFoundError(Exception):
def __init__(self):
self.devices = sd.query_devices()
self.host_apis = sd.query_hostapis()
super().__init__("No Devices Found")
def __str__(self):
return (
f"Devices \n"
f"{self.devices} \n "
f"Host APIs \n"
f"{pformat(self.host_apis)}"
)
def query_devices():
options = {
device.get("name"): index
for index, device in enumerate(sd.query_devices())
if (device.get("max_input_channels") > 0 and device.get("hostapi") == DEFAULT)
}
if not options:
raise DeviceNotFoundError()
return options