Compare commits
47 Commits
55ee80ce22
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b65bea7856 | ||
|
|
bd8deeb44e | ||
| 7f455f427e | |||
|
|
ddfa9fc2a3 | ||
|
|
fb9f8a680f | ||
|
|
a26dd619b8 | ||
|
|
133f29635e | ||
|
|
cbc2a3fc86 | ||
|
|
b3a5dbb626 | ||
|
|
44684ed020 | ||
|
|
5ff1d6273f | ||
|
|
6324f82789 | ||
|
|
3086da0e2b | ||
|
|
021f27d62e | ||
|
|
d3e7e780f3 | ||
|
|
872bbf2965 | ||
|
|
e7956577d7 | ||
|
|
c31984e2d8 | ||
|
|
5191433e5d | ||
|
|
9dfee88789 | ||
|
|
46ec27c359 | ||
|
|
75b2d0007d | ||
| c616acd6af | |||
|
|
7e44e0e803 | ||
| 2418ac2701 | |||
| f9d30b0c8b | |||
| a5ff9fa1be | |||
| 5b3f9bfaba | |||
|
|
9f10914b8b | ||
|
|
2c3c372da1 | ||
| 71af2c83d9 | |||
| 59ee866ac9 | |||
|
|
50b11efd80 | ||
|
|
f1de077b72 | ||
|
|
7362715a21 | ||
|
|
74e66eb796 | ||
|
|
925243b53c | ||
|
|
acb72eff03 | ||
| 5434941f3d | |||
|
|
d41ed60ee6 | ||
|
|
3ded857456 | ||
|
|
78432c07a0 | ||
|
|
f20b6cc0ed | ||
|
|
c872a27017 | ||
|
|
af6c9fb763 | ||
|
|
3dbbdaeec2 | ||
| 0fb1a155b5 |
57
.gitea/workflows/build-nightly.yml
Normal file
57
.gitea/workflows/build-nightly.yml
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
name: release-tag
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- dev
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release-image:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
DOCKER_LATEST: stable
|
||||||
|
CONTAINER_NAME: drb-client-discord-bot
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
- name: Set up Docker BuildX
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
with: # replace it with your local IP
|
||||||
|
config-inline: |
|
||||||
|
[registry."git.vpn.cusano.net"]
|
||||||
|
http = false
|
||||||
|
insecure = false
|
||||||
|
|
||||||
|
- name: Login to DockerHub
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: git.vpn.cusano.net # replace it with your local IP
|
||||||
|
username: ${{ secrets.GIT_REPO_USERNAME }}
|
||||||
|
password: ${{ secrets.GIT_REPO_PASSWORD }}
|
||||||
|
|
||||||
|
- name: Get Meta
|
||||||
|
id: meta
|
||||||
|
run: |
|
||||||
|
echo REPO_NAME=$(echo ${GITHUB_REPOSITORY} | awk -F"/" '{print $2}') >> $GITHUB_OUTPUT
|
||||||
|
echo REPO_VERSION=$(git describe --tags --always | sed 's/^v//') >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Validate build configuration
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
call: check
|
||||||
|
|
||||||
|
- name: Build and push
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
platforms: |
|
||||||
|
linux/arm64
|
||||||
|
push: true
|
||||||
|
tags: | # replace it with your local IP and tags
|
||||||
|
git.vpn.cusano.net/${{ vars.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}/${{ env.CONTAINER_NAME }}:${{ steps.meta.outputs.REPO_VERSION }}
|
||||||
|
git.vpn.cusano.net/${{ vars.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}/${{ env.CONTAINER_NAME }}:${{ env.DOCKER_LATEST }}
|
||||||
@@ -8,12 +8,9 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
release-image:
|
release-image:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
|
||||||
image: catthehacker/ubuntu:act-latest
|
|
||||||
env:
|
env:
|
||||||
DOCKER_ORG: teacup
|
DOCKER_LATEST: stable
|
||||||
DOCKER_LATEST: nightly
|
CONTAINER_NAME: drb-client-discord-bot
|
||||||
RUNNER_TOOL_CACHE: /toolcache
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -33,8 +30,8 @@ jobs:
|
|||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: git.vpn.cusano.net # replace it with your local IP
|
registry: git.vpn.cusano.net # replace it with your local IP
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.GIT_REPO_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.GIT_REPO_PASSWORD }}
|
||||||
|
|
||||||
- name: Get Meta
|
- name: Get Meta
|
||||||
id: meta
|
id: meta
|
||||||
@@ -42,15 +39,19 @@ jobs:
|
|||||||
echo REPO_NAME=$(echo ${GITHUB_REPOSITORY} | awk -F"/" '{print $2}') >> $GITHUB_OUTPUT
|
echo REPO_NAME=$(echo ${GITHUB_REPOSITORY} | awk -F"/" '{print $2}') >> $GITHUB_OUTPUT
|
||||||
echo REPO_VERSION=$(git describe --tags --always | sed 's/^v//') >> $GITHUB_OUTPUT
|
echo REPO_VERSION=$(git describe --tags --always | sed 's/^v//') >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Validate build configuration
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
call: check
|
||||||
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
uses: docker/build-push-action@v4
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
file: ./Dockerfile
|
file: ./Dockerfile
|
||||||
platforms: |
|
platforms: |
|
||||||
linux/amd64
|
linux/arm64
|
||||||
linux/arm64
|
|
||||||
push: true
|
push: true
|
||||||
tags: | # replace it with your local IP and tags
|
tags: | # replace it with your local IP and tags
|
||||||
git.vpn.cusano.net/${{ vars.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}:${{ steps.meta.outputs.REPO_VERSION }}
|
git.vpn.cusano.net/${{ vars.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}/${{ env.CONTAINER_NAME }}:${{ steps.meta.outputs.REPO_VERSION }}
|
||||||
git.vpn.cusano.net/${{ vars.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}:${{ env.DOCKER_LATEST }}
|
git.vpn.cusano.net/${{ vars.DOCKER_ORG }}/${{ steps.meta.outputs.REPO_NAME }}/${{ env.CONTAINER_NAME }}:${{ env.DOCKER_LATEST }}
|
||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,4 +1,6 @@
|
|||||||
__pycache__*
|
__pycache__*
|
||||||
bot-poc.py
|
bot-poc.py
|
||||||
configs*
|
configs*
|
||||||
.env
|
.env
|
||||||
|
*.log*
|
||||||
|
.venv
|
||||||
11
Dockerfile
11
Dockerfile
@@ -6,7 +6,8 @@ ENV DEBIAN_FRONTEND=noninteractive
|
|||||||
|
|
||||||
# Install system dependencies
|
# Install system dependencies
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
apt-get install -y git \
|
apt-get install -y --no-install-recommends libc-bin apt-transport-https tzdata && \
|
||||||
|
apt-get install -y --no-install-recommends git \
|
||||||
curl \
|
curl \
|
||||||
python3 \
|
python3 \
|
||||||
python3-pip \
|
python3-pip \
|
||||||
@@ -59,11 +60,11 @@ VOLUME ["/configs"]
|
|||||||
# Set the working directory in the container
|
# Set the working directory in the container
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copy opus first to break up the build time
|
||||||
|
COPY ./app/internal/opus /app/internal/opus
|
||||||
|
|
||||||
# Copy the rest of the directory contents into the container at /app
|
# Copy the rest of the directory contents into the container at /app
|
||||||
COPY ./app /app
|
COPY ./app /app
|
||||||
|
|
||||||
# Copy the pre-built opus libraries
|
|
||||||
COPY ./opus /app/opus
|
|
||||||
|
|
||||||
# Run the node script
|
# Run the node script
|
||||||
ENTRYPOINT ["uvicorn", "bot:app", "--host", "0.0.0.0", "--port", "8001", "--reload"]
|
ENTRYPOINT ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001", "--reload"]
|
||||||
10
Makefile
10
Makefile
@@ -23,6 +23,16 @@ run: build
|
|||||||
--network=host \
|
--network=host \
|
||||||
$(IMAGE_NAME)
|
$(IMAGE_NAME)
|
||||||
|
|
||||||
|
# Deploy docker
|
||||||
|
deploy: build
|
||||||
|
docker run --rm -d \
|
||||||
|
--privileged \
|
||||||
|
-v /dev:/dev \
|
||||||
|
-v $(shell pwd)/configs:/configs \
|
||||||
|
--name $(CONTAINER_NAME) \
|
||||||
|
--network=host \
|
||||||
|
$(IMAGE_NAME)
|
||||||
|
|
||||||
# Stop the Docker container
|
# Stop the Docker container
|
||||||
stop:
|
stop:
|
||||||
docker stop $(CONTAINER_NAME)
|
docker stop $(CONTAINER_NAME)
|
||||||
|
|||||||
158
app/bot.py
158
app/bot.py
@@ -1,158 +0,0 @@
|
|||||||
import asyncio
|
|
||||||
from typing import Optional, Dict
|
|
||||||
|
|
||||||
from fastapi import FastAPI, HTTPException
|
|
||||||
from pydantic import BaseModel
|
|
||||||
import discord
|
|
||||||
from discord.ext import commands
|
|
||||||
from NoiseGatev2 import NoiseGate
|
|
||||||
import op25_controller
|
|
||||||
import pulse
|
|
||||||
|
|
||||||
# Define FastAPI app
|
|
||||||
app = FastAPI()
|
|
||||||
|
|
||||||
# Discord Bot Setup
|
|
||||||
intents = discord.Intents.default()
|
|
||||||
intents.voice_states = True
|
|
||||||
intents.guilds = True
|
|
||||||
|
|
||||||
# Models for API requests
|
|
||||||
class BotConfig(BaseModel):
|
|
||||||
token: str # Discord Bot Token
|
|
||||||
|
|
||||||
class VoiceChannelRequest(BaseModel):
|
|
||||||
guild_id: int
|
|
||||||
channel_id: int
|
|
||||||
|
|
||||||
# Discord Bot Manager
|
|
||||||
class DiscordBotManager:
|
|
||||||
def __init__(self):
|
|
||||||
self.bot: Optional[commands.Bot] = None
|
|
||||||
self.bot_task: Optional[asyncio.Task] = None
|
|
||||||
self.voice_clients: Dict[int, discord.VoiceClient] = {}
|
|
||||||
self.token: Optional[str] = None
|
|
||||||
self.loop = asyncio.get_event_loop()
|
|
||||||
self.lock = asyncio.Lock()
|
|
||||||
|
|
||||||
async def start_bot(self, token: str):
|
|
||||||
async with self.lock:
|
|
||||||
if self.bot and self.bot.is_closed():
|
|
||||||
raise RuntimeError("Bot is already running.")
|
|
||||||
if self.bot_task and not self.bot_task.done():
|
|
||||||
raise RuntimeError("Bot is already running.")
|
|
||||||
|
|
||||||
self.token = token
|
|
||||||
self.bot = commands.Bot(command_prefix="!", intents=intents)
|
|
||||||
|
|
||||||
@self.bot.event
|
|
||||||
async def on_ready():
|
|
||||||
print(f'Logged in as {self.bot.user}')
|
|
||||||
|
|
||||||
# Handle graceful shutdown when all voice connections are closed
|
|
||||||
@self.bot.event
|
|
||||||
async def on_voice_state_update(member, before, after):
|
|
||||||
# Check if all voice clients are disconnected
|
|
||||||
await asyncio.sleep(1) # Give time for the state to update
|
|
||||||
if not self.voice_clients:
|
|
||||||
await self.stop_bot()
|
|
||||||
|
|
||||||
# Start the bot in the background
|
|
||||||
self.bot_task = self.loop.create_task(self.bot.start(token))
|
|
||||||
|
|
||||||
async def stop_bot(self):
|
|
||||||
async with self.lock:
|
|
||||||
if self.bot:
|
|
||||||
await self.bot.close()
|
|
||||||
self.bot = None
|
|
||||||
if self.bot_task:
|
|
||||||
await self.bot_task
|
|
||||||
self.bot_task = None
|
|
||||||
self.voice_clients.clear()
|
|
||||||
print("Bot has been stopped.")
|
|
||||||
|
|
||||||
async def join_voice_channel(self, guild_id: int, channel_id: int, ng_threshold: int = 50, device_id: int = 4):
|
|
||||||
if not self.bot:
|
|
||||||
raise RuntimeError("Bot is not running.")
|
|
||||||
|
|
||||||
guild = self.bot.get_guild(guild_id)
|
|
||||||
if not guild:
|
|
||||||
raise ValueError("Guild not found.")
|
|
||||||
|
|
||||||
channel = guild.get_channel(channel_id)
|
|
||||||
if not isinstance(channel, discord.VoiceChannel):
|
|
||||||
raise ValueError("Channel is not a voice channel.")
|
|
||||||
|
|
||||||
if guild_id in self.voice_clients:
|
|
||||||
raise RuntimeError("Already connected to this guild's voice channel.")
|
|
||||||
|
|
||||||
voice_client = await channel.connect()
|
|
||||||
streamHandler = NoiseGate(
|
|
||||||
_input_device_index=device_id,
|
|
||||||
_voice_connection=voice_client,
|
|
||||||
_noise_gate_threshold=ng_threshold)
|
|
||||||
# Start the audio stream
|
|
||||||
streamHandler.run()
|
|
||||||
self.voice_clients[guild_id] = voice_client
|
|
||||||
print(f"Joined guild {guild_id} voice channel {channel_id}.")
|
|
||||||
|
|
||||||
async def leave_voice_channel(self, guild_id: int):
|
|
||||||
if not self.bot:
|
|
||||||
raise RuntimeError("Bot is not running.")
|
|
||||||
|
|
||||||
voice_client = self.voice_clients.get(guild_id)
|
|
||||||
if not voice_client:
|
|
||||||
raise RuntimeError("Not connected to the specified guild's voice channel.")
|
|
||||||
|
|
||||||
await voice_client.disconnect()
|
|
||||||
del self.voice_clients[guild_id]
|
|
||||||
print(f"Left guild {guild_id} voice channel.")
|
|
||||||
|
|
||||||
|
|
||||||
# Initialize Discord Bot Manager
|
|
||||||
bot_manager = DiscordBotManager()
|
|
||||||
|
|
||||||
# API Endpoints
|
|
||||||
@app.post("/start_bot")
|
|
||||||
async def start_bot(config: BotConfig):
|
|
||||||
try:
|
|
||||||
await bot_manager.start_bot(config.token)
|
|
||||||
return {"status": "Bot started successfully."}
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
|
||||||
|
|
||||||
@app.post("/stop_bot")
|
|
||||||
async def stop_bot():
|
|
||||||
try:
|
|
||||||
await bot_manager.stop_bot()
|
|
||||||
return {"status": "Bot stopped successfully."}
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
|
||||||
|
|
||||||
@app.post("/join_voice")
|
|
||||||
async def join_voice_channel(request: VoiceChannelRequest):
|
|
||||||
try:
|
|
||||||
await bot_manager.join_voice_channel(request.guild_id, request.channel_id)
|
|
||||||
return {"status": f"Joined guild {request.guild_id} voice channel {request.channel_id}."}
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
|
||||||
|
|
||||||
@app.post("/leave_voice")
|
|
||||||
async def leave_voice_channel(request: VoiceChannelRequest):
|
|
||||||
try:
|
|
||||||
await bot_manager.leave_voice_channel(request.guild_id)
|
|
||||||
return {"status": f"Left guild {request.guild_id} voice channel."}
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
|
||||||
|
|
||||||
@app.get("/status")
|
|
||||||
async def get_status():
|
|
||||||
status = {
|
|
||||||
"bot_running": bot_manager.bot is not None and not bot_manager.bot.is_closed(),
|
|
||||||
"connected_guilds": list(bot_manager.voice_clients.keys())
|
|
||||||
}
|
|
||||||
return status
|
|
||||||
|
|
||||||
|
|
||||||
app.include_router(op25_controller.router, prefix="/op25")
|
|
||||||
app.include_router(pulse.router, prefix="/pulse")
|
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
import audioop
|
import audioop
|
||||||
import logging
|
|
||||||
import math
|
import math
|
||||||
import time
|
import time
|
||||||
|
|
||||||
import pyaudio
|
import pyaudio
|
||||||
import discord
|
import discord
|
||||||
import numpy
|
import numpy
|
||||||
|
from internal.logger import create_logger
|
||||||
|
|
||||||
voice_connection = None
|
voice_connection = None
|
||||||
|
|
||||||
LOGGER = logging.getLogger("Discord_Radio_Bot.NoiseGateV2")
|
LOGGER = create_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
# noinspection PyUnresolvedReferences
|
# noinspection PyUnresolvedReferences
|
||||||
179
app/internal/bot_manager.py
Normal file
179
app/internal/bot_manager.py
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
import asyncio
|
||||||
|
import platform
|
||||||
|
import os
|
||||||
|
from discord import VoiceClient, VoiceChannel, opus, Activity, ActivityType, Intents
|
||||||
|
from discord.ext import commands
|
||||||
|
from typing import Optional, Dict
|
||||||
|
from internal.NoiseGatev2 import NoiseGate
|
||||||
|
from internal.logger import create_logger
|
||||||
|
|
||||||
|
LOGGER = create_logger(__name__)
|
||||||
|
|
||||||
|
# Configure discord intents
|
||||||
|
intents = Intents.default()
|
||||||
|
intents.voice_states = True
|
||||||
|
intents.guilds = True
|
||||||
|
|
||||||
|
class DiscordBotManager:
|
||||||
|
def __init__(self):
|
||||||
|
self.bot: Optional[commands.Bot] = None
|
||||||
|
self.bot_task: Optional[asyncio.Task] = None
|
||||||
|
self.voice_clients: Dict[int, VoiceClient] = {}
|
||||||
|
self.token: Optional[str] = None
|
||||||
|
self.loop = asyncio.get_event_loop()
|
||||||
|
self.lock = asyncio.Lock()
|
||||||
|
self._ready_event = asyncio.Event()
|
||||||
|
self._voice_ready_event = asyncio.Event()
|
||||||
|
|
||||||
|
async def start_bot(self, token: str):
|
||||||
|
async with self.lock:
|
||||||
|
if self.bot and not self.bot.is_closed():
|
||||||
|
raise RuntimeError("Bot is already running.")
|
||||||
|
if self.bot_task and not self.bot_task.done():
|
||||||
|
raise RuntimeError("Bot is already running.")
|
||||||
|
|
||||||
|
self.token = token
|
||||||
|
self.bot = commands.Bot(command_prefix="!", intents=intents)
|
||||||
|
|
||||||
|
@self.bot.event
|
||||||
|
async def on_ready():
|
||||||
|
LOGGER.info(f'Logged in as {self.bot.user}')
|
||||||
|
# Set the event when on_ready is called
|
||||||
|
self._ready_event.set()
|
||||||
|
|
||||||
|
@self.bot.event
|
||||||
|
async def on_voice_state_update(member, before, after):
|
||||||
|
# Check if the bot was disconnected
|
||||||
|
if member == self.bot.user and after.channel is None:
|
||||||
|
guild_id = before.channel.guild.id
|
||||||
|
if not self.voice_clients.get(guild_id):
|
||||||
|
LOGGER.info("Bot has left channel, reconnection ignored.")
|
||||||
|
return
|
||||||
|
LOGGER.info(f"Bot was disconnected from channel in guild {guild_id}. Attempting to reconnect...")
|
||||||
|
try:
|
||||||
|
await self.leave_voice_channel(guild_id)
|
||||||
|
except Exception as e:
|
||||||
|
LOGGER.warning(f"Error leaving voice channel: '{e}'")
|
||||||
|
# Attempt to reconnect to the channel after a brief pause
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
await self.join_voice_channel(guild_id, before.channel.id)
|
||||||
|
|
||||||
|
if member == self.bot.user and before.channel is None and after.channel is not None:
|
||||||
|
print(f"{member.name} joined voice channel {after.channel.name}")
|
||||||
|
self._voice_ready_event.set()
|
||||||
|
|
||||||
|
# Load Opus for the current CPU
|
||||||
|
await self.load_opus()
|
||||||
|
|
||||||
|
# Create the task to run the bot in the background
|
||||||
|
self.bot_task = self.loop.create_task(self.bot.start(token))
|
||||||
|
|
||||||
|
# Wait for the on_ready event to be set by the bot task
|
||||||
|
LOGGER.info("Waiting for bot to become ready...")
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(self._ready_event.wait(), timeout=60.0)
|
||||||
|
LOGGER.info("Bot is ready, start_bot returning.")
|
||||||
|
return
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
LOGGER.error("Timeout waiting for bot to become ready. Bot might have failed to start.")
|
||||||
|
if self.bot_task and not self.bot_task.done():
|
||||||
|
self.bot_task.cancel()
|
||||||
|
raise RuntimeError("Bot failed to become ready within timeout.")
|
||||||
|
|
||||||
|
async def stop_bot(self):
|
||||||
|
async with self.lock:
|
||||||
|
if self.bot:
|
||||||
|
await self.bot.close()
|
||||||
|
self.bot = None
|
||||||
|
if self.bot_task:
|
||||||
|
await self.bot_task
|
||||||
|
self.bot_task = None
|
||||||
|
self.voice_clients.clear()
|
||||||
|
self._ready_event.clear()
|
||||||
|
LOGGER.info("Bot has been stopped.")
|
||||||
|
|
||||||
|
async def join_voice_channel(self, guild_id: int, channel_id: int, ng_threshold: int = 50, device_id: int = 4):
|
||||||
|
if not self.bot:
|
||||||
|
raise RuntimeError("Bot is not running.")
|
||||||
|
|
||||||
|
guild = self.bot.get_guild(guild_id)
|
||||||
|
if not guild:
|
||||||
|
raise ValueError("Guild not found.")
|
||||||
|
|
||||||
|
if not opus.is_loaded():
|
||||||
|
raise RuntimeError("Opus is not loaded.")
|
||||||
|
|
||||||
|
channel = guild.get_channel(channel_id)
|
||||||
|
if not isinstance(channel, VoiceChannel):
|
||||||
|
raise ValueError("Channel is not a voice channel.")
|
||||||
|
|
||||||
|
if guild_id in self.voice_clients:
|
||||||
|
raise RuntimeError("Already connected to this guild's voice channel.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
voice_client = await channel.connect(timeout=60.0, reconnect=True)
|
||||||
|
LOGGER.debug("Voice Connected.")
|
||||||
|
streamHandler = NoiseGate(
|
||||||
|
_input_device_index=device_id,
|
||||||
|
_voice_connection=voice_client,
|
||||||
|
_noise_gate_threshold=ng_threshold)
|
||||||
|
streamHandler.run()
|
||||||
|
LOGGER.debug("Stream is running.")
|
||||||
|
self.voice_clients[guild_id] = voice_client
|
||||||
|
LOGGER.info(f"Joined guild {guild_id} voice channel {channel_id} and stream is running.")
|
||||||
|
except Exception as e:
|
||||||
|
LOGGER.error(f"Failed to connect to voice channel: {e}")
|
||||||
|
|
||||||
|
LOGGER.info("Waiting for bot to join voice...")
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(self._voice_ready_event.wait(), timeout=60.0)
|
||||||
|
LOGGER.info("Bot joined voice, returning.")
|
||||||
|
return
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
LOGGER.error("Timeout waiting for bot to join voice.")
|
||||||
|
raise RuntimeError("Bot failed to join voice within timeout.")
|
||||||
|
|
||||||
|
async def leave_voice_channel(self, guild_id: int):
|
||||||
|
if not self.bot:
|
||||||
|
raise RuntimeError("Bot is not running.")
|
||||||
|
|
||||||
|
voice_client = self.voice_clients.get(guild_id)
|
||||||
|
if not voice_client:
|
||||||
|
raise RuntimeError("Not connected to the specified guild's voice channel.")
|
||||||
|
|
||||||
|
await voice_client.disconnect()
|
||||||
|
del self.voice_clients[guild_id]
|
||||||
|
LOGGER.info(f"Left guild {guild_id} voice channel.")
|
||||||
|
|
||||||
|
async def load_opus(self):
|
||||||
|
""" Load the proper OPUS library for the device being used """
|
||||||
|
processor = platform.machine()
|
||||||
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
LOGGER.debug("Processor: ", processor)
|
||||||
|
if os.name == 'nt':
|
||||||
|
if processor == "AMD64":
|
||||||
|
opus.load_opus(os.path.join(script_dir, './opus/libopus_amd64.dll'))
|
||||||
|
LOGGER.info("Loaded OPUS library for AMD64")
|
||||||
|
return "AMD64"
|
||||||
|
else:
|
||||||
|
if processor == "aarch64":
|
||||||
|
opus.load_opus(os.path.join(script_dir, './opus/libopus_aarcch64.so'))
|
||||||
|
LOGGER.info("Loaded OPUS library for aarch64")
|
||||||
|
return "aarch64"
|
||||||
|
elif processor == "armv7l":
|
||||||
|
opus.load_opus(os.path.join(script_dir, './opus/libopus_armv7l.so'))
|
||||||
|
LOGGER.info("Loaded OPUS library for armv7l")
|
||||||
|
return "armv7l"
|
||||||
|
|
||||||
|
async def set_presence(self, system_name: str):
|
||||||
|
""" Set the presence (activity) of the bot """
|
||||||
|
if not self.bot:
|
||||||
|
LOGGER.warning("Bot is not running, cannot set presence.")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
activity = Activity(type=ActivityType.listening, name=system_name)
|
||||||
|
await self.bot.change_presence(activity=activity)
|
||||||
|
LOGGER.info(f"Bot presence set to 'Listening to {system_name}'")
|
||||||
|
except Exception as pe:
|
||||||
|
LOGGER.error(f"Unable to set presence: '{pe}'")
|
||||||
55
app/internal/logger.py
Normal file
55
app/internal/logger.py
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import logging
|
||||||
|
from logging.handlers import RotatingFileHandler
|
||||||
|
|
||||||
|
def create_logger(name, level=logging.DEBUG, max_bytes=10485760, backup_count=2):
|
||||||
|
"""
|
||||||
|
Creates a logger with a console and rotating file handlers for both debug and info log levels.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
name (str): The name for the logger.
|
||||||
|
level (int): The logging level for the logger. Defaults to logging.DEBUG.
|
||||||
|
max_bytes (int): Maximum size of the log file in bytes before it gets rotated. Defaults to 10 MB.
|
||||||
|
backup_count (int): Number of backup files to keep. Defaults to 2.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
logging.Logger: Configured logger.
|
||||||
|
"""
|
||||||
|
# Set the log file paths
|
||||||
|
debug_log_file = "./client.debug.log"
|
||||||
|
info_log_file = "./client.log"
|
||||||
|
|
||||||
|
# Create a logger
|
||||||
|
logger = logging.getLogger(name)
|
||||||
|
logger.setLevel(level)
|
||||||
|
|
||||||
|
# Check if the logger already has handlers to avoid duplicate logs
|
||||||
|
if not logger.hasHandlers():
|
||||||
|
# Create console handler
|
||||||
|
console_handler = logging.StreamHandler()
|
||||||
|
console_handler.setLevel(level)
|
||||||
|
|
||||||
|
# Create rotating file handler for debug level
|
||||||
|
debug_file_handler = RotatingFileHandler(debug_log_file, maxBytes=max_bytes, backupCount=backup_count)
|
||||||
|
debug_file_handler.setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
# Create rotating file handler for info level
|
||||||
|
info_file_handler = RotatingFileHandler(info_log_file, maxBytes=max_bytes, backupCount=backup_count)
|
||||||
|
info_file_handler.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# Create formatter and add it to the handlers
|
||||||
|
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||||
|
console_handler.setFormatter(formatter)
|
||||||
|
debug_file_handler.setFormatter(formatter)
|
||||||
|
info_file_handler.setFormatter(formatter)
|
||||||
|
|
||||||
|
# Add the handlers to the logger
|
||||||
|
logger.addHandler(console_handler)
|
||||||
|
logger.addHandler(debug_file_handler)
|
||||||
|
logger.addHandler(info_file_handler)
|
||||||
|
|
||||||
|
return logger
|
||||||
|
|
||||||
|
# Example usage:
|
||||||
|
# logger = create_logger('my_logger')
|
||||||
|
# logger.debug('This is a debug message')
|
||||||
|
# logger.info('This is an info message')
|
||||||
70
app/internal/op25_config_utls.py
Normal file
70
app/internal/op25_config_utls.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
import csv
|
||||||
|
import json
|
||||||
|
from models import TalkgroupTag
|
||||||
|
from typing import List
|
||||||
|
from internal.logger import create_logger
|
||||||
|
|
||||||
|
LOGGER = create_logger(__name__)
|
||||||
|
|
||||||
|
def save_talkgroup_tags(talkgroup_tags: List[TalkgroupTag]) -> None:
|
||||||
|
"""
|
||||||
|
Writes a list of tags to the tags file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
talkgroup_tags (List[TalkgroupTag]): The list of TalkgroupTag instances.
|
||||||
|
"""
|
||||||
|
with open("/configs/active.cfg.tags.tsv", 'w', newline='', encoding='utf-8') as file:
|
||||||
|
writer = csv.writer(file, delimiter='\t', lineterminator='\n')
|
||||||
|
# Write rows
|
||||||
|
for tag in talkgroup_tags:
|
||||||
|
writer.writerow([tag.talkgroup, tag.tagDec])
|
||||||
|
|
||||||
|
def save_whitelist(talkgroup_tags: List[int]) -> None:
|
||||||
|
"""
|
||||||
|
Writes a list of talkgroups to the whitelists file.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
talkgroup_tags (List[int]): The list of decimals to whitelist.
|
||||||
|
"""
|
||||||
|
with open("/configs/active.cfg.whitelist.tsv", 'w', newline='', encoding='utf-8') as file:
|
||||||
|
writer = csv.writer(file, delimiter='\t', lineterminator='\n')
|
||||||
|
# Write rows
|
||||||
|
for tag in talkgroup_tags:
|
||||||
|
writer.writerow([tag])
|
||||||
|
|
||||||
|
def del_none_in_dict(d):
|
||||||
|
"""
|
||||||
|
Delete keys with the value ``None`` in a dictionary, recursively.
|
||||||
|
|
||||||
|
This alters the input so you may wish to ``copy`` the dict first.
|
||||||
|
"""
|
||||||
|
for key, value in list(d.items()):
|
||||||
|
LOGGER.info(f"Key: '{key}'\nValue: '{value}'")
|
||||||
|
if value is None:
|
||||||
|
del d[key]
|
||||||
|
elif isinstance(value, dict):
|
||||||
|
del_none_in_dict(value)
|
||||||
|
elif isinstance(value, list):
|
||||||
|
for iterative_value in value:
|
||||||
|
del_none_in_dict(iterative_value)
|
||||||
|
return d # For convenience
|
||||||
|
|
||||||
|
def get_current_system_from_config() -> str:
|
||||||
|
# Get the current config
|
||||||
|
with open('/configs/active.cfg.json', 'r') as f:
|
||||||
|
json_data = f.read()
|
||||||
|
if isinstance(json_data, str):
|
||||||
|
try:
|
||||||
|
data = json.loads(json_data)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
elif isinstance(json_data, dict):
|
||||||
|
data = json_data
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if "channels" in data and isinstance(data["channels"], list) and len(data["channels"]) > 0:
|
||||||
|
first_channel = data["channels"][0]
|
||||||
|
if "name" in first_channel:
|
||||||
|
return first_channel["name"]
|
||||||
|
return None
|
||||||
19
app/main.py
Normal file
19
app/main.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
import routers.op25_controller as op25_controller
|
||||||
|
import routers.pulse as pulse
|
||||||
|
import routers.bot as bot
|
||||||
|
from internal.logger import create_logger
|
||||||
|
from internal.bot_manager import DiscordBotManager
|
||||||
|
|
||||||
|
# Initialize logging
|
||||||
|
LOGGER = create_logger(__name__)
|
||||||
|
|
||||||
|
# Define FastAPI app
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
# Initialize Discord Bot Manager
|
||||||
|
bot_manager_instance = DiscordBotManager()
|
||||||
|
|
||||||
|
app.include_router(op25_controller.create_op25_router(bot_manager=bot_manager_instance), prefix="/op25")
|
||||||
|
app.include_router(pulse.router, prefix="/pulse")
|
||||||
|
app.include_router(bot.create_bot_router(bot_manager=bot_manager_instance), prefix="/bot")
|
||||||
104
app/models.py
Normal file
104
app/models.py
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import List, Optional, Union
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
|
class BotConfig(BaseModel):
|
||||||
|
token: str
|
||||||
|
|
||||||
|
class VoiceChannelJoinRequest(BaseModel):
|
||||||
|
guild_id: int
|
||||||
|
channel_id: int
|
||||||
|
|
||||||
|
class VoiceChannelLeaveRequest(BaseModel):
|
||||||
|
guild_id: int
|
||||||
|
|
||||||
|
class DecodeMode(str, Enum):
|
||||||
|
P25 = "P25"
|
||||||
|
DMR = "DMR"
|
||||||
|
ANALOG = "NBFM"
|
||||||
|
|
||||||
|
class TalkgroupTag(BaseModel):
|
||||||
|
talkgroup: str
|
||||||
|
tagDec: int
|
||||||
|
|
||||||
|
class ConfigGenerator(BaseModel):
|
||||||
|
type: DecodeMode
|
||||||
|
systemName: str
|
||||||
|
channels: List[Union[int, str]]
|
||||||
|
tags: Optional[List[TalkgroupTag]]
|
||||||
|
whitelist: Optional[List[int]]
|
||||||
|
|
||||||
|
class DemodType(str, Enum):
|
||||||
|
CQPSK = "cqpsk"
|
||||||
|
FSK4 = "fsk4"
|
||||||
|
|
||||||
|
class FilterType(str, Enum):
|
||||||
|
RC = "rc"
|
||||||
|
WIDEPULSE = "widepulse"
|
||||||
|
|
||||||
|
class ChannelConfig(BaseModel):
|
||||||
|
name: str
|
||||||
|
trunking_sysname: Optional[str]
|
||||||
|
enable_analog: str
|
||||||
|
demod_type: DemodType
|
||||||
|
filter_type: FilterType
|
||||||
|
device: Optional[str] = "sdr"
|
||||||
|
cqpsk_tracking: Optional[bool] = None
|
||||||
|
frequency: Optional[float] = None
|
||||||
|
nbfmSquelch: Optional[float] = None
|
||||||
|
destination: Optional[str] = "udp://127.0.0.1:23456"
|
||||||
|
tracking_threshold: Optional[int] = 120
|
||||||
|
tracking_feedback: Optional[float] = 0.75
|
||||||
|
excess_bw: Optional[float] = 0.2
|
||||||
|
if_rate: Optional[int] = 24000
|
||||||
|
plot: Optional[str] = ""
|
||||||
|
symbol_rate: Optional[int] = 4800
|
||||||
|
blacklist: Optional[str] = ""
|
||||||
|
whitelist: Optional[str] = ""
|
||||||
|
|
||||||
|
class DeviceConfig(BaseModel):
|
||||||
|
args: Optional[str] = "rtl"
|
||||||
|
gains: Optional[str] = "lna:39"
|
||||||
|
gain_mode: Optional[bool] = False
|
||||||
|
name: Optional[str] = "sdr"
|
||||||
|
offset: Optional[int] = 0
|
||||||
|
ppm: Optional[float] = 0.0
|
||||||
|
rate: Optional[int] = 1920000
|
||||||
|
usable_bw_pct: Optional[float] = 0.85
|
||||||
|
tunable: Optional[bool] = True
|
||||||
|
|
||||||
|
class TrunkingChannelConfig(BaseModel):
|
||||||
|
sysname: str
|
||||||
|
control_channel_list: str
|
||||||
|
tagsFile: Optional[str] = None
|
||||||
|
whitelist: Optional[str] = None
|
||||||
|
nac: Optional[str] = ""
|
||||||
|
wacn: Optional[str] = ""
|
||||||
|
tdma_cc: Optional[bool] = False
|
||||||
|
crypt_behavior: Optional[int] = 2
|
||||||
|
|
||||||
|
class TrunkingConfig(BaseModel):
|
||||||
|
module: str
|
||||||
|
chans: List[TrunkingChannelConfig]
|
||||||
|
|
||||||
|
class AudioInstanceConfig(BaseModel):
|
||||||
|
instance_name: Optional[str] = "audio0"
|
||||||
|
device_name: Optional[str] = "pulse"
|
||||||
|
udp_port: Optional[int] = 23456
|
||||||
|
audio_gain: Optional[float] = 2.5
|
||||||
|
number_channels: Optional[int] = 1
|
||||||
|
|
||||||
|
class AudioConfig(BaseModel):
|
||||||
|
module: Optional[str] = "sockaudio.py"
|
||||||
|
instances: Optional[List[AudioInstanceConfig]] = [AudioInstanceConfig()]
|
||||||
|
|
||||||
|
class TerminalConfig(BaseModel):
|
||||||
|
module: Optional[str] = "terminal.py"
|
||||||
|
terminal_type: Optional[str] = "http:0.0.0.0:8081"
|
||||||
|
terminal_timeout: Optional[float] = 5.0
|
||||||
|
curses_plot_interval: Optional[float] = 0.2
|
||||||
|
http_plot_interval: Optional[float] = 1.0
|
||||||
|
http_plot_directory: Optional[str] = "../www/images"
|
||||||
|
tuning_step_large: Optional[int] = 1200
|
||||||
|
tuning_step_small: Optional[int] = 100
|
||||||
@@ -1,242 +0,0 @@
|
|||||||
from fastapi import HTTPException, APIRouter
|
|
||||||
from pydantic import BaseModel
|
|
||||||
from enum import Enum
|
|
||||||
import subprocess
|
|
||||||
import os
|
|
||||||
import signal
|
|
||||||
import json
|
|
||||||
import csv
|
|
||||||
from typing import List, Optional
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
op25_process = None
|
|
||||||
OP25_PATH = "/op25/op25/gr-op25_repeater/apps/"
|
|
||||||
OP25_SCRIPT = "run_multi-rx_service.sh"
|
|
||||||
|
|
||||||
@router.post("/start")
|
|
||||||
async def start_op25():
|
|
||||||
global op25_process
|
|
||||||
if op25_process is None:
|
|
||||||
try:
|
|
||||||
op25_process = subprocess.Popen(os.path.join(OP25_PATH, OP25_SCRIPT), shell=True, preexec_fn=os.setsid, cwd=OP25_PATH)
|
|
||||||
print(op25_process)
|
|
||||||
return {"status": "OP25 started"}
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
|
||||||
else:
|
|
||||||
return {"status": "OP25 already running"}
|
|
||||||
|
|
||||||
@router.post("/stop")
|
|
||||||
async def stop_op25():
|
|
||||||
global op25_process
|
|
||||||
if op25_process is not None:
|
|
||||||
try:
|
|
||||||
os.killpg(os.getpgid(op25_process.pid), signal.SIGTERM)
|
|
||||||
op25_process = None
|
|
||||||
return {"status": "OP25 stopped"}
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
|
||||||
else:
|
|
||||||
return {"status": "OP25 is not running"}
|
|
||||||
|
|
||||||
@router.get("/status")
|
|
||||||
async def get_status():
|
|
||||||
return {"status": "running" if op25_process else "stopped"}
|
|
||||||
|
|
||||||
class DecodeMode(str, Enum):
|
|
||||||
P25 = "P25"
|
|
||||||
DMR = "DMR"
|
|
||||||
ANALOG = "NBFM"
|
|
||||||
|
|
||||||
class TalkgroupTag(BaseModel):
|
|
||||||
talkgroup: str
|
|
||||||
tagDec: int
|
|
||||||
|
|
||||||
class ConfigGenerator(BaseModel):
|
|
||||||
type: DecodeMode
|
|
||||||
systemName: str
|
|
||||||
channels: List[str]
|
|
||||||
tags: List[TalkgroupTag]
|
|
||||||
whitelist: List[int]
|
|
||||||
|
|
||||||
class DemodType(str, Enum):
|
|
||||||
CQPSK = "cqpsk"
|
|
||||||
FSK4 = "fsk4"
|
|
||||||
|
|
||||||
class FilterType(str, Enum):
|
|
||||||
RC = "rc"
|
|
||||||
WIDEPULSE = "widepulse"
|
|
||||||
|
|
||||||
class ChannelConfig(BaseModel):
|
|
||||||
name: str
|
|
||||||
trunking_sysname: Optional[str]
|
|
||||||
enable_analog: str
|
|
||||||
demod_type: DemodType
|
|
||||||
filter_type: FilterType
|
|
||||||
device: Optional[str] = "sdr"
|
|
||||||
cqpsk_tracking: Optional[bool] = None
|
|
||||||
frequency: Optional[float] = None
|
|
||||||
nbfmSquelch: Optional[float] = None
|
|
||||||
destination: Optional[str] = "udp://127.0.0.1:23456"
|
|
||||||
tracking_threshold: Optional[int] = 120
|
|
||||||
tracking_feedback: Optional[float] = 0.75
|
|
||||||
excess_bw: Optional[float] = 0.2
|
|
||||||
if_rate: Optional[int] = 24000
|
|
||||||
plot: Optional[str] = ""
|
|
||||||
symbol_rate: Optional[int] = 4800
|
|
||||||
blacklist: Optional[str] = ""
|
|
||||||
whitelist: Optional[str] = ""
|
|
||||||
|
|
||||||
class DeviceConfig(BaseModel):
|
|
||||||
args: Optional[str] = "rtl"
|
|
||||||
gains: Optional[str] = "lna:39"
|
|
||||||
gain_mode: Optional[bool] = False
|
|
||||||
name: Optional[str] = "sdr"
|
|
||||||
offset: Optional[int] = 0
|
|
||||||
ppm: Optional[float] = 0.0
|
|
||||||
rate: Optional[int] = 1920000
|
|
||||||
usable_bw_pct: Optional[float] = 0.85
|
|
||||||
tunable: Optional[bool] = True
|
|
||||||
|
|
||||||
class TrunkingChannelConfig(BaseModel):
|
|
||||||
sysname: str
|
|
||||||
control_channel_list: str
|
|
||||||
tagsFile: Optional[str] = None
|
|
||||||
whitelist: Optional[str] = None
|
|
||||||
nac: Optional[str] = ""
|
|
||||||
wacn: Optional[str] = ""
|
|
||||||
tdma_cc: Optional[bool] = False
|
|
||||||
crypt_behavior: Optional[int] = 2
|
|
||||||
|
|
||||||
class TrunkingConfig(BaseModel):
|
|
||||||
module: str
|
|
||||||
chans: List[TrunkingChannelConfig]
|
|
||||||
|
|
||||||
class AudioInstanceConfig(BaseModel):
|
|
||||||
instance_name: Optional[str] = "audio0"
|
|
||||||
device_name: Optional[str] = "pulse"
|
|
||||||
udp_port: Optional[int] = 23456
|
|
||||||
audio_gain: Optional[float] = 2.5
|
|
||||||
number_channels: Optional[int] = 1
|
|
||||||
|
|
||||||
class AudioConfig(BaseModel):
|
|
||||||
module: Optional[str] = "sockaudio.py"
|
|
||||||
instances: Optional[List[AudioInstanceConfig]] = [AudioInstanceConfig()]
|
|
||||||
|
|
||||||
class TerminalConfig(BaseModel):
|
|
||||||
module: Optional[str] = "terminal.py"
|
|
||||||
terminal_type: Optional[str] = "http:0.0.0.0:8081"
|
|
||||||
terminal_timeout: Optional[float] = 5.0
|
|
||||||
curses_plot_interval: Optional[float] = 0.2
|
|
||||||
http_plot_interval: Optional[float] = 1.0
|
|
||||||
http_plot_directory: Optional[str] = "../www/images"
|
|
||||||
tuning_step_large: Optional[int] = 1200
|
|
||||||
tuning_step_small: Optional[int] = 100
|
|
||||||
|
|
||||||
@router.post("/generate-config")
|
|
||||||
async def generate_config(generator: ConfigGenerator):
|
|
||||||
try:
|
|
||||||
if generator.type == DecodeMode.P25:
|
|
||||||
channels = [ChannelConfig(
|
|
||||||
name=generator.systemName,
|
|
||||||
trunking_sysname=generator.systemName,
|
|
||||||
enable_analog="off",
|
|
||||||
demod_type="cqpsk",
|
|
||||||
cqpsk_tracking=True,
|
|
||||||
filter_type="rc"
|
|
||||||
)]
|
|
||||||
devices = [DeviceConfig()]
|
|
||||||
save_talkgroup_tags(generator.tags)
|
|
||||||
save_whitelist(generator.whitelist)
|
|
||||||
trunking = TrunkingConfig(
|
|
||||||
module="tk_p25.py",
|
|
||||||
chans=[TrunkingChannelConfig(
|
|
||||||
sysname=generator.systemName,
|
|
||||||
control_channel_list=','.join(generator.channels),
|
|
||||||
tagsFile="/configs/active.cfg.tags.tsv",
|
|
||||||
whitelist="/configs/active.cfg.whitelist.tsv"
|
|
||||||
)]
|
|
||||||
)
|
|
||||||
|
|
||||||
audio = AudioConfig()
|
|
||||||
|
|
||||||
terminal = TerminalConfig()
|
|
||||||
|
|
||||||
config_dict = {
|
|
||||||
"channels": [channel.dict() for channel in channels],
|
|
||||||
"devices": [device.dict() for device in devices],
|
|
||||||
"trunking": trunking.dict(),
|
|
||||||
"audio": audio.dict(),
|
|
||||||
"terminal": terminal.dict()
|
|
||||||
}
|
|
||||||
|
|
||||||
elif generator.type == DecodeMode.ANALOG:
|
|
||||||
generator = generator.config
|
|
||||||
channels = [ChannelConfig(
|
|
||||||
channelName=generator.systemName,
|
|
||||||
enableAnalog="on",
|
|
||||||
demodType="fsk4",
|
|
||||||
frequency=generator.frequency,
|
|
||||||
filterType="widepulse",
|
|
||||||
nbfmSquelch=generator.nbfmSquelch
|
|
||||||
)]
|
|
||||||
devices = [DeviceConfig(gain="LNA:32")]
|
|
||||||
|
|
||||||
config_dict = {
|
|
||||||
"channels": [channel.dict() for channel in channels],
|
|
||||||
"devices": [device.dict() for device in devices]
|
|
||||||
}
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise HTTPException(status_code=400, detail="Invalid configuration type. Must be 'p25' or 'nbfm'.")
|
|
||||||
|
|
||||||
with open('/configs/active.cfg.json', 'w') as f:
|
|
||||||
json.dump(del_none_in_dict(config_dict), f, indent=2)
|
|
||||||
|
|
||||||
return {"message": "Config exported to '/configs/active.cfg.json'"}
|
|
||||||
except Exception as e:
|
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
|
||||||
|
|
||||||
def save_talkgroup_tags(talkgroup_tags: List[TalkgroupTag]) -> None:
|
|
||||||
"""
|
|
||||||
Writes a list of tags to the tags file.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
talkgroup_tags (List[TalkgroupTag]): The list of TalkgroupTag instances.
|
|
||||||
"""
|
|
||||||
with open("/configs/active.cfg.tags.tsv", 'w', newline='', encoding='utf-8') as file:
|
|
||||||
writer = csv.writer(file, delimiter='\t', lineterminator='\n')
|
|
||||||
# Write rows
|
|
||||||
for tag in talkgroup_tags:
|
|
||||||
writer.writerow([tag.talkgroup, tag.tagDec])
|
|
||||||
|
|
||||||
def save_whitelist(talkgroup_tags: List[int]) -> None:
|
|
||||||
"""
|
|
||||||
Writes a list of talkgroups to the whitelists file.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
talkgroup_tags (List[int]): The list of decimals to whitelist.
|
|
||||||
"""
|
|
||||||
with open("/configs/active.cfg.whitelist.tsv", 'w', newline='', encoding='utf-8') as file:
|
|
||||||
writer = csv.writer(file, delimiter='\t', lineterminator='\n')
|
|
||||||
# Write rows
|
|
||||||
for tag in talkgroup_tags:
|
|
||||||
writer.writerow([tag])
|
|
||||||
|
|
||||||
def del_none_in_dict(d):
|
|
||||||
"""
|
|
||||||
Delete keys with the value ``None`` in a dictionary, recursively.
|
|
||||||
|
|
||||||
This alters the input so you may wish to ``copy`` the dict first.
|
|
||||||
"""
|
|
||||||
for key, value in list(d.items()):
|
|
||||||
print(f"Key: '{key}'\nValue: '{value}'")
|
|
||||||
if value is None:
|
|
||||||
del d[key]
|
|
||||||
elif isinstance(value, dict):
|
|
||||||
del_none_in_dict(value)
|
|
||||||
elif isinstance(value, list):
|
|
||||||
for iterative_value in value:
|
|
||||||
del_none_in_dict(iterative_value)
|
|
||||||
return d # For convenience
|
|
||||||
58
app/routers/bot.py
Normal file
58
app/routers/bot.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException
|
||||||
|
from models import BotConfig, VoiceChannelJoinRequest, VoiceChannelLeaveRequest
|
||||||
|
from internal.bot_manager import DiscordBotManager
|
||||||
|
from internal.logger import create_logger
|
||||||
|
|
||||||
|
LOGGER = create_logger(__name__)
|
||||||
|
|
||||||
|
# Function to create router
|
||||||
|
def create_bot_router(bot_manager: DiscordBotManager):
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
# API Endpoints
|
||||||
|
@router.post("/start_bot")
|
||||||
|
async def start_bot(config: BotConfig):
|
||||||
|
try:
|
||||||
|
await bot_manager.start_bot(config.token)
|
||||||
|
return {"status": "Bot started successfully."}
|
||||||
|
except Exception as e:
|
||||||
|
LOGGER.error(f"Error starting bot: {e}")
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
@router.post("/stop_bot")
|
||||||
|
async def stop_bot():
|
||||||
|
try:
|
||||||
|
await bot_manager.stop_bot()
|
||||||
|
return {"status": "Bot stopped successfully."}
|
||||||
|
except Exception as e:
|
||||||
|
LOGGER.error(f"Error stopping bot: {e}")
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
@router.post("/join_voice")
|
||||||
|
async def join_voice_channel(request: VoiceChannelJoinRequest):
|
||||||
|
try:
|
||||||
|
await bot_manager.join_voice_channel(request.guild_id, request.channel_id)
|
||||||
|
return {"status": f"Joined guild {request.guild_id} voice channel {request.channel_id}."}
|
||||||
|
except Exception as e:
|
||||||
|
LOGGER.error(f"Error joining voice channel: {e}")
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
@router.post("/leave_voice")
|
||||||
|
async def leave_voice_channel(request: VoiceChannelLeaveRequest):
|
||||||
|
try:
|
||||||
|
await bot_manager.leave_voice_channel(request.guild_id)
|
||||||
|
return {"status": f"Left guild {request.guild_id} voice channel."}
|
||||||
|
except Exception as e:
|
||||||
|
LOGGER.error(f"Error leaving voice channel: {e}")
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
|
||||||
|
@router.get("/status")
|
||||||
|
async def get_status():
|
||||||
|
status = {
|
||||||
|
"bot_running": bot_manager.bot is not None and not bot_manager.bot.is_closed(),
|
||||||
|
"connected_guilds": list(bot_manager.voice_clients.keys()),
|
||||||
|
"active_token": bot_manager.token
|
||||||
|
}
|
||||||
|
return status
|
||||||
|
|
||||||
|
return router
|
||||||
126
app/routers/op25_controller.py
Normal file
126
app/routers/op25_controller.py
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
from fastapi import HTTPException, APIRouter
|
||||||
|
import subprocess
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import json
|
||||||
|
from models import ConfigGenerator, DecodeMode, ChannelConfig, DeviceConfig, TrunkingConfig, TrunkingChannelConfig, AudioConfig, TerminalConfig
|
||||||
|
from internal.logger import create_logger
|
||||||
|
from internal.bot_manager import DiscordBotManager
|
||||||
|
from internal.op25_config_utls import save_talkgroup_tags, save_whitelist, del_none_in_dict, get_current_system_from_config
|
||||||
|
|
||||||
|
LOGGER = create_logger(__name__)
|
||||||
|
|
||||||
|
op25_process = None
|
||||||
|
OP25_PATH = "/op25/op25/gr-op25_repeater/apps/"
|
||||||
|
OP25_SCRIPT = "run_multi-rx_service.sh"
|
||||||
|
|
||||||
|
def create_op25_router(bot_manager: DiscordBotManager):
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post("/start")
|
||||||
|
async def start_op25():
|
||||||
|
global op25_process
|
||||||
|
if op25_process is None:
|
||||||
|
try:
|
||||||
|
op25_process = subprocess.Popen(os.path.join(OP25_PATH, OP25_SCRIPT), shell=True, preexec_fn=os.setsid, cwd=OP25_PATH)
|
||||||
|
LOGGER.debug(op25_process)
|
||||||
|
return {"status": "OP25 started"}
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
else:
|
||||||
|
return {"status": "OP25 already running"}
|
||||||
|
|
||||||
|
@router.post("/stop")
|
||||||
|
async def stop_op25():
|
||||||
|
global op25_process
|
||||||
|
if op25_process is not None:
|
||||||
|
try:
|
||||||
|
os.killpg(os.getpgid(op25_process.pid), signal.SIGTERM)
|
||||||
|
op25_process = None
|
||||||
|
return {"status": "OP25 stopped"}
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
else:
|
||||||
|
return {"status": "OP25 is not running"}
|
||||||
|
|
||||||
|
@router.get("/status")
|
||||||
|
async def get_status():
|
||||||
|
return {"status": "running" if op25_process else "stopped"}
|
||||||
|
|
||||||
|
@router.post("/generate-config")
|
||||||
|
async def generate_config(generator: ConfigGenerator):
|
||||||
|
try:
|
||||||
|
if generator.type == DecodeMode.P25:
|
||||||
|
channels = [ChannelConfig(
|
||||||
|
name=generator.systemName,
|
||||||
|
trunking_sysname=generator.systemName,
|
||||||
|
enable_analog="off",
|
||||||
|
demod_type="cqpsk",
|
||||||
|
cqpsk_tracking=True,
|
||||||
|
filter_type="rc"
|
||||||
|
)]
|
||||||
|
devices = [DeviceConfig()]
|
||||||
|
save_talkgroup_tags(generator.tags)
|
||||||
|
save_whitelist(generator.whitelist)
|
||||||
|
trunking = TrunkingConfig(
|
||||||
|
module="tk_p25.py",
|
||||||
|
chans=[TrunkingChannelConfig(
|
||||||
|
sysname=generator.systemName,
|
||||||
|
control_channel_list=','.join(generator.channels),
|
||||||
|
tagsFile="/configs/active.cfg.tags.tsv",
|
||||||
|
whitelist="/configs/active.cfg.whitelist.tsv"
|
||||||
|
)]
|
||||||
|
)
|
||||||
|
|
||||||
|
audio = AudioConfig()
|
||||||
|
|
||||||
|
terminal = TerminalConfig()
|
||||||
|
|
||||||
|
config_dict = {
|
||||||
|
"channels": [channel.dict() for channel in channels],
|
||||||
|
"devices": [device.dict() for device in devices],
|
||||||
|
"trunking": trunking.dict(),
|
||||||
|
"audio": audio.dict(),
|
||||||
|
"terminal": terminal.dict()
|
||||||
|
}
|
||||||
|
|
||||||
|
elif generator.type == DecodeMode.ANALOG:
|
||||||
|
generator = generator.config
|
||||||
|
channels = [ChannelConfig(
|
||||||
|
channelName=generator.systemName,
|
||||||
|
enableAnalog="on",
|
||||||
|
demodType="fsk4",
|
||||||
|
frequency=generator.frequency,
|
||||||
|
filterType="widepulse",
|
||||||
|
nbfmSquelch=generator.nbfmSquelch
|
||||||
|
)]
|
||||||
|
devices = [DeviceConfig(gain="LNA:32")]
|
||||||
|
|
||||||
|
config_dict = {
|
||||||
|
"channels": [channel.dict() for channel in channels],
|
||||||
|
"devices": [device.dict() for device in devices]
|
||||||
|
}
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid configuration type. Must be 'p25' or 'nbfm'.")
|
||||||
|
|
||||||
|
with open('/configs/active.cfg.json', 'w') as f:
|
||||||
|
json.dump(del_none_in_dict(config_dict), f, indent=2)
|
||||||
|
|
||||||
|
# Set the presence of the bot (if it's online)
|
||||||
|
await bot_manager.set_presence(generator.systemName)
|
||||||
|
|
||||||
|
return {"message": "Config exported to '/configs/active.cfg.json'"}
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
|
@router.post("/update-presence")
|
||||||
|
async def update_presence():
|
||||||
|
current_system = get_current_system_from_config()
|
||||||
|
if not current_system:
|
||||||
|
raise HTTPException(status_code=500, detail="Unable to get current system.")
|
||||||
|
|
||||||
|
await bot_manager.set_presence(current_system)
|
||||||
|
return current_system
|
||||||
|
|
||||||
|
return router
|
||||||
15
op25-liq.service
Normal file
15
op25-liq.service
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=op25-liq
|
||||||
|
After=syslog.target network.target nss-lookup.target network-online.target
|
||||||
|
Requires=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=1000
|
||||||
|
Group=1000
|
||||||
|
WorkingDirectory=/op25/op25/gr-op25_repeater/apps
|
||||||
|
ExecStart=/usr/bin/liquidsoap op25.liq
|
||||||
|
RestartSec=5
|
||||||
|
Restart=on-failure
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -4,5 +4,4 @@ numpy==1.24.3
|
|||||||
uvicorn
|
uvicorn
|
||||||
fastapi
|
fastapi
|
||||||
pyaudio
|
pyaudio
|
||||||
argparse
|
argparse
|
||||||
pyaudio
|
|
||||||
Reference in New Issue
Block a user