deleted tnc folder, moved to modem folder

This commit is contained in:
DJ2LS 2023-10-20 14:12:20 +02:00
parent b11e820ebc
commit 5d0d008cdc
57 changed files with 639 additions and 619 deletions

View file

@ -200,21 +200,21 @@ jobs:
zip_name: ubuntu_tnc zip_name: ubuntu_tnc
generator: Unix Makefiles generator: Unix Makefiles
daemon_binary_name: freedata-daemon daemon_binary_name: freedata-daemon
tnc_binary_name: freedata-tnc tnc_binary_name: freedata-modem
electron_parameters: "-p always" electron_parameters: "-p always"
- os: macos-11 - os: macos-11
zip_name: macos_tnc zip_name: macos_tnc
generator: Unix Makefiles generator: Unix Makefiles
daemon_binary_name: freedata-daemon daemon_binary_name: freedata-daemon
tnc_binary_name: freedata-tnc tnc_binary_name: freedata-modem
electron_parameters: "-p always" electron_parameters: "-p always"
- os: windows-latest - os: windows-latest
zip_name: windows_tnc zip_name: windows_tnc
generator: Visual Studio 16 2019 generator: Visual Studio 16 2019
daemon_binary_name: freedata-daemon.exe daemon_binary_name: freedata-daemon.exe
tnc_binary_name: freedata-tnc.exe tnc_binary_name: freedata-modem.exe
electron_parameters: "-p always --x64 --ia32" electron_parameters: "-p always --x64 --ia32"
steps: steps:
- name: Checkout code for ${{ matrix.platform.name }} - name: Checkout code for ${{ matrix.platform.name }}
@ -232,30 +232,30 @@ jobs:
with: with:
node-version: 18.17 node-version: 18.17
- name: Create tnc/dist - name: Create modem/dist
working-directory: tnc working-directory: modem
run: | run: |
mkdir -p dist mkdir -p dist
- name: Create tnc/dist/tnc - name: Create modem/dist/modem
working-directory: tnc working-directory: modem
run: | run: |
mkdir -p dist/tnc mkdir -p dist/tnc
##- name: Download libcodec2 artifact TNC DIST ##- name: Download libcodec2 artifact TNC DIST
## uses: actions/download-artifact@v3 ## uses: actions/download-artifact@v3
## with: ## with:
## path: tnc/dist/codec2 ## path: modem/dist/codec2
- name: create tnc/lib/codec2 - name: create modem/lib/codec2
working-directory: tnc/lib/ working-directory: modem/lib/
run: | run: |
mkdir codec2 mkdir codec2
- name: Download libcodec2 artifact TNC LIB - name: Download libcodec2 artifact TNC LIB
uses: actions/download-artifact@v3 uses: actions/download-artifact@v3
with: with:
path: tnc/lib/codec2 path: modem/lib/codec2
- name: Install Linux dependencies - name: Install Linux dependencies
@ -285,7 +285,7 @@ jobs:
- name: Build binaries macOS - name: Build binaries macOS
if: ${{startsWith(matrix.os, 'macos')}} if: ${{startsWith(matrix.os, 'macos')}}
working-directory: tnc working-directory: modem
run: | run: |
# now build tnc binaries # now build tnc binaries
pyinstaller -y freedata.spec pyinstaller -y freedata.spec
@ -295,7 +295,7 @@ jobs:
- name: Build binaries Linux and Windows - name: Build binaries Linux and Windows
if: ${{!startsWith(matrix.os, 'macos')}} if: ${{!startsWith(matrix.os, 'macos')}}
working-directory: tnc working-directory: modem
run: | run: |
# pyinstaller freedata.spec # pyinstaller freedata.spec
# python3 -m nuitka --enable-plugin=numpy --assume-yes-for-downloads --onefile daemon.py -o ${{ matrix.daemon_binary_name }} # python3 -m nuitka --enable-plugin=numpy --assume-yes-for-downloads --onefile daemon.py -o ${{ matrix.daemon_binary_name }}
@ -305,30 +305,30 @@ jobs:
- name: Copy binaries - Linux - name: Copy binaries - Linux
if: ${{startsWith(matrix.os, 'ubuntu')}} if: ${{startsWith(matrix.os, 'ubuntu')}}
working-directory: tnc working-directory: modem
run: | run: |
cp -r -f daemon.dist/* dist/tnc cp -r -f daemon.dist/* dist/tnc
cp -r -f main.dist/* dist/tnc cp -r -f main.dist/* dist/tnc
- name: Copy binaries - Windows - name: Copy binaries - Windows
if: ${{startsWith(matrix.os, 'windows')}} if: ${{startsWith(matrix.os, 'windows')}}
working-directory: tnc working-directory: modem
# These are powershell aliases, not UNIX commands. # These are powershell aliases, not UNIX commands.
run: | run: |
cp -r -Force daemon.dist/* dist/tnc cp -r -Force daemon.dist/* dist/tnc
cp -r -Force main.dist/* dist/tnc cp -r -Force main.dist/* dist/tnc
- name: Rename tnc binaries - name: Rename modem binaries
# we don't need renaming for pyinstaller builds as output name is defined # we don't need renaming for pyinstaller builds as output name is defined
if: ${{!startsWith(matrix.os, 'macos')}} if: ${{!startsWith(matrix.os, 'macos')}}
working-directory: tnc working-directory: modem
run: | run: |
mv dist/tnc/daemon* dist/tnc/${{ matrix.daemon_binary_name }} mv dist/tnc/daemon* dist/tnc/${{ matrix.daemon_binary_name }}
mv dist/tnc/main* dist/tnc/${{ matrix.tnc_binary_name }} mv dist/tnc/main* dist/tnc/${{ matrix.tnc_binary_name }}
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v3
with: with:
path: tnc/dist/tnc path: modem/dist/modem
- name: LIST ALL FILES - name: LIST ALL FILES
@ -336,7 +336,7 @@ jobs:
- name: Download Portaudio binaries Linux macOS - name: Download Portaudio binaries Linux macOS
if: ${{!startsWith(matrix.os, 'windows')}} if: ${{!startsWith(matrix.os, 'windows')}}
working-directory: tnc working-directory: modem
run: | run: |
if ! test -d "dist/tnc/_sounddevice_data"; then if ! test -d "dist/tnc/_sounddevice_data"; then
git clone https://github.com/spatialaudio/portaudio-binaries dist/tnc/_sounddevice_data/portaudio-binaries git clone https://github.com/spatialaudio/portaudio-binaries dist/tnc/_sounddevice_data/portaudio-binaries
@ -344,7 +344,7 @@ jobs:
- name: Download Portaudio binaries Windows - name: Download Portaudio binaries Windows
if: ${{startsWith(matrix.os, 'windows')}} if: ${{startsWith(matrix.os, 'windows')}}
working-directory: tnc working-directory: modem
run: | run: |
if(Test-Path -Path "dist/tnc/_sounddevice_data"){ if(Test-Path -Path "dist/tnc/_sounddevice_data"){
echo "sounddevice folder already exists" echo "sounddevice folder already exists"
@ -382,8 +382,8 @@ jobs:
with: with:
type: 'zip' type: 'zip'
filename: '${{ matrix.zip_name }}.zip' filename: '${{ matrix.zip_name }}.zip'
# directory: ./tnc/dist/tnc # directory: ./modem/dist/modem
directory: ./tnc/dist/tnc directory: ./modem/dist/modem
path: . path: .
# exclusions: '*.git* /*node_modules/* .editorconfig' # exclusions: '*.git* /*node_modules/* .editorconfig'
@ -391,8 +391,8 @@ jobs:
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v1
if: startsWith(github.ref, 'refs/tags/v') if: startsWith(github.ref, 'refs/tags/v')
with: with:
files: ./tnc/dist/tnc/${{ matrix.zip_name }}.zip files: ./modem/dist/modem/${{ matrix.zip_name }}.zip
#files: ./tnc/dist/${{ matrix.zip_name }}.zip #files: ./modem/dist/${{ matrix.zip_name }}.zip
- name: LIST ALL FILES - name: LIST ALL FILES
run: ls -R run: ls -R
@ -402,13 +402,13 @@ jobs:
# if: ${{!startsWith(github.ref, 'refs/tags/v')}} # if: ${{!startsWith(github.ref, 'refs/tags/v')}}
# with: # with:
# name: ${{ matrix.zip_name }}.zip # name: ${{ matrix.zip_name }}.zip
# # path: ./tnc/dist/tnc/${{ matrix.zip_name }}.zip # # path: ./modem/dist/modem/${{ matrix.zip_name }}.zip
# path: ./tnc/dist/tnc/${{ matrix.zip_name }}.zip# # path: ./modem/dist/modem/${{ matrix.zip_name }}.zip#
#- name: Upload App bundle artifacts #- name: Upload App bundle artifacts
# uses: actions/upload-artifact@v3 # uses: actions/upload-artifact@v3
# if: ${{!startsWith(github.ref, 'refs/tags/v')}} # if: ${{!startsWith(github.ref, 'refs/tags/v')}}
# with: # with:
# name: app_bundle_${{ matrix.os }}.zip # name: app_bundle_${{ matrix.os }}.zip
# # path: ./tnc/dist/tnc/${{ matrix.zip_name }}.zip # # path: ./modem/dist/modem/${{ matrix.zip_name }}.zip
# path: ./gui/dist/* # path: ./gui/dist/*

4
.gitignore vendored
View file

@ -1,5 +1,5 @@
# possible installation of codec2 within tnc # possible installation of codec2 within modem
tnc/codec2 modem/codec2
# temporary test artifacts # temporary test artifacts
**/build **/build

View file

View file

@ -4,7 +4,7 @@ import helpers
import time import time
import modem import modem
import base64 import base64
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem
import sock import sock
import ujson as json import ujson as json
@ -34,7 +34,7 @@ class broadcastHandler:
modem.RECEIVE_DATAC4 = True modem.RECEIVE_DATAC4 = True
self.send_data_to_socket_queue( self.send_data_to_socket_queue(
freedata="tnc-message", freedata="modem-message",
fec="wakeup", fec="wakeup",
mode=self.wakeup_mode, mode=self.wakeup_mode,
bursts=bursts, bursts=bursts,
@ -42,7 +42,7 @@ class broadcastHandler:
) )
self.log.info( self.log.info(
"[TNC] FRAME WAKEUP RCVD [" "[Modem] FRAME WAKEUP RCVD ["
+ str(self.fec_wakeup_callsign, "UTF-8") + str(self.fec_wakeup_callsign, "UTF-8")
+ "] ", mode=self.wakeup_mode, bursts=bursts, + "] ", mode=self.wakeup_mode, bursts=bursts,
) )
@ -51,13 +51,13 @@ class broadcastHandler:
print(self.fec_wakeup_callsign) print(self.fec_wakeup_callsign)
self.send_data_to_socket_queue( self.send_data_to_socket_queue(
freedata="tnc-message", freedata="modem-message",
fec="broadcast", fec="broadcast",
dxcallsign=str(self.fec_wakeup_callsign, "UTF-8"), dxcallsign=str(self.fec_wakeup_callsign, "UTF-8"),
data=base64.b64encode(data_in[1:]).decode("UTF-8") data=base64.b64encode(data_in[1:]).decode("UTF-8")
) )
self.log.info("[TNC] FEC DATA RCVD") self.log.info("[Modem] FEC DATA RCVD")
def send_data_to_socket_queue(self, **jsondata): def send_data_to_socket_queue(self, **jsondata):
""" """
@ -67,7 +67,7 @@ class broadcastHandler:
Dictionary containing the data to be sent, in the format: Dictionary containing the data to be sent, in the format:
key=value, for each item. E.g.: key=value, for each item. E.g.:
self.send_data_to_socket_queue( self.send_data_to_socket_queue(
freedata="tnc-message", freedata="modem-message",
arq="received", arq="received",
status="success", status="success",
uuid=self.transmission_uuid, uuid=self.transmission_uuid,
@ -87,12 +87,12 @@ class broadcastHandler:
if "dxcallsign" not in jsondata: if "dxcallsign" not in jsondata:
jsondata["dxcallsign"] = str(Station.dxcallsign, "UTF-8") jsondata["dxcallsign"] = str(Station.dxcallsign, "UTF-8")
except Exception as e: except Exception as e:
self.log.debug("[TNC] error adding callsigns to network message", e=e) self.log.debug("[Modem] error adding callsigns to network message", e=e)
# run json dumps # run json dumps
json_data_out = json.dumps(jsondata) json_data_out = json.dumps(jsondata)
self.log.debug("[TNC] send_data_to_socket_queue:", jsondata=json_data_out) self.log.debug("[Modem] send_data_to_socket_queue:", jsondata=json_data_out)
# finally push data to our network queue # finally push data to our network queue
sock.SOCKET_QUEUE.put(json_data_out) sock.SOCKET_QUEUE.put(json_data_out)
@ -106,7 +106,7 @@ class broadcastHandler:
self.broadcast_timeout_reached = True self.broadcast_timeout_reached = True
self.log.info( self.log.info(
"[TNC] closing broadcast slot [" "[Modem] closing broadcast slot ["
+ str(self.fec_wakeup_callsign, "UTF-8") + str(self.fec_wakeup_callsign, "UTF-8")
+ "] ", mode=self.wakeup_mode, bursts=self.broadcast_payload_bursts, + "] ", mode=self.wakeup_mode, bursts=self.broadcast_payload_bursts,
) )

View file

@ -0,0 +1 @@
{"DJ2LS-0": "22864b", "IW2DHW-0": "fcef94", "BEACON": "5492c7", "EI7IG-0": "0975c8", "G0HWW-0": "2cb363", "LA3QMA-0": "2b9fac", "EA7KOH-0": "9e1c3e", "OK6MS-0": "5f75ed", "N1QM-0": "e045a0"}

View file

@ -45,7 +45,7 @@ class CONFIG:
write entire config write entire config
""" """
self.config['NETWORK'] = {'#Network settings': None, self.config['NETWORK'] = {'#Network settings': None,
'TNCPORT': data[50] 'ModemPORT': data[50]
} }
self.config['STATION'] = {'#Station settings': None, self.config['STATION'] = {'#Station settings': None,
@ -66,7 +66,7 @@ class CONFIG:
'rigctld_ip': data[6], 'rigctld_ip': data[6],
'rigctld_port': data[7] 'rigctld_port': data[7]
} }
self.config['TNC'] = {'#TNC settings': None, self.config['Modem'] = {'#Modem settings': None,
'scatter': data[8], 'scatter': data[8],
'fft': data[9], 'fft': data[9],
'narrowband': data[10], 'narrowband': data[10],

70
modem/cw.py Normal file
View file

@ -0,0 +1,70 @@
import numpy as np
"""
morse code generator
MorseCodePlayer().text_to_signal("DJ2LS-1")
"""
class MorseCodePlayer:
def __init__(self, wpm=150, f=1500, fs=48000):
self.wpm = wpm
self.f0 = f
self.fs = fs
self.dot_duration = 1.2/(self.wpm)
self.dash_duration = 3*self.dot_duration
self.pause_duration = self.dot_duration
self.word_pause_duration = 7*self.dot_duration
self.morse_alphabet = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....',
'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.',
'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-',
'5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '.': '.-.-.-', ',': '--..--',
'?': '..--..', "'": '.----.', '!': '-.-.--', '/': '-..-.', '(': '-.--.', ')': '-.--.-', '&': '.-...',
':': '---...', ';': '-.-.-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '_': '..--.-', '"': '.-..-.',
'$': '...-..-', '@': '.--.-.'
}
def text_to_morse(self, text):
morse = ''
for char in text:
if char.upper() in self.morse_alphabet:
morse += self.morse_alphabet[char.upper()] + ' '
elif char == ' ':
morse += ' '
return morse
def morse_to_signal(self, morse):
signal = np.array([], dtype=np.int16)
for char in morse:
if char == '.':
duration = int(self.dot_duration * self.fs)
s = np.sin(2 * np.pi * self.f0 * np.arange(duration) / self.fs)
signal = np.concatenate((signal, s * 32767))
pause_duration = int(self.pause_duration * self.fs)
signal = np.concatenate((signal, np.zeros(pause_duration, dtype=np.int16)))
elif char == '-':
duration = int(self.dash_duration * self.fs)
s = np.sin(2 * np.pi * self.f0 * np.arange(duration) / self.fs)
signal = np.concatenate((signal, s * 32767))
pause_duration = int(self.pause_duration * self.fs)
signal = np.concatenate((signal, np.zeros(pause_duration, dtype=np.int16)))
elif char == ' ':
pause_duration = int(self.word_pause_duration * self.fs)
signal = np.concatenate((signal, np.zeros(pause_duration, dtype=np.int16)))
pause_duration = int(self.pause_duration * self.fs)
signal = np.concatenate((signal, np.zeros(pause_duration, dtype=np.int16)))
pause_duration = int(self.word_pause_duration * self.fs)
#signal = np.concatenate((signal, np.zeros(pause_duration, dtype=np.int16)))
# Convert the signal to mono (single-channel)
#signal = signal.reshape(-1, 1)
return signal
def text_to_signal(self, text):
morse = self.text_to_morse(text)
return self.morse_to_signal(morse)

View file

@ -5,7 +5,7 @@ daemon.py
Author: DJ2LS, January 2022 Author: DJ2LS, January 2022
daemon for providing basic information for the tnc like audio or serial devices daemon for providing basic information for the modem like audio or serial devices
""" """
# pylint: disable=invalid-name, line-too-long, c-extension-no-member # pylint: disable=invalid-name, line-too-long, c-extension-no-member
@ -26,7 +26,7 @@ import crcengine
import log_handler import log_handler
import serial.tools.list_ports import serial.tools.list_ports
import sock import sock
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem
import structlog import structlog
import ujson as json import ujson as json
@ -83,7 +83,7 @@ class DAEMON:
""" """
while True: while True:
try: try:
if not Daemon.tncstarted: if not Daemon.modemstarted:
( (
AudioParam.audio_input_devices, AudioParam.audio_input_devices,
AudioParam.audio_output_devices, AudioParam.audio_output_devices,
@ -153,8 +153,8 @@ class DAEMON:
# data[20] stats # data[20] stats
# data[21] tx_delay # data[21] tx_delay
if data[0] == "STARTTNC": if data[0] == "STARTModem":
self.start_tnc(data) self.start_modem(data)
if data[0] == "TEST_HAMLIB": if data[0] == "TEST_HAMLIB":
# data[9] radiocontrol # data[9] radiocontrol
@ -387,8 +387,8 @@ class DAEMON:
def start_tnc(self, data): def start_modem(self, data):
self.log.warning("[DMN] Starting TNC", rig=data[5], port=data[6]) self.log.warning("[DMN] Starting Modem", rig=data[5], port=data[6])
# list of parameters, necessary for running subprocess command as a list # list of parameters, necessary for running subprocess command as a list
options = ["--port", str(DAEMON.port - 1)] options = ["--port", str(DAEMON.port - 1)]
@ -467,8 +467,8 @@ class DAEMON:
# safe data to config file # safe data to config file
config.write_entire_config(data) config.write_entire_config(data)
# Try running tnc from binary, else run from source # Try running modem from binary, else run from source
# This helps running the tnc in a developer environment # This helps running the modem in a developer environment
try: try:
command = [] command = []
@ -477,12 +477,12 @@ class DAEMON:
# extends the sys module by a flag frozen=True and sets the app # extends the sys module by a flag frozen=True and sets the app
# path into variable _MEIPASS'. # path into variable _MEIPASS'.
application_path = sys._MEIPASS application_path = sys._MEIPASS
command.append(f'{application_path}/freedata-tnc') command.append(f'{application_path}/freedata-modem')
elif sys.platform in ["linux", "darwin"]: elif sys.platform in ["linux", "darwin"]:
command.append("./freedata-tnc") command.append("./freedata-modem")
elif sys.platform in ["win32", "win64"]: elif sys.platform in ["win32", "win64"]:
command.append("freedata-tnc.exe") command.append("freedata-modem.exe")
command += options command += options
@ -490,11 +490,11 @@ class DAEMON:
atexit.register(proc.kill) atexit.register(proc.kill)
Daemon.tncprocess = proc Daemon.modemprocess = proc
Daemon.tncstarted = True Daemon.modemstarted = True
self.log.info("[DMN] TNC started", path="binary") self.log.info("[DMN] Modem started", path="binary")
except FileNotFoundError as err1: except FileNotFoundError as err1:
try: try:
@ -511,13 +511,13 @@ class DAEMON:
proc = subprocess.Popen(command) proc = subprocess.Popen(command)
atexit.register(proc.kill) atexit.register(proc.kill)
self.log.info("[DMN] TNC started", path="source") self.log.info("[DMN] Modem started", path="source")
Daemon.tncprocess = proc Daemon.modemprocess = proc
Daemon.tncstarted = True Daemon.modemstarted = True
except Exception as e: except Exception as e:
self.log.error("[DMN] TNC not started", error=e) self.log.error("[DMN] Modem not started", error=e)
Daemon.tncstarted = False Daemon.modemstarted = False
@ -569,7 +569,7 @@ if __name__ == "__main__":
# https://stackoverflow.com/a/16641793 # https://stackoverflow.com/a/16641793
socketserver.TCPServer.allow_reuse_address = True socketserver.TCPServer.allow_reuse_address = True
cmdserver = sock.ThreadedTCPServer( cmdserver = sock.ThreadedTCPServer(
(TNC.host, DAEMON.port), sock.ThreadedTCPRequestHandler (Modem.host, DAEMON.port), sock.ThreadedTCPRequestHandler
) )
server_thread = threading.Thread(target=cmdserver.serve_forever) server_thread = threading.Thread(target=cmdserver.serve_forever)
server_thread.daemon = True server_thread.daemon = True
@ -586,7 +586,7 @@ if __name__ == "__main__":
"[DMN] Starting FreeDATA Daemon", "[DMN] Starting FreeDATA Daemon",
author="DJ2LS", author="DJ2LS",
year="2023", year="2023",
version=TNC.version, version=Modem.version,
) )
while True: while True:
threading.Event().wait(1) threading.Event().wait(1)

File diff suppressed because it is too large Load diff

View file

@ -13,7 +13,7 @@ import time
import ujson as json import ujson as json
import structlog import structlog
import static import static
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem
log = structlog.get_logger("explorer") log = structlog.get_logger("explorer")
@ -38,8 +38,8 @@ class explorer():
band = "USB" band = "USB"
callsign = str(Station.mycallsign, "utf-8") callsign = str(Station.mycallsign, "utf-8")
gridsquare = str(Station.mygrid, "utf-8") gridsquare = str(Station.mygrid, "utf-8")
version = str(TNC.version) version = str(Modem.version)
bandwidth = str(TNC.low_bandwidth_mode) bandwidth = str(Modem.low_bandwidth_mode)
beacon = str(Beacon.beacon_state) beacon = str(Beacon.beacon_state)
strength = str(HamlibParam.hamlib_strength) strength = str(HamlibParam.hamlib_strength)
@ -48,7 +48,7 @@ class explorer():
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
station_data = {'callsign': callsign, 'gridsquare': gridsquare, 'frequency': frequency, 'strength': strength, 'band': band, 'version': version, 'bandwidth': bandwidth, 'beacon': beacon, "lastheard": []} station_data = {'callsign': callsign, 'gridsquare': gridsquare, 'frequency': frequency, 'strength': strength, 'band': band, 'version': version, 'bandwidth': bandwidth, 'beacon': beacon, "lastheard": []}
for i in TNC.heard_stations: for i in Modem.heard_stations:
try: try:
callsign = str(i[0], "UTF-8") callsign = str(i[0], "UTF-8")
grid = str(i[1], "UTF-8") grid = str(i[1], "UTF-8")

View file

@ -41,8 +41,8 @@ daemon_a.datas += Tree('lib', prefix='lib')
# daemon_a.datas += Tree('./codec2', prefix='codec2') # daemon_a.datas += Tree('./codec2', prefix='codec2')
# TNC -------------------------------------------------- # Modem --------------------------------------------------
tnc_a = Analysis(['main.py'], modem_a = Analysis(['main.py'],
pathex=[], pathex=[],
binaries=[], binaries=[],
datas=[], datas=[],
@ -55,15 +55,15 @@ tnc_a = Analysis(['main.py'],
win_private_assemblies=False, win_private_assemblies=False,
cipher=block_cipher, cipher=block_cipher,
noarchive=False) noarchive=False)
tnc_pyz = PYZ(tnc_a.pure, tnc_a.zipped_data, modem_pyz = PYZ(modem_a.pure, modem_a.zipped_data,
cipher=block_cipher) cipher=block_cipher)
tnc_exe = EXE(tnc_pyz, modem_exe = EXE(modem_pyz,
tnc_a.scripts, modem_a.scripts,
[], [],
exclude_binaries=True, exclude_binaries=True,
name='freedata-tnc', name='freedata-modem',
bundle_identifier='com.dj2ls.freedata-tnc', bundle_identifier='com.dj2ls.freedata-modem',
debug=False, debug=False,
bootloader_ignore_signals=False, bootloader_ignore_signals=False,
strip=False, strip=False,
@ -79,11 +79,11 @@ coll = COLLECT(daemon_exe,
daemon_a.binaries, daemon_a.binaries,
daemon_a.zipfiles, daemon_a.zipfiles,
daemon_a.datas, daemon_a.datas,
tnc_exe, modem_exe,
tnc_a.binaries, modem_a.binaries,
tnc_a.zipfiles, modem_a.zipfiles,
tnc_a.datas, modem_a.datas,
strip=False, strip=False,
upx=True, upx=True,
upx_exclude=[], upx_exclude=[],
name='tnc') name='modem')

View file

@ -1,6 +1,6 @@
# global_instances.py # global_instances.py
from static import Daemon, ARQ, AudioParam, Beacon, Channel, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC, MeshParam from static import Daemon, ARQ, AudioParam, Beacon, Channel, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem, MeshParam
# Initialize instances with appropriate default values # Initialize instances with appropriate default values
@ -15,5 +15,5 @@ ModemParam = ModemParam()
Station = Station() Station = Station()
Statistics = Statistics() Statistics = Statistics()
TCIParam = TCIParam() TCIParam = TCIParam()
TNC = TNC() Modem = Modem()
MeshParam = MeshParam() MeshParam = MeshParam()

View file

@ -8,7 +8,7 @@ import time
from datetime import datetime,timezone from datetime import datetime,timezone
import crcengine import crcengine
import static import static
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC, MeshParam from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem, MeshParam
import structlog import structlog
import numpy as np import numpy as np
import threading import threading
@ -139,16 +139,16 @@ def add_to_heard_stations(dxcallsign, dxgrid, datatype, snr, offset, frequency):
Nothing Nothing
""" """
# check if buffer empty # check if buffer empty
if len(TNC.heard_stations) == 0: if len(Modem.heard_stations) == 0:
TNC.heard_stations.append( Modem.heard_stations.append(
[dxcallsign, dxgrid, int(datetime.now(timezone.utc).timestamp()), datatype, snr, offset, frequency] [dxcallsign, dxgrid, int(datetime.now(timezone.utc).timestamp()), datatype, snr, offset, frequency]
) )
# if not, we search and update # if not, we search and update
else: else:
for i in range(len(TNC.heard_stations)): for i in range(len(Modem.heard_stations)):
# Update callsign with new timestamp # Update callsign with new timestamp
if TNC.heard_stations[i].count(dxcallsign) > 0: if Modem.heard_stations[i].count(dxcallsign) > 0:
TNC.heard_stations[i] = [ Modem.heard_stations[i] = [
dxcallsign, dxcallsign,
dxgrid, dxgrid,
int(time.time()), int(time.time()),
@ -159,8 +159,8 @@ def add_to_heard_stations(dxcallsign, dxgrid, datatype, snr, offset, frequency):
] ]
break break
# Insert if nothing found # Insert if nothing found
if i == len(TNC.heard_stations) - 1: if i == len(Modem.heard_stations) - 1:
TNC.heard_stations.append( Modem.heard_stations.append(
[ [
dxcallsign, dxcallsign,
dxgrid, dxgrid,
@ -174,10 +174,10 @@ def add_to_heard_stations(dxcallsign, dxgrid, datatype, snr, offset, frequency):
break break
# for idx, item in enumerate(TNC.heard_stations): # for idx, item in enumerate(Modem.heard_stations):
# if dxcallsign in item: # if dxcallsign in item:
# item = [dxcallsign, int(time.time())] # item = [dxcallsign, int(time.time())]
# TNC.heard_stations[idx] = item # Modem.heard_stations[idx] = item
def callsign_to_bytes(callsign) -> bytes: def callsign_to_bytes(callsign) -> bytes:
@ -530,7 +530,7 @@ def get_hmac_salt(dxcallsign: bytes, mycallsign: bytes):
filepath = subfolder / filename filepath = subfolder / filename
except Exception as e: except Exception as e:
log.error( log.error(
"[TNC] [HMAC] File lookup error", file=filepath, "[Modem] [HMAC] File lookup error", file=filepath,
) )
# check if file exists else return false # check if file exists else return false
@ -580,13 +580,13 @@ def search_hmac_salt(dxcallsign: bytes, mycallsign: bytes, search_token, data_fr
filepath = subfolder / filename filepath = subfolder / filename
except Exception as e: except Exception as e:
log.error( log.error(
"[TNC] [HMAC] File lookup error", file=filepath, "[Modem] [HMAC] File lookup error", file=filepath,
) )
# check if file exists else return false # check if file exists else return false
if not check_if_file_exists(filepath): if not check_if_file_exists(filepath):
log.warning( log.warning(
"[TNC] [HMAC] Token file not found", file=filepath, "[Modem] [HMAC] Token file not found", file=filepath,
) )
return False return False
@ -611,19 +611,19 @@ def search_hmac_salt(dxcallsign: bytes, mycallsign: bytes, search_token, data_fr
token_position = len(token_list) - _ token_position = len(token_list) - _
delete_last_line_from_hmac_list(filepath, token_position) delete_last_line_from_hmac_list(filepath, token_position)
log.info( log.info(
"[TNC] [HMAC] Signature found", expected=search_token.hex(), "[Modem] [HMAC] Signature found", expected=search_token.hex(),
) )
return True return True
log.warning( log.warning(
"[TNC] [HMAC] Signature not found", expected=search_token.hex(), filepath=filepath, "[Modem] [HMAC] Signature not found", expected=search_token.hex(), filepath=filepath,
) )
return False return False
except Exception as e: except Exception as e:
log.warning( log.warning(
"[TNC] [HMAC] Lookup failed", e=e, expected=search_token, "[Modem] [HMAC] Lookup failed", e=e, expected=search_token,
) )
return False return False
@ -662,6 +662,6 @@ def check_if_file_exists(path):
return False return False
except Exception as e: except Exception as e:
log.warning( log.warning(
"[TNC] [FILE] Lookup failed", e=e, path=path, "[Modem] [FILE] Lookup failed", e=e, path=path,
) )
return False return False

View file

@ -5,11 +5,11 @@ Created on Tue Dec 22 16:58:45 2020
@author: DJ2LS @author: DJ2LS
main module for running the tnc main module for running the modem
""" """
# run tnc self test on startup before we are doing other things # run modem self test on startup before we are doing other things
# import selftest # import selftest
# selftest.TEST() # selftest.TEST()
@ -29,7 +29,7 @@ import helpers
import log_handler import log_handler
import modem import modem
import static import static
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC, MeshParam from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem, MeshParam
import structlog import structlog
import explorer import explorer
import json import json
@ -46,7 +46,7 @@ def signal_handler(sig, frame):
Returns: system exit Returns: system exit
""" """
print("Closing TNC...") print("Closing Modem...")
sock.CLOSE_SIGNAL = True sock.CLOSE_SIGNAL = True
sys.exit(0) sys.exit(0)
@ -57,7 +57,7 @@ if __name__ == "__main__":
# This is for Windows multiprocessing support # This is for Windows multiprocessing support
multiprocessing.freeze_support() multiprocessing.freeze_support()
# --------------------------------------------GET PARAMETER INPUTS # --------------------------------------------GET PARAMETER INPUTS
PARSER = argparse.ArgumentParser(description="FreeDATA TNC") PARSER = argparse.ArgumentParser(description="FreeDATA Modem")
#PARSER.add_argument( #PARSER.add_argument(
# "--use-config", # "--use-config",
@ -205,7 +205,7 @@ if __name__ == "__main__":
"--explorer", "--explorer",
dest="enable_explorer", dest="enable_explorer",
action="store_true", action="store_true",
help="Enable sending tnc data to https://explorer.freedata.app", help="Enable sending modem data to https://explorer.freedata.app",
) )
PARSER.add_argument( PARSER.add_argument(
@ -295,27 +295,27 @@ if __name__ == "__main__":
except ValueError: except ValueError:
AudioParam.audio_output_device = ARGS.audio_output_device AudioParam.audio_output_device = ARGS.audio_output_device
TNC.port = ARGS.socket_port Modem.port = ARGS.socket_port
HamlibParam.hamlib_radiocontrol = ARGS.hamlib_radiocontrol HamlibParam.hamlib_radiocontrol = ARGS.hamlib_radiocontrol
HamlibParam.hamlib_rigctld_ip = ARGS.rigctld_ip HamlibParam.hamlib_rigctld_ip = ARGS.rigctld_ip
HamlibParam.hamlib_rigctld_port = str(ARGS.rigctld_port) HamlibParam.hamlib_rigctld_port = str(ARGS.rigctld_port)
ModemParam.enable_scatter = ARGS.send_scatter ModemParam.enable_scatter = ARGS.send_scatter
AudioParam.enable_fft = ARGS.send_fft AudioParam.enable_fft = ARGS.send_fft
TNC.enable_fsk = ARGS.enable_fsk Modem.enable_fsk = ARGS.enable_fsk
TNC.low_bandwidth_mode = ARGS.low_bandwidth_mode Modem.low_bandwidth_mode = ARGS.low_bandwidth_mode
ModemParam.tuning_range_fmin = ARGS.tuning_range_fmin ModemParam.tuning_range_fmin = ARGS.tuning_range_fmin
ModemParam.tuning_range_fmax = ARGS.tuning_range_fmax ModemParam.tuning_range_fmax = ARGS.tuning_range_fmax
AudioParam.tx_audio_level = ARGS.tx_audio_level AudioParam.tx_audio_level = ARGS.tx_audio_level
TNC.respond_to_cq = ARGS.enable_respond_to_cq Modem.respond_to_cq = ARGS.enable_respond_to_cq
ARQ.rx_buffer_size = ARGS.rx_buffer_size ARQ.rx_buffer_size = ARGS.rx_buffer_size
TNC.enable_explorer = ARGS.enable_explorer Modem.enable_explorer = ARGS.enable_explorer
AudioParam.audio_auto_tune = ARGS.enable_audio_auto_tune AudioParam.audio_auto_tune = ARGS.enable_audio_auto_tune
TNC.enable_stats = ARGS.enable_stats Modem.enable_stats = ARGS.enable_stats
TCIParam.ip = ARGS.tci_ip TCIParam.ip = ARGS.tci_ip
TCIParam.port = ARGS.tci_port TCIParam.port = ARGS.tci_port
ModemParam.tx_delay = ARGS.tx_delay ModemParam.tx_delay = ARGS.tx_delay
MeshParam.enable_protocol = ARGS.enable_mesh MeshParam.enable_protocol = ARGS.enable_mesh
TNC.enable_hmac = ARGS.enable_hmac Modem.enable_hmac = ARGS.enable_hmac
except Exception as e: except Exception as e:
@ -348,25 +348,25 @@ if __name__ == "__main__":
except ValueError: except ValueError:
AudioParam.audio_output_device = conf.get('AUDIO', 'tx', '0') AudioParam.audio_output_device = conf.get('AUDIO', 'tx', '0')
TNC.port = int(conf.get('NETWORK', 'tncport', '3000')) Modem.port = int(conf.get('NETWORK', 'modemport', '3000'))
HamlibParam.hamlib_radiocontrol = conf.get('RADIO', 'radiocontrol', 'disabled') HamlibParam.hamlib_radiocontrol = conf.get('RADIO', 'radiocontrol', 'disabled')
HamlibParam.hamlib_rigctld_ip = conf.get('RADIO', 'rigctld_ip', '127.0.0.1') HamlibParam.hamlib_rigctld_ip = conf.get('RADIO', 'rigctld_ip', '127.0.0.1')
HamlibParam.hamlib_rigctld_port = str(conf.get('RADIO', 'rigctld_port', '4532')) HamlibParam.hamlib_rigctld_port = str(conf.get('RADIO', 'rigctld_port', '4532'))
ModemParam.enable_scatter = conf.get('TNC', 'scatter', 'True') ModemParam.enable_scatter = conf.get('Modem', 'scatter', 'True')
AudioParam.enable_fft = conf.get('TNC', 'fft', 'True') AudioParam.enable_fft = conf.get('Modem', 'fft', 'True')
TNC.enable_fsk = conf.get('TNC', 'fsk', 'False') Modem.enable_fsk = conf.get('Modem', 'fsk', 'False')
TNC.low_bandwidth_mode = conf.get('TNC', 'narrowband', 'False') Modem.low_bandwidth_mode = conf.get('Modem', 'narrowband', 'False')
ModemParam.tuning_range_fmin = float(conf.get('TNC', 'fmin', '-50.0')) ModemParam.tuning_range_fmin = float(conf.get('Modem', 'fmin', '-50.0'))
ModemParam.tuning_range_fmax = float(conf.get('TNC', 'fmax', '50.0')) ModemParam.tuning_range_fmax = float(conf.get('Modem', 'fmax', '50.0'))
AudioParam.tx_audio_level = int(conf.get('AUDIO', 'txaudiolevel', '100')) AudioParam.tx_audio_level = int(conf.get('AUDIO', 'txaudiolevel', '100'))
TNC.respond_to_cq = conf.get('TNC', 'qrv', 'True') Modem.respond_to_cq = conf.get('Modem', 'qrv', 'True')
ARQ.rx_buffer_size = int(conf.get('TNC', 'rx_buffer_size', '16')) ARQ.rx_buffer_size = int(conf.get('Modem', 'rx_buffer_size', '16'))
TNC.enable_explorer = conf.get('TNC', 'explorer', 'False') Modem.enable_explorer = conf.get('Modem', 'explorer', 'False')
AudioParam.audio_auto_tune = conf.get('AUDIO', 'auto_tune', 'False') AudioParam.audio_auto_tune = conf.get('AUDIO', 'auto_tune', 'False')
TNC.enable_stats = conf.get('TNC', 'stats', 'False') Modem.enable_stats = conf.get('Modem', 'stats', 'False')
TCIParam.ip = str(conf.get('TCI', 'tci_ip', 'localhost')) TCIParam.ip = str(conf.get('TCI', 'tci_ip', 'localhost'))
TCIParam.port = int(conf.get('TCI', 'tci_port', '50001')) TCIParam.port = int(conf.get('TCI', 'tci_port', '50001'))
ModemParam.tx_delay = int(conf.get('TNC', 'tx_delay', '0')) ModemParam.tx_delay = int(conf.get('Modem', 'tx_delay', '0'))
MeshParam.enable_protocol = conf.get('MESH','mesh_enable','False') MeshParam.enable_protocol = conf.get('MESH','mesh_enable','False')
except KeyError as e: except KeyError as e:
log.warning("[CFG] Error reading config file near", key=str(e)) log.warning("[CFG] Error reading config file near", key=str(e))
@ -384,7 +384,7 @@ if __name__ == "__main__":
# config logging # config logging
try: try:
if sys.platform == "linux": if sys.platform == "linux":
logging_path = os.getenv("HOME") + "/.config/" + "FreeDATA/" + "tnc" logging_path = os.getenv("HOME") + "/.config/" + "FreeDATA/" + "modem"
if sys.platform == "darwin": if sys.platform == "darwin":
logging_path = ( logging_path = (
@ -392,11 +392,11 @@ if __name__ == "__main__":
+ "/Library/" + "/Library/"
+ "Application Support/" + "Application Support/"
+ "FreeDATA/" + "FreeDATA/"
+ "tnc" + "modem"
) )
if sys.platform in ["win32", "win64"]: if sys.platform in ["win32", "win64"]:
logging_path = os.getenv("APPDATA") + "/" + "FreeDATA/" + "tnc" logging_path = os.getenv("APPDATA") + "/" + "FreeDATA/" + "modem"
if not os.path.exists(logging_path): if not os.path.exists(logging_path):
os.makedirs(logging_path) os.makedirs(logging_path)
@ -405,7 +405,7 @@ if __name__ == "__main__":
log.error("[DMN] logger init error", exception=err) log.error("[DMN] logger init error", exception=err)
log.info( log.info(
"[TNC] Starting FreeDATA", author="DJ2LS", version=TNC.version "[Modem] Starting FreeDATA", author="DJ2LS", version=Modem.version
) )
# start data handler # start data handler
@ -421,17 +421,17 @@ if __name__ == "__main__":
mesh = mesh.MeshRouter() mesh = mesh.MeshRouter()
# optionally start explorer module # optionally start explorer module
if TNC.enable_explorer: if Modem.enable_explorer:
log.info("[EXPLORER] Publishing to https://explorer.freedata.app", state=TNC.enable_explorer) log.info("[EXPLORER] Publishing to https://explorer.freedata.app", state=Modem.enable_explorer)
explorer = explorer.explorer() explorer = explorer.explorer()
# --------------------------------------------START CMD SERVER # --------------------------------------------START CMD SERVER
try: try:
log.info("[TNC] Starting TCP/IP socket", port=TNC.port) log.info("[Modem] Starting TCP/IP socket", port=Modem.port)
# https://stackoverflow.com/a/16641793 # https://stackoverflow.com/a/16641793
socketserver.TCPServer.allow_reuse_address = True socketserver.TCPServer.allow_reuse_address = True
cmdserver = sock.ThreadedTCPServer( cmdserver = sock.ThreadedTCPServer(
(TNC.host, TNC.port), sock.ThreadedTCPRequestHandler (Modem.host, Modem.port), sock.ThreadedTCPRequestHandler
) )
server_thread = threading.Thread(target=cmdserver.serve_forever) server_thread = threading.Thread(target=cmdserver.serve_forever)
@ -439,7 +439,7 @@ if __name__ == "__main__":
server_thread.start() server_thread.start()
except Exception as err: except Exception as err:
log.error("[TNC] Starting TCP/IP socket failed", port=TNC.port, e=err) log.error("[Modem] Starting TCP/IP socket failed", port=Modem.port, e=err)
sys.exit(1) sys.exit(1)
while True: while True:
threading.Event().wait(1) threading.Event().wait(1)

View file

@ -37,7 +37,7 @@ SNR: negative --> * 2
# pylint: disable=import-outside-toplevel, attribute-defined-outside-init # pylint: disable=import-outside-toplevel, attribute-defined-outside-init
from static import FRAME_TYPE from static import FRAME_TYPE
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem
from codec2 import FREEDV_MODE from codec2 import FREEDV_MODE
import numpy as np import numpy as np
@ -113,7 +113,7 @@ class MeshRouter():
heard stations format: heard stations format:
[dxcallsign,dxgrid,int(time.time()),datatype,snr,offset,frequency] [dxcallsign,dxgrid,int(time.time()),datatype,snr,offset,frequency]
TNC.heard_stations.append( Modem.heard_stations.append(
[ [
dxcallsign, dxcallsign,
dxgrid, dxgrid,
@ -134,7 +134,7 @@ class MeshRouter():
frequency_position = 6 frequency_position = 6
try: try:
for item in TNC.heard_stations: for item in Modem.heard_stations:
#print("-----------") #print("-----------")
#print(item) #print(item)
#print(item[snr_position]) #print(item[snr_position])
@ -222,13 +222,13 @@ class MeshRouter():
#print(len(_)) #print(len(_))
frame_list.append(mesh_broadcast_frame_header + _) frame_list.append(mesh_broadcast_frame_header + _)
TNC.transmitting = True Modem.transmitting = True
c2_mode = FREEDV_MODE.datac4.value c2_mode = FREEDV_MODE.datac4.value
self.log.info("[MESH] broadcasting routing table", frame_list=frame_list, frames=len(split_result)) self.log.info("[MESH] broadcasting routing table", frame_list=frame_list, frames=len(split_result))
modem.MODEM_TRANSMIT_QUEUE.put([c2_mode, 1, 0, frame_list]) modem.MODEM_TRANSMIT_QUEUE.put([c2_mode, 1, 0, frame_list])
# Wait while transmitting # Wait while transmitting
while TNC.transmitting: while Modem.transmitting:
threading.Event().wait(0.01) threading.Event().wait(0.01)
except Exception as e: except Exception as e:
self.log.warning("[MESH] broadcasting routing table", e=e) self.log.warning("[MESH] broadcasting routing table", e=e)
@ -522,7 +522,7 @@ class MeshRouter():
repeat_delay=0, repeat_delay=0,
) -> None: ) -> None:
""" """
Send (transmit) supplied frame to TNC Send (transmit) supplied frame to Modem
:param frame_to_tx: Frame data to send :param frame_to_tx: Frame data to send
:type frame_to_tx: list of bytearrays :type frame_to_tx: list of bytearrays
@ -536,16 +536,16 @@ class MeshRouter():
#print(frame_to_tx[0]) #print(frame_to_tx[0])
#print(frame_to_tx) #print(frame_to_tx)
frame_type = FRAME_TYPE(int.from_bytes(frame_to_tx[0][:1], byteorder="big")).name frame_type = FRAME_TYPE(int.from_bytes(frame_to_tx[0][:1], byteorder="big")).name
self.log.debug("[TNC] enqueue_frame_for_tx", c2_mode=FREEDV_MODE(c2_mode).name, data=frame_to_tx, self.log.debug("[Modem] enqueue_frame_for_tx", c2_mode=FREEDV_MODE(c2_mode).name, data=frame_to_tx,
type=frame_type) type=frame_type)
# Set the TRANSMITTING flag before adding an object to the transmit queue # Set the TRANSMITTING flag before adding an object to the transmit queue
# TODO: This is not that nice, we could improve this somehow # TODO: This is not that nice, we could improve this somehow
TNC.transmitting = True Modem.transmitting = True
modem.MODEM_TRANSMIT_QUEUE.put([c2_mode, copies, repeat_delay, frame_to_tx]) modem.MODEM_TRANSMIT_QUEUE.put([c2_mode, copies, repeat_delay, frame_to_tx])
# Wait while transmitting # Wait while transmitting
while TNC.transmitting: while Modem.transmitting:
threading.Event().wait(0.01) threading.Event().wait(0.01)

View file

@ -23,7 +23,7 @@ import numpy as np
import sock import sock
import sounddevice as sd import sounddevice as sd
import static import static
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem
from static import FRAME_TYPE from static import FRAME_TYPE
import structlog import structlog
import ujson as json import ujson as json
@ -37,7 +37,7 @@ TESTMODE = False
RXCHANNEL = "" RXCHANNEL = ""
TXCHANNEL = "" TXCHANNEL = ""
TNC.transmitting = False Modem.transmitting = False
# Receive only specific modes to reduce CPU load # Receive only specific modes to reduce CPU load
RECEIVE_SIG0 = True RECEIVE_SIG0 = True
@ -287,7 +287,7 @@ class RF:
) )
fft_thread.start() fft_thread.start()
if TNC.enable_fsk: if Modem.enable_fsk:
audio_thread_fsk_ldpc0 = threading.Thread( audio_thread_fsk_ldpc0 = threading.Thread(
target=self.audio_fsk_ldpc_0, name="AUDIO_THREAD FSK LDPC0", daemon=True target=self.audio_fsk_ldpc_0, name="AUDIO_THREAD FSK LDPC0", daemon=True
) )
@ -386,8 +386,8 @@ class RF:
(self.dat0_datac1_buffer, RECEIVE_DATAC1), (self.dat0_datac1_buffer, RECEIVE_DATAC1),
(self.dat0_datac3_buffer, RECEIVE_DATAC3), (self.dat0_datac3_buffer, RECEIVE_DATAC3),
(self.dat0_datac4_buffer, RECEIVE_DATAC4), (self.dat0_datac4_buffer, RECEIVE_DATAC4),
(self.fsk_ldpc_buffer_0, TNC.enable_fsk), (self.fsk_ldpc_buffer_0, Modem.enable_fsk),
(self.fsk_ldpc_buffer_1, TNC.enable_fsk), (self.fsk_ldpc_buffer_1, Modem.enable_fsk),
]: ]:
if ( if (
not (data_buffer.nbuffer + length_x) > data_buffer.size not (data_buffer.nbuffer + length_x) > data_buffer.size
@ -420,8 +420,8 @@ class RF:
(self.dat0_datac1_buffer, RECEIVE_DATAC1), (self.dat0_datac1_buffer, RECEIVE_DATAC1),
(self.dat0_datac3_buffer, RECEIVE_DATAC3), (self.dat0_datac3_buffer, RECEIVE_DATAC3),
(self.dat0_datac4_buffer, RECEIVE_DATAC4), (self.dat0_datac4_buffer, RECEIVE_DATAC4),
(self.fsk_ldpc_buffer_0, TNC.enable_fsk), (self.fsk_ldpc_buffer_0, Modem.enable_fsk),
(self.fsk_ldpc_buffer_1, TNC.enable_fsk), (self.fsk_ldpc_buffer_1, Modem.enable_fsk),
]: ]:
if ( if (
not (data_buffer.nbuffer + length_x) > data_buffer.size not (data_buffer.nbuffer + length_x) > data_buffer.size
@ -468,7 +468,7 @@ class RF:
# Avoid decoding when transmitting to reduce CPU # Avoid decoding when transmitting to reduce CPU
# TODO: Overriding this for testing purposes # TODO: Overriding this for testing purposes
# if not TNC.transmitting: # if not Modem.transmitting:
length_x = len(x) length_x = len(x)
# Avoid buffer overflow by filling only if buffer for # Avoid buffer overflow by filling only if buffer for
# selected datachannel mode is not full # selected datachannel mode is not full
@ -478,14 +478,14 @@ class RF:
(self.dat0_datac1_buffer, RECEIVE_DATAC1, 2), (self.dat0_datac1_buffer, RECEIVE_DATAC1, 2),
(self.dat0_datac3_buffer, RECEIVE_DATAC3, 3), (self.dat0_datac3_buffer, RECEIVE_DATAC3, 3),
(self.dat0_datac4_buffer, RECEIVE_DATAC4, 4), (self.dat0_datac4_buffer, RECEIVE_DATAC4, 4),
(self.fsk_ldpc_buffer_0, TNC.enable_fsk, 5), (self.fsk_ldpc_buffer_0, Modem.enable_fsk, 5),
(self.fsk_ldpc_buffer_1, TNC.enable_fsk, 6), (self.fsk_ldpc_buffer_1, Modem.enable_fsk, 6),
]: ]:
if (audiobuffer.nbuffer + length_x) > audiobuffer.size: if (audiobuffer.nbuffer + length_x) > audiobuffer.size:
AudioParam.buffer_overflow_counter[index] += 1 AudioParam.buffer_overflow_counter[index] += 1
elif receive: elif receive:
audiobuffer.push(x) audiobuffer.push(x)
# end of "not TNC.transmitting" if block # end of "not Modem.transmitting" if block
if not self.modoutqueue or self.mod_out_locked: if not self.modoutqueue or self.mod_out_locked:
data_out48k = np.zeros(frames, dtype=np.int16) data_out48k = np.zeros(frames, dtype=np.int16)
@ -541,7 +541,7 @@ class RF:
else: else:
return False return False
TNC.transmitting = True Modem.transmitting = True
# if we're transmitting FreeDATA signals, reset channel busy state # if we're transmitting FreeDATA signals, reset channel busy state
ModemParam.channel_busy = False ModemParam.channel_busy = False
@ -729,7 +729,7 @@ class RF:
self.mod_out_locked = True self.mod_out_locked = True
self.modem_transmit_queue.task_done() self.modem_transmit_queue.task_done()
TNC.transmitting = False Modem.transmitting = False
threading.Event().set() threading.Event().set()
end_of_transmission = time.time() end_of_transmission = time.time()
@ -737,7 +737,7 @@ class RF:
self.log.debug("[MDM] ON AIR TIME", time=transmission_time) self.log.debug("[MDM] ON AIR TIME", time=transmission_time)
def transmit_morse(self, repeats, repeat_delay, frames): def transmit_morse(self, repeats, repeat_delay, frames):
TNC.transmitting = True Modem.transmitting = True
# if we're transmitting FreeDATA signals, reset channel busy state # if we're transmitting FreeDATA signals, reset channel busy state
ModemParam.channel_busy = False ModemParam.channel_busy = False
self.log.debug( self.log.debug(
@ -800,7 +800,7 @@ class RF:
self.mod_out_locked = True self.mod_out_locked = True
self.modem_transmit_queue.task_done() self.modem_transmit_queue.task_done()
TNC.transmitting = False Modem.transmitting = False
threading.Event().set() threading.Event().set()
end_of_transmission = time.time() end_of_transmission = time.time()
@ -894,8 +894,8 @@ class RF:
if nbytes == bytes_per_frame: if nbytes == bytes_per_frame:
print(bytes(bytes_out)) print(bytes(bytes_out))
# process commands only if TNC.listen = True # process commands only if Modem.listen = True
if TNC.listen: if Modem.listen:
# ignore data channel opener frames for avoiding toggle states # ignore data channel opener frames for avoiding toggle states
@ -931,7 +931,7 @@ class RF:
else: else:
self.log.warning( self.log.warning(
"[MDM] [demod_audio] received frame but ignored processing", "[MDM] [demod_audio] received frame but ignored processing",
listen=TNC.listen listen=Modem.listen
) )
except Exception as e: except Exception as e:
self.log.warning("[MDM] [demod_audio] Stream not active anymore", e=e) self.log.warning("[MDM] [demod_audio] Stream not active anymore", e=e)
@ -1244,7 +1244,7 @@ class RF:
threading.Event().wait(0.1) threading.Event().wait(0.1)
HamlibParam.hamlib_status = self.radio.get_status() HamlibParam.hamlib_status = self.radio.get_status()
threading.Event().wait(0.1) threading.Event().wait(0.1)
if TNC.transmitting: if Modem.transmitting:
HamlibParam.alc = self.radio.get_alc() HamlibParam.alc = self.radio.get_alc()
threading.Event().wait(0.1) threading.Event().wait(0.1)
# HamlibParam.hamlib_rf = self.radio.get_level() # HamlibParam.hamlib_rf = self.radio.get_level()
@ -1295,7 +1295,7 @@ class RF:
# Therefore we are setting it to 100 so it will be highlighted # Therefore we are setting it to 100 so it will be highlighted
# Have to do this when we are not transmitting so our # Have to do this when we are not transmitting so our
# own sending data will not affect this too much # own sending data will not affect this too much
if not TNC.transmitting: if not Modem.transmitting:
dfft[dfft > avg + 15] = 100 dfft[dfft > avg + 15] = 100
# Calculate audio dbfs # Calculate audio dbfs
@ -1354,12 +1354,12 @@ class RF:
range_start = range[0] range_start = range[0]
range_end = range[1] range_end = range[1]
# define the area, we are detecting busy state # define the area, we are detecting busy state
#dfft = dfft[120:176] if TNC.low_bandwidth_mode else dfft[65:231] #dfft = dfft[120:176] if Modem.low_bandwidth_mode else dfft[65:231]
slotdfft = dfft[range_start:range_end] slotdfft = dfft[range_start:range_end]
# Check for signals higher than average by checking for "100" # Check for signals higher than average by checking for "100"
# If we have a signal, increment our channel_busy delay counter # If we have a signal, increment our channel_busy delay counter
# so we have a smoother state toggle # so we have a smoother state toggle
if np.sum(slotdfft[slotdfft > avg + 15]) >= 200 and not TNC.transmitting: if np.sum(slotdfft[slotdfft > avg + 15]) >= 200 and not Modem.transmitting:
addDelay=True addDelay=True
ModemParam.channel_busy_slot[slot] = True ModemParam.channel_busy_slot[slot] = True
else: else:

View file

@ -3,7 +3,7 @@ Hold queues used by more than one module to eliminate cyclic imports.
""" """
import queue import queue
import static import static
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, TCIParam, TNC from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, TCIParam, Modem
DATA_QUEUE_TRANSMIT = queue.Queue() DATA_QUEUE_TRANSMIT = queue.Queue()
DATA_QUEUE_RECEIVED = queue.Queue() DATA_QUEUE_RECEIVED = queue.Queue()

View file

@ -1,5 +1,5 @@
""" """
simple TNC self tests simple Modem self tests
""" """
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
@ -15,9 +15,9 @@ class TEST():
def __init__(self): def __init__(self):
log.info("[selftest] running self tests...") log.info("[selftest] running self tests...")
if self.run_tests(): if self.run_tests():
log.info("[selftest] passed -> starting TNC") log.info("[selftest] passed -> starting Modem")
else: else:
log.error("[selftest] failed -> closing TNC") log.error("[selftest] failed -> closing Modem")
sys.exit(0) sys.exit(0)
def run_tests(self): def run_tests(self):

View file

@ -27,7 +27,7 @@ import time
import wave import wave
import helpers import helpers
import static import static
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC, MeshParam from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, Modem, MeshParam
import structlog import structlog
from random import randrange from random import randrange
import ujson as json import ujson as json
@ -66,10 +66,10 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
""" """
tempdata = b"" tempdata = b""
while self.connection_alive and not CLOSE_SIGNAL: while self.connection_alive and not CLOSE_SIGNAL:
# send tnc state as network stream # send modem state as network stream
# check server port against daemon port and send corresponding data # check server port against daemon port and send corresponding data
if self.server.server_address[1] == TNC.port and not Daemon.tncstarted: if self.server.server_address[1] == Modem.port and not Daemon.modemstarted:
data = send_tnc_state() data = send_modem_state()
if data != tempdata: if data != tempdata:
tempdata = data tempdata = data
SOCKET_QUEUE.put(data) SOCKET_QUEUE.put(data)
@ -126,8 +126,8 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
# iterate thorugh data list # iterate thorugh data list
for commands in data: for commands in data:
if self.server.server_address[1] == TNC.port: if self.server.server_address[1] == Modem.port:
self.process_tnc_commands(commands) self.process_modem_commands(commands)
else: else:
self.process_daemon_commands(commands) self.process_daemon_commands(commands)
@ -191,10 +191,10 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
e=e, e=e,
) )
# ------------------------ TNC COMMANDS # ------------------------ Modem COMMANDS
def process_tnc_commands(self, data): def process_modem_commands(self, data):
""" """
process tnc commands process modem commands
Args: Args:
data: data:
@ -202,7 +202,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
Returns: Returns:
""" """
log = structlog.get_logger("process_tnc_commands") log = structlog.get_logger("process_modem_commands")
# we need to do some error handling in case of socket timeout or decoding issue # we need to do some error handling in case of socket timeout or decoding issue
try: try:
@ -210,207 +210,207 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
received_json = json.loads(data) received_json = json.loads(data)
log.debug("[SCK] CMD", command=received_json) log.debug("[SCK] CMD", command=received_json)
# ENABLE TNC LISTENING STATE # ENABLE Modem LISTENING STATE
if received_json["type"] == "set" and received_json["command"] == "listen": if received_json["type"] == "set" and received_json["command"] == "listen":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_listen(None, received_json) ThreadedTCPRequestHandler.modem_set_listen(None, received_json)
else: else:
self.tnc_set_listen(received_json) self.modem_set_listen(received_json)
# START STOP AUDIO RECORDING # START STOP AUDIO RECORDING
if received_json["type"] == "set" and received_json["command"] == "record_audio": if received_json["type"] == "set" and received_json["command"] == "record_audio":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_record_audio(None, received_json) ThreadedTCPRequestHandler.modem_set_record_audio(None, received_json)
else: else:
self.tnc_set_record_audio(received_json) self.modem_set_record_audio(received_json)
# SET ENABLE/DISABLE RESPOND TO CALL # SET ENABLE/DISABLE RESPOND TO CALL
if received_json["type"] == "set" and received_json["command"] == "respond_to_call": if received_json["type"] == "set" and received_json["command"] == "respond_to_call":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_respond_to_call(None, received_json) ThreadedTCPRequestHandler.modem_set_respond_to_call(None, received_json)
else: else:
self.tnc_set_respond_to_call(received_json) self.modem_set_respond_to_call(received_json)
# SET ENABLE RESPOND TO CQ # SET ENABLE RESPOND TO CQ
if received_json["type"] == "set" and received_json["command"] == "respond_to_cq": if received_json["type"] == "set" and received_json["command"] == "respond_to_cq":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_record_audio(None, received_json) ThreadedTCPRequestHandler.modem_set_record_audio(None, received_json)
else: else:
self.tnc_set_record_audio(received_json) self.modem_set_record_audio(received_json)
# SET TX AUDIO LEVEL # SET TX AUDIO LEVEL
if received_json["type"] == "set" and received_json["command"] == "tx_audio_level": if received_json["type"] == "set" and received_json["command"] == "tx_audio_level":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_tx_audio_level(None, received_json) ThreadedTCPRequestHandler.modem_set_tx_audio_level(None, received_json)
else: else:
self.tnc_set_tx_audio_level(received_json) self.modem_set_tx_audio_level(received_json)
# TRANSMIT TEST FRAME # TRANSMIT TEST FRAME
if received_json["type"] == "set" and received_json["command"] == "send_test_frame": if received_json["type"] == "set" and received_json["command"] == "send_test_frame":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_send_test_frame(None, received_json) ThreadedTCPRequestHandler.modem_set_send_test_frame(None, received_json)
elif TNC.tnc_state in ['busy']: elif Modem.modem_state in ['busy']:
log.warning( log.warning(
"[SCK] Dropping command", "[SCK] Dropping command",
e="tnc state", e="modem state",
state=TNC.tnc_state, state=Modem.modem_state,
command=received_json, command=received_json,
) )
else: else:
self.tnc_set_send_test_frame(received_json) self.modem_set_send_test_frame(received_json)
# TRANSMIT FEC FRAME # TRANSMIT FEC FRAME
if received_json["type"] == "fec" and received_json["command"] == "transmit": if received_json["type"] == "fec" and received_json["command"] == "transmit":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_fec_transmit(None, received_json) ThreadedTCPRequestHandler.modem_fec_transmit(None, received_json)
else: else:
self.tnc_fec_transmit(received_json) self.modem_fec_transmit(received_json)
# TRANSMIT IS WRITING FRAME # TRANSMIT IS WRITING FRAME
if received_json["type"] == "fec" and received_json["command"] == "transmit_is_writing": if received_json["type"] == "fec" and received_json["command"] == "transmit_is_writing":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_fec_is_writing(None, received_json) ThreadedTCPRequestHandler.modem_fec_is_writing(None, received_json)
elif TNC.tnc_state in ['busy']: elif Modem.modem_state in ['busy']:
log.warning( log.warning(
"[SCK] Dropping command", "[SCK] Dropping command",
e="tnc state", e="modem state",
state=TNC.tnc_state, state=Modem.modem_state,
command=received_json, command=received_json,
) )
else: else:
self.tnc_fec_is_writing(received_json) self.modem_fec_is_writing(received_json)
# CQ CQ CQ # CQ CQ CQ
if received_json["command"] == "cqcqcq": if received_json["command"] == "cqcqcq":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_cqcqcq(None, received_json) ThreadedTCPRequestHandler.modem_cqcqcq(None, received_json)
elif TNC.tnc_state in ['BUSY']: elif Modem.modem_state in ['BUSY']:
log.warning( log.warning(
"[SCK] Dropping command", "[SCK] Dropping command",
e="tnc state", e="modem state",
state=TNC.tnc_state, state=Modem.modem_state,
command=received_json, command=received_json,
) )
else: else:
self.tnc_cqcqcq(received_json) self.modem_cqcqcq(received_json)
# START_BEACON # START_BEACON
if received_json["command"] == "start_beacon": if received_json["command"] == "start_beacon":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_start_beacon(None, received_json) ThreadedTCPRequestHandler.modem_start_beacon(None, received_json)
else: else:
self.tnc_start_beacon(received_json) self.modem_start_beacon(received_json)
# STOP_BEACON # STOP_BEACON
if received_json["command"] == "stop_beacon": if received_json["command"] == "stop_beacon":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_stop_beacon(None, received_json) ThreadedTCPRequestHandler.modem_stop_beacon(None, received_json)
else: else:
self.tnc_stop_beacon(received_json) self.modem_stop_beacon(received_json)
# PING # PING
if received_json["type"] == "ping" and received_json["command"] == "ping": if received_json["type"] == "ping" and received_json["command"] == "ping":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_ping_ping(None, received_json) ThreadedTCPRequestHandler.modem_ping_ping(None, received_json)
elif TNC.tnc_state in ['BUSY']: elif Modem.modem_state in ['BUSY']:
log.warning( log.warning(
"[SCK] Dropping command", "[SCK] Dropping command",
e="tnc state", e="modem state",
state=TNC.tnc_state, state=Modem.modem_state,
command=received_json, command=received_json,
) )
else: else:
self.tnc_ping_ping(received_json) self.modem_ping_ping(received_json)
# CONNECT # CONNECT
if received_json["type"] == "arq" and received_json["command"] == "connect": if received_json["type"] == "arq" and received_json["command"] == "connect":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_arq_connect(None, received_json) ThreadedTCPRequestHandler.modem_arq_connect(None, received_json)
elif TNC.tnc_state in ['BUSY']: elif Modem.modem_state in ['BUSY']:
log.warning( log.warning(
"[SCK] Dropping command", "[SCK] Dropping command",
e="tnc state", e="modem state",
state=TNC.tnc_state, state=Modem.modem_state,
command=received_json, command=received_json,
) )
else: else:
self.tnc_arq_connect(received_json) self.modem_arq_connect(received_json)
# DISCONNECT # DISCONNECT
if received_json["type"] == "arq" and received_json["command"] == "disconnect": if received_json["type"] == "arq" and received_json["command"] == "disconnect":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_arq_disconnect(None, received_json) ThreadedTCPRequestHandler.modem_arq_disconnect(None, received_json)
else: else:
self.tnc_arq_disconnect(received_json) self.modem_arq_disconnect(received_json)
# TRANSMIT RAW DATA # TRANSMIT RAW DATA
if received_json["type"] == "arq" and received_json["command"] == "send_raw": if received_json["type"] == "arq" and received_json["command"] == "send_raw":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_arq_send_raw(None, received_json) ThreadedTCPRequestHandler.modem_arq_send_raw(None, received_json)
elif TNC.tnc_state in ['busy']: elif Modem.modem_state in ['busy']:
log.warning( log.warning(
"[SCK] Dropping command", "[SCK] Dropping command",
e="tnc state", e="modem state",
state=TNC.tnc_state, state=Modem.modem_state,
command=received_json, command=received_json,
) )
else: else:
self.tnc_arq_send_raw(received_json) self.modem_arq_send_raw(received_json)
# STOP TRANSMISSION # STOP TRANSMISSION
if received_json["type"] == "arq" and received_json["command"] == "stop_transmission": if received_json["type"] == "arq" and received_json["command"] == "stop_transmission":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_arq_stop_transmission(None, received_json) ThreadedTCPRequestHandler.modem_arq_stop_transmission(None, received_json)
else: else:
self.tnc_arq_stop_transmission(received_json) self.modem_arq_stop_transmission(received_json)
# GET RX BUFFER # GET RX BUFFER
if received_json["type"] == "get" and received_json["command"] == "rx_buffer": if received_json["type"] == "get" and received_json["command"] == "rx_buffer":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_get_rx_buffer(None, received_json) ThreadedTCPRequestHandler.modem_get_rx_buffer(None, received_json)
else: else:
self.tnc_get_rx_buffer(received_json) self.modem_get_rx_buffer(received_json)
# DELETE RX BUFFER # DELETE RX BUFFER
if received_json["type"] == "set" and received_json["command"] == "del_rx_buffer": if received_json["type"] == "set" and received_json["command"] == "del_rx_buffer":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_del_rx_buffer(None, received_json) ThreadedTCPRequestHandler.modem_set_del_rx_buffer(None, received_json)
else: else:
self.tnc_set_del_rx_buffer(received_json) self.modem_set_del_rx_buffer(received_json)
# SET FREQUENCY # SET FREQUENCY
if received_json["type"] == "set" and received_json["command"] == "frequency": if received_json["type"] == "set" and received_json["command"] == "frequency":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_frequency(None, received_json) ThreadedTCPRequestHandler.modem_set_frequency(None, received_json)
else: else:
self.tnc_set_frequency(received_json) self.modem_set_frequency(received_json)
# SET MODE # SET MODE
if received_json["type"] == "set" and received_json["command"] == "mode": if received_json["type"] == "set" and received_json["command"] == "mode":
if TESTMODE: if TESTMODE:
ThreadedTCPRequestHandler.tnc_set_mode(None, received_json) ThreadedTCPRequestHandler.modem_set_mode(None, received_json)
else: else:
self.tnc_set_mode(received_json) self.modem_set_mode(received_json)
# GET ROUTING TABLE # GET ROUTING TABLE
if received_json["type"] == "get" and received_json["command"] == "routing_table": if received_json["type"] == "get" and received_json["command"] == "routing_table":
self.tnc_get_mesh_routing_table(received_json) self.modem_get_mesh_routing_table(received_json)
# -------------- MESH ---------------- # # -------------- MESH ---------------- #
# MESH PING # MESH PING
if received_json["type"] == "mesh" and received_json["command"] == "ping": if received_json["type"] == "mesh" and received_json["command"] == "ping":
self.tnc_mesh_ping(received_json) self.modem_mesh_ping(received_json)
except Exception as err: except Exception as err:
log.error("[SCK] JSON decoding error", e=err) log.error("[SCK] JSON decoding error", e=err)
def tnc_set_listen(self, received_json): def modem_set_listen(self, received_json):
try: try:
TNC.listen = received_json["state"] in ['true', 'True', True, "ON", "on"] Modem.listen = received_json["state"] in ['true', 'True', True, "ON", "on"]
command_response("listen", True) command_response("listen", True)
# if tnc is connected, force disconnect when TNC.listen == False # if modem is connected, force disconnect when Modem.listen == False
if not TNC.listen and ARQ.arq_session_state not in ["disconnecting", "disconnected", "failed"]: if not Modem.listen and ARQ.arq_session_state not in ["disconnecting", "disconnected", "failed"]:
DATA_QUEUE_TRANSMIT.put(["DISCONNECT"]) DATA_QUEUE_TRANSMIT.put(["DISCONNECT"])
# set early disconnecting state so we can interrupt connection attempts # set early disconnecting state so we can interrupt connection attempts
ARQ.arq_session_state = "disconnecting" ARQ.arq_session_state = "disconnecting"
@ -424,11 +424,11 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
"[SCK] CQ command execution error", e=err, command=received_json "[SCK] CQ command execution error", e=err, command=received_json
) )
def tnc_set_record_audio(self, received_json): def modem_set_record_audio(self, received_json):
try: try:
if not AudioParam.audio_record: if not AudioParam.audio_record:
AudioParam.audio_record_file = wave.open(f"{int(time.time())}_audio_recording.wav", 'w') AudioParam.audio_record_file = wave.open(f"{int(time.time())}_audio_recording.wav", 'w')
AudioParam.audio_record_file.setnchannels(1) AudioParam.audio_record_file.semodemhannels(1)
AudioParam.audio_record_file.setsampwidth(2) AudioParam.audio_record_file.setsampwidth(2)
AudioParam.audio_record_file.setframerate(8000) AudioParam.audio_record_file.setframerate(8000)
AudioParam.audio_record = True AudioParam.audio_record = True
@ -444,9 +444,9 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
"[SCK] CQ command execution error", e=err, command=received_json "[SCK] CQ command execution error", e=err, command=received_json
) )
def tnc_set_respond_to_call(self, received_json): def modem_set_respond_to_call(self, received_json):
try: try:
TNC.respond_to_call = received_json["state"] in ['true', 'True', True] Modem.respond_to_call = received_json["state"] in ['true', 'True', True]
command_response("respond_to_call", True) command_response("respond_to_call", True)
except Exception as err: except Exception as err:
@ -455,9 +455,9 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
"[SCK] CQ command execution error", e=err, command=received_json "[SCK] CQ command execution error", e=err, command=received_json
) )
def tnc_set_respond_to_cq(self, received_json): def modem_set_respond_to_cq(self, received_json):
try: try:
TNC.respond_to_cq = received_json["state"] in ['true', 'True', True] Modem.respond_to_cq = received_json["state"] in ['true', 'True', True]
command_response("respond_to_cq", True) command_response("respond_to_cq", True)
except Exception as err: except Exception as err:
@ -466,7 +466,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
"[SCK] CQ command execution error", e=err, command=received_json "[SCK] CQ command execution error", e=err, command=received_json
) )
def tnc_set_tx_audio_level(self, received_json): def modem_set_tx_audio_level(self, received_json):
try: try:
AudioParam.tx_audio_level = int(received_json["value"]) AudioParam.tx_audio_level = int(received_json["value"])
command_response("tx_audio_level", True) command_response("tx_audio_level", True)
@ -479,7 +479,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_set_send_test_frame(self, received_json): def modem_set_send_test_frame(self, received_json):
try: try:
DATA_QUEUE_TRANSMIT.put(["SEND_TEST_FRAME"]) DATA_QUEUE_TRANSMIT.put(["SEND_TEST_FRAME"])
command_response("send_test_frame", True) command_response("send_test_frame", True)
@ -491,7 +491,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_fec_transmit(self, received_json): def modem_fec_transmit(self, received_json):
try: try:
mode = received_json["mode"] mode = received_json["mode"]
wakeup = received_json["wakeup"] wakeup = received_json["wakeup"]
@ -519,7 +519,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_fec_is_writing(self, received_json): def modem_fec_is_writing(self, received_json):
try: try:
mycallsign = received_json["mycallsign"] mycallsign = received_json["mycallsign"]
DATA_QUEUE_TRANSMIT.put(["FEC_IS_WRITING", mycallsign]) DATA_QUEUE_TRANSMIT.put(["FEC_IS_WRITING", mycallsign])
@ -532,7 +532,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_cqcqcq(self, received_json): def modem_cqcqcq(self, received_json):
try: try:
DATA_QUEUE_TRANSMIT.put(["CQ"]) DATA_QUEUE_TRANSMIT.put(["CQ"])
command_response("cqcqcq", True) command_response("cqcqcq", True)
@ -543,7 +543,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
"[SCK] CQ command execution error", e=err, command=received_json "[SCK] CQ command execution error", e=err, command=received_json
) )
def tnc_start_beacon(self, received_json): def modem_start_beacon(self, received_json):
try: try:
Beacon.beacon_state = True Beacon.beacon_state = True
interval = int(received_json["parameter"]) interval = int(received_json["parameter"])
@ -557,7 +557,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_stop_beacon(self, received_json): def modem_stop_beacon(self, received_json):
try: try:
log.warning("[SCK] Stopping beacon!") log.warning("[SCK] Stopping beacon!")
Beacon.beacon_state = False Beacon.beacon_state = False
@ -572,7 +572,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
) )
def tnc_mesh_ping(self, received_json): def modem_mesh_ping(self, received_json):
# send ping frame and wait for ACK # send ping frame and wait for ACK
try: try:
dxcallsign = received_json["dxcallsign"] dxcallsign = received_json["dxcallsign"]
@ -585,7 +585,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
dxcallsign = helpers.callsign_to_bytes(dxcallsign) dxcallsign = helpers.callsign_to_bytes(dxcallsign)
dxcallsign = helpers.bytes_to_callsign(dxcallsign) dxcallsign = helpers.bytes_to_callsign(dxcallsign)
# check if specific callsign is set with different SSID than the TNC is initialized # check if specific callsign is set with different SSID than the Modem is initialized
try: try:
mycallsign = received_json["mycallsign"] mycallsign = received_json["mycallsign"]
mycallsign = helpers.callsign_to_bytes(mycallsign) mycallsign = helpers.callsign_to_bytes(mycallsign)
@ -605,7 +605,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
"[SCK] PING command execution error", e=err, command=received_json "[SCK] PING command execution error", e=err, command=received_json
) )
def tnc_ping_ping(self, received_json): def modem_ping_ping(self, received_json):
# send ping frame and wait for ACK # send ping frame and wait for ACK
try: try:
@ -619,7 +619,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
dxcallsign = helpers.callsign_to_bytes(dxcallsign) dxcallsign = helpers.callsign_to_bytes(dxcallsign)
dxcallsign = helpers.bytes_to_callsign(dxcallsign) dxcallsign = helpers.bytes_to_callsign(dxcallsign)
# check if specific callsign is set with different SSID than the TNC is initialized # check if specific callsign is set with different SSID than the Modem is initialized
try: try:
mycallsign = received_json["mycallsign"] mycallsign = received_json["mycallsign"]
mycallsign = helpers.callsign_to_bytes(mycallsign) mycallsign = helpers.callsign_to_bytes(mycallsign)
@ -639,7 +639,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
"[SCK] PING command execution error", e=err, command=received_json "[SCK] PING command execution error", e=err, command=received_json
) )
def tnc_arq_connect(self, received_json): def modem_arq_connect(self, received_json):
# pause our beacon first # pause our beacon first
Beacon.beacon_pause = True Beacon.beacon_pause = True
@ -653,7 +653,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
dxcallsign = received_json["dxcallsign"] dxcallsign = received_json["dxcallsign"]
# check if specific callsign is set with different SSID than the TNC is initialized # check if specific callsign is set with different SSID than the Modem is initialized
try: try:
mycallsign = received_json["mycallsign"] mycallsign = received_json["mycallsign"]
mycallsign = helpers.callsign_to_bytes(mycallsign) mycallsign = helpers.callsign_to_bytes(mycallsign)
@ -697,7 +697,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
# allow beacon transmission again # allow beacon transmission again
Beacon.beacon_pause = False Beacon.beacon_pause = False
def tnc_arq_disconnect(self, received_json): def modem_arq_disconnect(self, received_json):
try: try:
if ARQ.arq_session_state not in ["disconnecting", "disconnected", "failed"]: if ARQ.arq_session_state not in ["disconnecting", "disconnected", "failed"]:
DATA_QUEUE_TRANSMIT.put(["DISCONNECT"]) DATA_QUEUE_TRANSMIT.put(["DISCONNECT"])
@ -716,7 +716,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_arq_send_raw(self, received_json): def modem_arq_send_raw(self, received_json):
Beacon.beacon_pause = True Beacon.beacon_pause = True
# wait some random time # wait some random time
@ -754,7 +754,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
base64data = received_json["parameter"][0]["data"] base64data = received_json["parameter"][0]["data"]
# check if specific callsign is set with different SSID than the TNC is initialized # check if specific callsign is set with different SSID than the Modem is initialized
try: try:
mycallsign = received_json["parameter"][0]["mycallsign"] mycallsign = received_json["parameter"][0]["mycallsign"]
mycallsign = helpers.callsign_to_bytes(mycallsign) mycallsign = helpers.callsign_to_bytes(mycallsign)
@ -800,12 +800,12 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_arq_stop_transmission(self, received_json): def modem_arq_stop_transmission(self, received_json):
try: try:
if TNC.tnc_state == "BUSY" or ARQ.arq_state: if Modem.modem_state == "BUSY" or ARQ.arq_state:
DATA_QUEUE_TRANSMIT.put(["STOP"]) DATA_QUEUE_TRANSMIT.put(["STOP"])
log.warning("[SCK] Stopping transmission!") log.warning("[SCK] Stopping transmission!")
TNC.tnc_state = "IDLE" Modem.modem_state = "IDLE"
ARQ.arq_state = False ARQ.arq_state = False
command_response("stop_transmission", True) command_response("stop_transmission", True)
except Exception as err: except Exception as err:
@ -814,7 +814,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
"[SCK] STOP command execution error", e=err, command=received_json "[SCK] STOP command execution error", e=err, command=received_json
) )
def tnc_get_mesh_routing_table(self, received_json): def modem_get_mesh_routing_table(self, received_json):
try: try:
output = { output = {
"command": "routing_table", "command": "routing_table",
@ -851,7 +851,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_get_rx_buffer(self, received_json): def modem_get_rx_buffer(self, received_json):
try: try:
if not RX_BUFFER.empty(): if not RX_BUFFER.empty():
# TODO: REMOVE DEPRECATED MESSAGES # TODO: REMOVE DEPRECATED MESSAGES
@ -892,7 +892,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
# RX_BUFFER[10] = speed list stats # RX_BUFFER[10] = speed list stats
for _buffer_length in range(RX_BUFFER.qsize()): for _buffer_length in range(RX_BUFFER.qsize()):
output = { output = {
"freedata" : "tnc-message", "freedata" : "modem-message",
"arq" : "transmission", "arq" : "transmission",
"status" : "received", "status" : "received",
"uuid" : RX_BUFFER.queue[_buffer_length][0], "uuid" : RX_BUFFER.queue[_buffer_length][0],
@ -929,7 +929,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_set_del_rx_buffer(self, received_json): def modem_set_del_rx_buffer(self, received_json):
try: try:
RX_BUFFER.queue.clear() RX_BUFFER.queue.clear()
command_response("del_rx_buffer", True) command_response("del_rx_buffer", True)
@ -941,7 +941,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_set_mode(self, received_json): def modem_set_mode(self, received_json):
try: try:
RIGCTLD_COMMAND_QUEUE.put(["set_mode", received_json["mode"]]) RIGCTLD_COMMAND_QUEUE.put(["set_mode", received_json["mode"]])
command_response("set_mode", True) command_response("set_mode", True)
@ -953,7 +953,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command=received_json, command=received_json,
) )
def tnc_set_frequency(self, received_json): def modem_set_frequency(self, received_json):
try: try:
RIGCTLD_COMMAND_QUEUE.put(["set_frequency", received_json["frequency"]]) RIGCTLD_COMMAND_QUEUE.put(["set_frequency", received_json["frequency"]])
command_response("set_frequency", True) command_response("set_frequency", True)
@ -990,16 +990,16 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
if ( if (
received_json["type"] == "set" received_json["type"] == "set"
and received_json["command"] == "start_tnc" and received_json["command"] == "start_modem"
and not Daemon.tncstarted and not Daemon.modemstarted
): ):
self.daemon_start_tnc(received_json) self.daemon_start_modem(received_json)
if received_json["type"] == "get" and received_json["command"] == "test_hamlib": if received_json["type"] == "get" and received_json["command"] == "test_hamlib":
self.daemon_test_hamlib(received_json) self.daemon_test_hamlib(received_json)
if received_json["type"] == "set" and received_json["command"] == "stop_tnc": if received_json["type"] == "set" and received_json["command"] == "stop_modem":
self.daemon_stop_tnc(received_json) self.daemon_stop_modem(received_json)
if received_json["type"] == "set" and received_json["command"] == "start_rigctld" and not Daemon.rigctldstarted: if received_json["type"] == "set" and received_json["command"] == "start_rigctld" and not Daemon.rigctldstarted:
self.daemon_start_rigctld(received_json) self.daemon_start_rigctld(received_json)
@ -1047,7 +1047,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
command_response("mygrid", False) command_response("mygrid", False)
log.warning("[SCK] command execution error", e=err, command=received_json) log.warning("[SCK] command execution error", e=err, command=received_json)
def daemon_start_tnc(self, received_json): def daemon_start_modem(self, received_json):
try: try:
startparam = received_json["parameter"][0] startparam = received_json["parameter"][0]
@ -1087,13 +1087,13 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
# print some debugging parameters # print some debugging parameters
for item in startparam: for item in startparam:
log.debug( log.debug(
f"[SCK] TNC Startup Config : {item}", f"[SCK] Modem Startup Config : {item}",
value=startparam[item], value=startparam[item],
) )
DAEMON_QUEUE.put( DAEMON_QUEUE.put(
[ [
"STARTTNC", "STARTModem",
mycall, mycall,
mygrid, mygrid,
rx_audio, rx_audio,
@ -1120,23 +1120,23 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
enable_mesh enable_mesh
] ]
) )
command_response("start_tnc", True) command_response("start_modem", True)
except Exception as err: except Exception as err:
command_response("start_tnc", False) command_response("start_modem", False)
log.warning("[SCK] command execution error", e=err, command=received_json) log.warning("[SCK] command execution error", e=err, command=received_json)
def daemon_stop_tnc(self, received_json): def daemon_stop_modem(self, received_json):
try: try:
Daemon.tncprocess.kill() Daemon.modemprocess.kill()
# unregister process from atexit to avoid process zombies # unregister process from atexit to avoid process zombies
atexit.unregister(Daemon.tncprocess.kill) atexit.unregister(Daemon.modemprocess.kill)
log.warning("[SCK] Stopping TNC") log.warning("[SCK] Stopping Modem")
Daemon.tncstarted = False Daemon.modemstarted = False
command_response("stop_tnc", True) command_response("stop_modem", True)
except Exception as err: except Exception as err:
command_response("stop_tnc", False) command_response("stop_modem", False)
log.warning("[SCK] command execution error", e=err, command=received_json) log.warning("[SCK] command execution error", e=err, command=received_json)
def daemon_test_hamlib(self, received_json): def daemon_test_hamlib(self, received_json):
@ -1236,7 +1236,7 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
Daemon.rigctldstarted = False Daemon.rigctldstarted = False
command_response("stop_rigctld", True) command_response("stop_rigctld", True)
except Exception as err: except Exception as err:
command_response("stop_tnc", False) command_response("stop_modem", False)
log.warning("[SCK] command execution error", e=err, command=received_json) log.warning("[SCK] command execution error", e=err, command=received_json)
@ -1264,16 +1264,16 @@ def send_daemon_state():
Daemon.rigctldstarted = False Daemon.rigctldstarted = False
retcode_tnc = Daemon.tncprocess.poll() retcode_modem = Daemon.modemprocess.poll()
if retcode_tnc in [None, "None"]: if retcode_modem in [None, "None"]:
Daemon.tncstarted = True Daemon.modemstarted = True
# This is a blocking code .... # This is a blocking code ....
# output, errs = Daemon.tncprocess.communicate() # output, errs = Daemon.modemprocess.communicate()
# print(f"tnc out: {output}") # print(f"modem out: {output}")
# print(f"tnc err: {errs}") # print(f"modem err: {errs}")
else: else:
# print(f"tnc closed with code: {retcode_tnc}") # print(f"modem closed with code: {retcode_modem}")
Daemon.tncstarted = False Daemon.modemstarted = False
except Exception: except Exception:
pass pass
@ -1291,10 +1291,10 @@ def send_daemon_state():
"serial_devices": Daemon.serial_devices, "serial_devices": Daemon.serial_devices,
# 'cpu': str(psutil.cpu_percent()), # 'cpu': str(psutil.cpu_percent()),
# 'ram': str(psutil.virtual_memory().percent), # 'ram': str(psutil.virtual_memory().percent),
"version": TNC.version, "version": Modem.version,
} }
if Daemon.tncstarted: if Daemon.modemstarted:
output["daemon_state"].append({"status": "running"}) output["daemon_state"].append({"status": "running"})
else: else:
output["daemon_state"].append({"status": "stopped"}) output["daemon_state"].append({"status": "stopped"})
@ -1310,15 +1310,15 @@ def send_daemon_state():
return None return None
def send_tnc_state(): def send_modem_state():
""" """
send the tnc state to network send the modem state to network
""" """
encoding = "utf-8" encoding = "utf-8"
output = { output = {
"command": "tnc_state", "command": "modem_state",
"ptt_state": str(HamlibParam.ptt_state), "ptt_state": str(HamlibParam.ptt_state),
"tnc_state": str(TNC.tnc_state), "modem_state": str(Modem.modem_state),
"arq_state": str(ARQ.arq_state), "arq_state": str(ARQ.arq_state),
"arq_session": str(ARQ.arq_session), "arq_session": str(ARQ.arq_session),
"arq_session_state": str(ARQ.arq_session_state), "arq_session_state": str(ARQ.arq_session_state),
@ -1357,13 +1357,13 @@ def send_tnc_state():
"dxcallsign": str(Station.dxcallsign, encoding), "dxcallsign": str(Station.dxcallsign, encoding),
"dxgrid": str(Station.dxgrid, encoding), "dxgrid": str(Station.dxgrid, encoding),
"hamlib_status": HamlibParam.hamlib_status, "hamlib_status": HamlibParam.hamlib_status,
"listen": str(TNC.listen), "listen": str(Modem.listen),
"audio_recording": str(AudioParam.audio_record), "audio_recording": str(AudioParam.audio_record),
} }
# add heard stations to heard stations object # add heard stations to heard stations object
for heard in TNC.heard_stations: for heard in Modem.heard_stations:
output["stations"].append( output["stations"].append(
{ {
"dxcallsign": str(heard[0], encoding), "dxcallsign": str(heard[0], encoding),

View file

@ -73,9 +73,9 @@ class Channel:
@dataclass @dataclass
class Daemon: class Daemon:
tncprocess: subprocess.Popen modemprocess: subprocess.Popen
rigctldprocess: subprocess.Popen rigctldprocess: subprocess.Popen
tncstarted: bool = False modemstarted: bool = False
rigctldstarted: bool = False rigctldstarted: bool = False
port: int = 3001 port: int = 3001
serial_devices = [] serial_devices = []
@ -133,12 +133,12 @@ class TCIParam:
port: int = '9000' port: int = '9000'
@dataclass @dataclass
class TNC: class Modem:
version = "0.11.0-alpha.1-vuejs" version = "0.11.0-alpha.1-vuejs"
host: str = "0.0.0.0" host: str = "0.0.0.0"
port: int = 3000 port: int = 3000
SOCKET_TIMEOUT: int = 1 # seconds SOCKET_TIMEOUT: int = 1 # seconds
tnc_state: str = "IDLE" modem_state: str = "IDLE"
enable_explorer = False enable_explorer = False
enable_stats = False enable_stats = False
transmitting: bool = False transmitting: bool = False

View file

@ -12,7 +12,7 @@ import threading
import time import time
import ujson as json import ujson as json
import structlog import structlog
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, TCIParam, TNC from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, TCIParam, Modem
log = structlog.get_logger("stats") log = structlog.get_logger("stats")
@ -47,7 +47,7 @@ class stats():
'duration': duration, 'duration': duration,
'percentage': ARQ.arq_transmission_percent, 'percentage': ARQ.arq_transmission_percent,
'status': status, 'status': status,
'version': TNC.version 'version': Modem.version
} }
station_data = json.dumps(station_data) station_data = json.dumps(station_data)

View file

@ -7,7 +7,7 @@ import websocket
import numpy as np import numpy as np
import time import time
from queues import AUDIO_TRANSMIT_QUEUE, AUDIO_RECEIVED_QUEUE from queues import AUDIO_TRANSMIT_QUEUE, AUDIO_RECEIVED_QUEUE
from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, TCIParam, TNC from global_instances import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, TCIParam, Modem
class TCICtrl: class TCICtrl:
def __init__(self, hostname='127.0.0.1', port=50001): def __init__(self, hostname='127.0.0.1', port=50001):

View file

@ -39,7 +39,7 @@ class RETCODE(Enum):
RIG_EVFO = 16 RIG_EVFO = 16
RIG_EDOM = 17 RIG_EDOM = 17
libname = pathlib.Path("../tnc/lib/hamlib/linux/libhamlib.so") libname = pathlib.Path("../modem/lib/hamlib/linux/libhamlib.so")
hamlib = ctypes.CDLL(libname) hamlib = ctypes.CDLL(libname)
class SERIAL(ctypes.Structure): class SERIAL(ctypes.Structure):

View file

@ -66,9 +66,9 @@ def t_HighSNR_C_P_DATACx(
tx_side = "freedv_data_raw_tx" tx_side = "freedv_data_raw_tx"
_txpaths = ( _txpaths = (
os.path.join("..", "tnc") os.path.join("..", "modem")
if os.path.exists(os.path.join("..", "tnc")) if os.path.exists(os.path.join("..", "modem"))
else "tnc" else "modem"
) )
_txpaths = glob.glob(rf"{_txpaths}/**/{tx_side}", recursive=True) _txpaths = glob.glob(rf"{_txpaths}/**/{tx_side}", recursive=True)
for path in _txpaths: for path in _txpaths:

View file

@ -59,9 +59,9 @@ def t_HighSNR_P_C_DATACx(bursts: int, frames_per_burst: int, mode: str):
# Facilitate running from main directory as well as inside test/ # Facilitate running from main directory as well as inside test/
rx_side = "freedv_data_raw_rx" rx_side = "freedv_data_raw_rx"
_rxpath = ( _rxpath = (
os.path.join("..", "tnc") os.path.join("..", "modem")
if os.path.exists(os.path.join("..", "tnc")) if os.path.exists(os.path.join("..", "modem"))
else "tnc" else "modem"
) )
_rxpaths = glob.glob(rf"{_rxpath}/**/{rx_side}", recursive=True) _rxpaths = glob.glob(rf"{_rxpath}/**/{rx_side}", recursive=True)
for path in _rxpaths: for path in _rxpaths:

View file

@ -23,7 +23,7 @@ import pytest
# pylint: disable=wrong-import-position # pylint: disable=wrong-import-position
sys.path.insert(0, "..") sys.path.insert(0, "..")
sys.path.insert(0, "../tnc") sys.path.insert(0, "../modem")
import data_handler import data_handler
import helpers import helpers
from static import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC from static import ARQ, AudioParam, Beacon, Channel, Daemon, HamlibParam, ModemParam, Station, Statistics, TCIParam, TNC

View file

@ -16,7 +16,7 @@ import numpy as np
import pyaudio import pyaudio
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
# --------------------------------------------GET PARAMETER INPUTS # --------------------------------------------GET PARAMETER INPUTS
parser = argparse.ArgumentParser(description="FreeDATA audio test") parser = argparse.ArgumentParser(description="FreeDATA audio test")

View file

@ -15,7 +15,7 @@ import numpy as np
import pyaudio import pyaudio
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
# --------------------------------------------GET PARAMETER INPUTS # --------------------------------------------GET PARAMETER INPUTS
parser = argparse.ArgumentParser(description="FreeDATA audio test") parser = argparse.ArgumentParser(description="FreeDATA audio test")

View file

@ -16,7 +16,7 @@ import numpy as np
import pyaudio import pyaudio
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
# --------------------------------------------GET PARAMETER INPUTS # --------------------------------------------GET PARAMETER INPUTS
parser = argparse.ArgumentParser(description="FreeDATA audio test") parser = argparse.ArgumentParser(description="FreeDATA audio test")

View file

@ -15,7 +15,7 @@ import numpy as np
import pyaudio import pyaudio
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
# --------------------------------------------GET PARAMETER INPUTS # --------------------------------------------GET PARAMETER INPUTS
parser = argparse.ArgumentParser(description="FreeDATA audio test") parser = argparse.ArgumentParser(description="FreeDATA audio test")

View file

@ -15,7 +15,7 @@ import numpy as np
import pyaudio import pyaudio
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
# --------------------------------------------GET PARAMETER INPUTS # --------------------------------------------GET PARAMETER INPUTS
parser = argparse.ArgumentParser(description="FreeDATA audio test") parser = argparse.ArgumentParser(description="FreeDATA audio test")

View file

@ -17,7 +17,7 @@ import numpy as np
import pyaudio import pyaudio
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
# --------------------------------------------GET PARAMETER INPUTS # --------------------------------------------GET PARAMETER INPUTS
parser = argparse.ArgumentParser(description="FreeDATA audio test") parser = argparse.ArgumentParser(description="FreeDATA audio test")

View file

@ -202,8 +202,8 @@ def t_highsnr_arq_short_station1(
time.sleep(0.5) time.sleep(0.5)
log.info("station1", arq_state=pformat(ARQ.arq_state)) log.info("station1", arq_state=pformat(ARQ.arq_state))
# log.info("S1 DQT: ", DQ_Tx=pformat(tnc.data_queue_transmit.queue)) # log.info("S1 DQT: ", DQ_Tx=pformat(modem.data_queue_transmit.queue))
# log.info("S1 DQR: ", DQ_Rx=pformat(tnc.data_queue_received.queue)) # log.info("S1 DQR: ", DQ_Rx=pformat(modem.data_queue_received.queue))
log.info("S1 Socket: ", socket_queue=pformat(sock.SOCKET_QUEUE.queue)) log.info("S1 Socket: ", socket_queue=pformat(sock.SOCKET_QUEUE.queue))
assert '"arq":"transmission","status":"transmitting"' in str( assert '"arq":"transmission","status":"transmitting"' in str(

View file

@ -153,8 +153,8 @@ def t_highsnr_arq_short_station2(
time.sleep(0.5) time.sleep(0.5)
log.info("station2", arq_state=pformat(ARQ.arq_state)) log.info("station2", arq_state=pformat(ARQ.arq_state))
# log.info("S2 DQT: ", DQ_Tx=pformat(tnc.data_queue_transmit.queue)) # log.info("S2 DQT: ", DQ_Tx=pformat(modem.data_queue_transmit.queue))
# log.info("S2 DQR: ", DQ_Rx=pformat(tnc.data_queue_received.queue)) # log.info("S2 DQR: ", DQ_Rx=pformat(modem.data_queue_received.queue))
log.info("S2 Socket: ", socket_queue=pformat(sock.SOCKET_QUEUE.queue)) log.info("S2 Socket: ", socket_queue=pformat(sock.SOCKET_QUEUE.queue))
assert '"arq":"transmission","status":"received"' in str(sock.SOCKET_QUEUE.queue) assert '"arq":"transmission","status":"received"' in str(sock.SOCKET_QUEUE.queue)

View file

@ -189,8 +189,8 @@ def t_datac13_1(
time.sleep(0.5) time.sleep(0.5)
log.info("station1, final") log.info("station1, final")
# log.info("S1 DQT: ", DQ_Tx=pformat(tnc.data_queue_transmit.queue)) # log.info("S1 DQT: ", DQ_Tx=pformat(modem.data_queue_transmit.queue))
# log.info("S1 DQR: ", DQ_Rx=pformat(tnc.data_queue_received.queue)) # log.info("S1 DQR: ", DQ_Rx=pformat(modem.data_queue_received.queue))
log.debug("S1 Socket: ", socket_queue=pformat(sock.SOCKET_QUEUE.queue)) log.debug("S1 Socket: ", socket_queue=pformat(sock.SOCKET_QUEUE.queue))
for item in final_tx_check: for item in final_tx_check:
@ -298,8 +298,8 @@ def t_datac13_2(
time.sleep(0.5) time.sleep(0.5)
log.info("station2, final") log.info("station2, final")
# log.info("S2 DQT: ", DQ_Tx=pformat(tnc.data_queue_transmit.queue)) # log.info("S2 DQT: ", DQ_Tx=pformat(modem.data_queue_transmit.queue))
# log.info("S2 DQR: ", DQ_Rx=pformat(tnc.data_queue_received.queue)) # log.info("S2 DQR: ", DQ_Rx=pformat(modem.data_queue_received.queue))
log.debug("S2 Socket: ", socket_queue=pformat(sock.SOCKET_QUEUE.queue)) log.debug("S2 Socket: ", socket_queue=pformat(sock.SOCKET_QUEUE.queue))
for item in final_rx_check: for item in final_rx_check:

View file

@ -23,7 +23,7 @@ import numpy as np
import pyaudio import pyaudio
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
def test_mm_rx(): def test_mm_rx():

View file

@ -22,7 +22,7 @@ import numpy as np
import pyaudio import pyaudio
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
def test_mm_tx(): def test_mm_tx():

View file

@ -23,8 +23,8 @@ import sounddevice as sd
# pylint: disable=wrong-import-position # pylint: disable=wrong-import-position
sys.path.insert(0, "..") sys.path.insert(0, "..")
sys.path.insert(0, "../tnc") sys.path.insert(0, "../modem")
from tnc import codec2 from modem import codec2
def util_rx(): def util_rx():

View file

@ -18,7 +18,7 @@ from typing import Callable
import structlog import structlog
sys.path.insert(0, "../tnc") sys.path.insert(0, "../modem")
import data_handler import data_handler
import helpers import helpers
import modem import modem

View file

@ -19,7 +19,7 @@ from typing import Callable
import structlog import structlog
sys.path.insert(0, "../tnc") sys.path.insert(0, "../modem")
import data_handler import data_handler
import helpers import helpers
import modem import modem

View file

@ -21,7 +21,7 @@ import numpy as np
import sounddevice as sd import sounddevice as sd
sys.path.insert(0, "..") sys.path.insert(0, "..")
from tnc import codec2 from modem import codec2
def util_tx(): def util_tx():

View file

@ -1,46 +0,0 @@
[NETWORK]
#network settings
tncport = 3000
[STATION]
#station settings
mycall = DJ2LS
mygrid = JN48cs
ssid_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[AUDIO]
#audio settings
rx = 4
tx = 4
txaudiolevel = 100
auto_tune = False
[RADIO]
#radio settings
radiocontrol = disabled
rigctld_ip = 127.0.0.1
rigctld_port = 4532
[TNC]
#tnc settings
scatter = True
fft = True
narrowband = False
fmin = -50.0
fmax = 50.0
qrv = True
rx_buffer_size = 16
explorer = True
stats = False
fsk = False
tx_delay = 0
[TCI]
#tci settings
ip = undefined
port = undefined
[MESH]
#tci settings
enable_protocol = False

View file

@ -1,5 +0,0 @@
# PyAudio
## downloaded from
https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio

View file

@ -39,7 +39,7 @@ def create_hmac_salts(dxcallsign: str, mycallsign: str, num_tokens: int):
for _ in range(len(token_array)): for _ in range(len(token_array)):
file.write(token_array[_] + '\n') file.write(token_array[_] + '\n')
print("files created - place them in tnc/hmac folder and share the file with the remote station") print("files created - place them in modem/hmac folder and share the file with the remote station")
except Exception: except Exception:
print("error creating hmac file") print("error creating hmac file")

View file

@ -5,7 +5,7 @@ daemon.py
Author: DJ2LS, January 2022 Author: DJ2LS, January 2022
daemon for providing basic information for the tnc like audio or serial devices daemon for providing basic information for the modem like audio or serial devices
""" """
# pylint: disable=invalid-name, line-too-long, c-extension-no-member # pylint: disable=invalid-name, line-too-long, c-extension-no-member
@ -92,7 +92,7 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
#pass #pass
print(jsondata.get("routing_table")) print(jsondata.get("routing_table"))
if jsondata.get('freedata') == "tnc-message": if jsondata.get('freedata') == "modem-message":
log.info(jsondata) log.info(jsondata)
if jsondata.get('ping') == "acknowledge": if jsondata.get('ping') == "acknowledge":