socket non-block design

new design for non blocking network socket. Sock is now streaming status information without need for requesting it.
This commit is contained in:
dj2ls 2022-01-20 20:38:56 +01:00
parent 10d3d5c53e
commit 805a8450c5
7 changed files with 299 additions and 322 deletions

View file

@ -21,7 +21,7 @@ const config = require(configPath);
// START INTERVALL COMMAND EXECUTION FOR STATES
setInterval(daemon.getDaemonState, 1000)
setInterval(sock.getTncState, 150)
//setInterval(sock.getTncState, 150)
setInterval(sock.getRxBuffer, 1000)
setInterval(sock.getMsgRxBuffer, 1000)

View file

@ -109,7 +109,7 @@ client.on('data', function(data) {
msg += data.toString('utf8'); // append data to buffer so we can stick long data together
//console.log(data)
// check if we reached an EOF, if true, clear buffer and parse JSON data
if (data.endsWith('"EOF":"EOF"}')) {
if (data.endsWith('"EOF":"EOF"}\n')) {
//console.log(msg)
try {
//console.log(msg)

View file

@ -23,6 +23,13 @@ import structlog
import log_handler
import helpers
import os
import queue
import audio
DAEMON_QUEUE = queue.Queue()
log_handler.setup_logging("daemon")
structlog.get_logger("structlog").info("[DMN] Starting FreeDATA daemon", author="DJ2LS", year="2022", version="0.1")
@ -32,36 +39,6 @@ python_version = str(sys.version_info[0]) + "." + str(sys.version_info[1])
structlog.get_logger("structlog").info("[DMN] Python", version=python_version)
####################################################
# https://stackoverflow.com/questions/7088672/pyaudio-working-but-spits-out-error-messages-each-time
# https://github.com/DJ2LS/FreeDATA/issues/22
# we need to have a look at this if we want to run this on Windows and MacOS !
# Currently it seems, this is a Linux-only problem
from ctypes import *
from contextlib import contextmanager
import pyaudio
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
# with noalsaerr():
# p = pyaudio.PyAudio()
######################################################
# load crc engine
crc_algorithm = crcengine.new('crc16-ccitt-false') # load crc8 library
@ -178,15 +155,6 @@ class CMDTCPRequestHandler(socketserver.BaseRequestHandler):
rigctld_port = str(received_json["parameter"][0]["rigctld_port"])
structlog.get_logger("structlog").warning("[DMN] Starting TNC", rig=devicename, port=deviceport)
#print(received_json["parameter"][0])
# command = "--rx "+ rx_audio +" \
# --tx "+ tx_audio +" \
# --deviceport "+ deviceport +" \
# --deviceid "+ deviceid + " \
# --serialspeed "+ serialspeed + " \
# --pttprotocol "+ pttprotocol + " \
# --pttport "+ pttport
# list of parameters, necessary for running subprocess command as a list
options = []
@ -265,8 +233,8 @@ class CMDTCPRequestHandler(socketserver.BaseRequestHandler):
'HAMLIB_VERSION': str(hamlib_version),
'INPUT_DEVICES': [],
'OUTPUT_DEVICES': [],
'SERIAL_DEVICES': [
], "CPU": str(psutil.cpu_percent()), "RAM": str(psutil.virtual_memory().percent), "VERSION": "0.1-prototype"}
'SERIAL_DEVICES': [],
"CPU": str(psutil.cpu_percent()), "RAM": str(psutil.virtual_memory().percent), "VERSION": "0.1-prototype"}
if static.TNCSTARTED:
data["DAEMON_STATE"].append({"STATUS": "running"})
@ -277,11 +245,11 @@ class CMDTCPRequestHandler(socketserver.BaseRequestHandler):
try:
# we need to "try" this, because sometimes libasound.so isn't in the default place
# try to supress error messages
with noalsaerr(): # https://github.com/DJ2LS/FreeDATA/issues/22
p = pyaudio.PyAudio()
with audio.noalsaerr(): # https://github.com/DJ2LS/FreeDATA/issues/22
p = audio.pyaudio.PyAudio()
# else do it the default way
except Exception as e:
p = pyaudio.PyAudio()
p = audio.pyaudio.PyAudio()
for i in range(0, p.get_device_count()):
# we need to do a try exception, beacuse for windows theres now audio device range
@ -293,10 +261,6 @@ class CMDTCPRequestHandler(socketserver.BaseRequestHandler):
maxInputChannels = 0
maxOutputChannels = 0
name = ''
#crc_name = crc_algorithm(bytes(name, encoding='utf-8'))
#crc_name = crc_name.to_bytes(2, byteorder='big')
#crc_name = crc_name.hex()
#name = name + ' [' + crc_name + ']'
if maxInputChannels > 0:
data["INPUT_DEVICES"].append(

View file

@ -71,12 +71,14 @@ if __name__ == '__main__':
# config logging
log_handler.setup_logging("tnc")
structlog.get_logger("structlog").info("[TNC] Starting FreeDATA", author="DJ2LS", year="2022", version="0.1")
# start data handler
data_handler.DATA()
# start modem
modem = modem.RF()
# --------------------------------------------START CMD SERVER
try:

View file

@ -9,7 +9,6 @@ import sys
import ctypes
from ctypes import *
import pathlib
#import asyncio
import logging, structlog, log_handler
import time
import threading
@ -22,35 +21,9 @@ import data_handler
import re
import queue
import codec2
import audio
####################################################
# https://stackoverflow.com/questions/7088672/pyaudio-working-but-spits-out-error-messages-each-time
# https://github.com/DJ2LS/FreeDATA/issues/22
# we need to have a look at this if we want to run this on Windows and MacOS !
# Currently it seems, this is a Linux-only problem
from ctypes import *
from contextlib import contextmanager
import pyaudio
ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p)
def py_error_handler(filename, line, function, err, fmt):
pass
c_error_handler = ERROR_HANDLER_FUNC(py_error_handler)
@contextmanager
def noalsaerr():
asound = cdll.LoadLibrary('libasound.so')
asound.snd_lib_error_set_handler(c_error_handler)
yield
asound.snd_lib_error_set_handler(None)
# with noalsaerr():
# p = pyaudio.PyAudio()
######################################################
MODEM_STATS_NR_MAX = 320
@ -143,11 +116,11 @@ class RF():
try:
# we need to "try" this, because sometimes libasound.so isn't in the default place
# try to supress error messages
with noalsaerr(): # https://github.com/DJ2LS/FreeDATA/issues/22
self.p = pyaudio.PyAudio()
with audio.noalsaerr(): # https://github.com/DJ2LS/FreeDATA/issues/22
self.p = audio.pyaudio.PyAudio()
# else do it the default way
except:
self.p = pyaudio.PyAudio()
self.p = audio.pyaudio.PyAudio()
atexit.register(self.p.terminate)
# --------------------------------------------OPEN RX AUDIO CHANNEL
@ -162,7 +135,7 @@ class RF():
static.AUDIO_OUTPUT_DEVICE = loopback_list[1] #1 = TX
print(f"loopback_list rx: {loopback_list}", file=sys.stderr)
self.audio_stream = self.p.open(format=pyaudio.paInt16,
self.audio_stream = self.p.open(format=audio.pyaudio.paInt16,
channels=self.AUDIO_CHANNELS,
rate=self.AUDIO_SAMPLE_RATE_RX,
frames_per_buffer=self.AUDIO_FRAMES_PER_BUFFER_RX,
@ -249,7 +222,7 @@ class RF():
data_out48k = self.modoutqueue.get()
self.fft_data = bytes(data_out48k)
return (data_out48k, pyaudio.paContinue)
return (data_out48k, audio.pyaudio.paContinue)
# --------------------------------------------------------------------------------------------------------

View file

@ -18,7 +18,6 @@ Created on Fri Dec 25 21:25:14 2020
# "dxcallsign" : "..."
# "data" : "..."
"""
import socketserver
@ -31,252 +30,291 @@ import helpers
import sys
import os
import logging, structlog, log_handler
import queue
SOCKET_QUEUE = queue.Queue()
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
pass
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler):
def send_to_client(self):
while self.connection_alive:
# send tnc state as network stream
data = send_tnc_state()
# we want to transmit scatter data only once to reduce network traffic
static.SCATTER = []
# we want to display INFO messages only once
static.INFO = []
sock_data = bytes(data, 'utf-8')
sock_data += b'\n' # append line limiter
self.request.sendall(sock_data)
time.sleep(0.15)
def receive_from_client(self):
data = bytes()
while self.connection_alive:
chunk = self.request.recv(2)
data += chunk
if chunk == b'':
print("connection broken. Closing...")
self.connection_alive = False
if data.startswith(b'{"type"') and data.endswith(b'}\n'):
data = data[:-1] # remove b'\n'
process_tnc_commands(data)
data = bytes()
if data.endswith(b'1\n'):
print(data)
data = bytes()
def handle(self):
structlog.get_logger("structlog").debug("[TNC] Client connected", ip=self.client_address[0], port=self.client_address[1])
# set encoding
encoding = 'utf-8'
self.connection_alive = True
self.sendThread = threading.Thread(target=self.send_to_client, args=[]).start()
self.receiveThread = threading.Thread(target=self.receive_from_client, args=[]).start()
# loop through socket buffer until timeout is reached. then close buffer
socketTimeout = time.time() + static.SOCKET_TIMEOUT
while socketTimeout > time.time():
# keep connection alive until we close it
while self.connection_alive:
time.sleep(1)
time.sleep(0.01)
data = bytes()
# we need to loop through buffer until end of chunk is reached or timeout occured
while socketTimeout > time.time():
data += self.request.recv(64) # we keep amount of bytes short
if data.startswith(b'{"type"') and data.endswith(b'}\n'):
break
data = data[:-1] # remove b'\n'
data = str(data, encoding)
if len(data) > 0:
# reset socket timeout
socketTimeout = time.time() + static.SOCKET_TIMEOUT
# only read first line of string. multiple lines will cause an json error
# this occurs possibly, if we are getting data too fast
# data = data.splitlines()[0]
data = data.splitlines()[0]
# we need to do some error handling in case of socket timeout or decoding issue
try:
# convert data to json object
received_json = json.loads(data)
# CQ CQ CQ -----------------------------------------------------
if received_json["command"] == "CQCQCQ":
data_handler.DATA_QUEUE_TRANSMIT.put(['CQ'])
# START_BEACON -----------------------------------------------------
if received_json["command"] == "START_BEACON":
static.BEACON_STATE = True
interval = int(received_json["parameter"])
data_handler.DATA_QUEUE_TRANSMIT.put(['BEACON', interval, True])
# STOP_BEACON -----------------------------------------------------
if received_json["command"] == "STOP_BEACON":
static.BEACON_STATE = False
structlog.get_logger("structlog").warning("[TNC] Stopping beacon!")
data_handler.DATA_QUEUE_TRANSMIT.put(['BEACON', interval, False])
# PING ----------------------------------------------------------
if received_json["type"] == 'PING' and received_json["command"] == "PING":
# send ping frame and wait for ACK
dxcallsign = received_json["dxcallsign"]
data_handler.DATA_QUEUE_TRANSMIT.put(['PING', dxcallsign])
if received_json["type"] == 'ARQ' and received_json["command"] == "sendFile":
static.TNC_STATE = 'BUSY'
# on a new transmission we reset the timer
static.ARQ_START_OF_TRANSMISSION = int(time.time())
dxcallsign = received_json["dxcallsign"]
mode = int(received_json["mode"])
n_frames = int(received_json["n_frames"])
filename = received_json["filename"]
filetype = received_json["filetype"]
data = received_json["data"]
checksum = received_json["checksum"]
static.DXCALLSIGN = bytes(dxcallsign, 'utf-8')
static.DXCALLSIGN_CRC8 = helpers.get_crc_8(static.DXCALLSIGN)
# dt = datatype
# --> f = file
# --> m = message
# fn = filename
# ft = filetype
# d = data
# crc = checksum
rawdata = {"dt": "f", "fn": filename, "ft": filetype,"d": data, "crc": checksum}
dataframe = json.dumps(rawdata)
data_out = bytes(dataframe, 'utf-8')
data_handler.DATA_QUEUE_TRANSMIT.put(['ARQ_FILE', data_out, mode, n_frames])
# send message
if received_json["type"] == 'ARQ' and received_json["command"] == "sendMessage":
static.TNC_STATE = 'BUSY'
print(received_json)
# on a new transmission we reset the timer
static.ARQ_START_OF_TRANSMISSION = int(time.time())
dxcallsign = received_json["dxcallsign"]
mode = int(received_json["mode"])
n_frames = int(received_json["n_frames"])
data = received_json["data"] # d = data
checksum = received_json["checksum"] # crc = checksum
static.DXCALLSIGN = bytes(dxcallsign, 'utf-8')
static.DXCALLSIGN_CRC8 = helpers.get_crc_8(static.DXCALLSIGN)
# dt = datatype
# --> f = file
# --> m = message
# fn = filename
# ft = filetype
# d = data
# crc = checksum
rawdata = {"dt": "m","d": data, "crc": checksum}
dataframe = json.dumps(rawdata)
data_out = bytes(dataframe, 'utf-8')
data_handler.DATA_QUEUE_TRANSMIT.put(['ARQ_MESSAGE', data_out, mode, n_frames])
if received_json["type"] == 'ARQ' and received_json["command"] == "stopTransmission":
data_handler.DATA_QUEUE_TRANSMIT.put(['STOP'])
print(" >>> STOPPING TRANSMISSION <<<")
structlog.get_logger("structlog").warning("[TNC] Stopping transmission!")
static.TNC_STATE = 'IDLE'
static.ARQ_STATE = False
if received_json["type"] == 'GET' and received_json["command"] == 'STATION_INFO':
output = {
"COMMAND": "STATION_INFO",
"TIMESTAMP": received_json["timestamp"],
"MY_CALLSIGN": str(static.MYCALLSIGN, encoding),
"DX_CALLSIGN": str(static.DXCALLSIGN, encoding),
"DX_GRID": str(static.DXGRID, encoding),
"EOF": "EOF",
}
jsondata = json.dumps(output)
self.request.sendall(bytes(jsondata, encoding))
if received_json["type"] == 'GET' and received_json["command"] == 'TNC_STATE':
output = {
"COMMAND": "TNC_STATE",
"TIMESTAMP": received_json["timestamp"],
"PTT_STATE": str(static.PTT_STATE),
#"CHANNEL_STATE": str(static.CHANNEL_STATE),
"TNC_STATE": str(static.TNC_STATE),
"ARQ_STATE": str(static.ARQ_STATE),
"AUDIO_RMS": str(static.AUDIO_RMS),
"SNR": str(static.SNR),
"FREQUENCY": str(static.HAMLIB_FREQUENCY),
"MODE": str(static.HAMLIB_MODE),
"BANDWITH": str(static.HAMLIB_BANDWITH),
"FFT": str(static.FFT),
"SCATTER": static.SCATTER,
"RX_BUFFER_LENGTH": str(len(static.RX_BUFFER)),
"RX_MSG_BUFFER_LENGTH": str(len(static.RX_MSG_BUFFER)),
"ARQ_BYTES_PER_MINUTE": str(static.ARQ_BYTES_PER_MINUTE),
"ARQ_BYTES_PER_MINUTE_BURST": str(static.ARQ_BYTES_PER_MINUTE_BURST),
"ARQ_COMPRESSION_FACTOR": str(static.ARQ_COMPRESSION_FACTOR),
"ARQ_TRANSMISSION_PERCENT": str(static.ARQ_TRANSMISSION_PERCENT),
"TOTAL_BYTES": str(static.TOTAL_BYTES),
"INFO" : static.INFO,
"BEACON_STATE" : str(static.BEACON_STATE),
"STATIONS": [],
"EOF": "EOF",
}
# we want to transmit scatter data only once to reduce network traffic
static.SCATTER = []
# we want to display INFO messages only once
static.INFO = []
# add heard stations to heard stations object
for i in range(0, len(static.HEARD_STATIONS)):
output["STATIONS"].append({"DXCALLSIGN": str(static.HEARD_STATIONS[i][0], 'utf-8'), "DXGRID": str(static.HEARD_STATIONS[i][1], 'utf-8'),"TIMESTAMP": static.HEARD_STATIONS[i][2], "DATATYPE": static.HEARD_STATIONS[i][3], "SNR": static.HEARD_STATIONS[i][4], "OFFSET": static.HEARD_STATIONS[i][5], "FREQUENCY": static.HEARD_STATIONS[i][6]})
try:
jsondata = json.dumps(output)
except ValueError as e:
structlog.get_logger("structlog").error(e, data=jsondata)
try:
self.request.sendall(bytes(jsondata, encoding))
except Exception as e:
structlog.get_logger("structlog").error(e, data=jsondata)
if received_json["type"] == 'GET' and received_json["command"] == 'RX_BUFFER':
output = {
"COMMAND": "RX_BUFFER",
"DATA-ARRAY": [],
"EOF": "EOF",
}
for i in range(0, len(static.RX_BUFFER)):
rawdata = json.loads(static.RX_BUFFER[i][3])
output["DATA-ARRAY"].append({"DXCALLSIGN": str(static.RX_BUFFER[i][0], 'utf-8'), "DXGRID": str(static.RX_BUFFER[i][1], 'utf-8'), "TIMESTAMP": static.RX_BUFFER[i][2], "RXDATA": [rawdata]})
jsondata = json.dumps(output)
self.request.sendall(bytes(jsondata, encoding))
if received_json["type"] == 'GET' and received_json["command"] == 'RX_MSG_BUFFER':
output = {
"COMMAND": "RX_MSG_BUFFER",
"DATA-ARRAY": [],
"EOF": "EOF",
}
for i in range(0, len(static.RX_MSG_BUFFER)):
rawdata = json.loads(static.RX_MSG_BUFFER[i][3])
output["DATA-ARRAY"].append({"DXCALLSIGN": str(static.RX_MSG_BUFFER[i][0], 'utf-8'), "DXGRID": str(static.RX_MSG_BUFFER[i][1], 'utf-8'), "TIMESTAMP": static.RX_MSG_BUFFER[i][2], "RXDATA": [rawdata]})
jsondata = json.dumps(output)
self.request.sendall(bytes(jsondata, encoding))
if received_json["type"] == 'SET' and received_json["command"] == 'DEL_RX_BUFFER':
static.RX_BUFFER = []
if received_json["type"] == 'SET' and received_json["command"] == 'DEL_RX_MSG_BUFFER':
static.RX_MSG_BUFFER = []
# exception, if JSON cant be decoded
except Exception as e:
#socketTimeout = 0
structlog.get_logger("structlog").error("[TNC] Network error", e=e)
structlog.get_logger("structlog").warning("[TNC] Closing client socket", ip=self.client_address[0], port=self.client_address[1])
def process_tnc_commands(data):
# we need to do some error handling in case of socket timeout or decoding issue
try:
# convert data to json object
received_json = json.loads(data)
# CQ CQ CQ -----------------------------------------------------
if received_json["command"] == "CQCQCQ":
data_handler.DATA_QUEUE_TRANSMIT.put(['CQ'])
# START_BEACON -----------------------------------------------------
if received_json["command"] == "START_BEACON":
static.BEACON_STATE = True
interval = int(received_json["parameter"])
data_handler.DATA_QUEUE_TRANSMIT.put(['BEACON', interval, True])
# STOP_BEACON -----------------------------------------------------
if received_json["command"] == "STOP_BEACON":
static.BEACON_STATE = False
structlog.get_logger("structlog").warning("[TNC] Stopping beacon!")
data_handler.DATA_QUEUE_TRANSMIT.put(['BEACON', interval, False])
# PING ----------------------------------------------------------
if received_json["type"] == 'PING' and received_json["command"] == "PING":
# send ping frame and wait for ACK
dxcallsign = received_json["dxcallsign"]
data_handler.DATA_QUEUE_TRANSMIT.put(['PING', dxcallsign])
# TRANSMIT FILE ----------------------------------------------------------
if received_json["type"] == 'ARQ' and received_json["command"] == "sendFile":
static.TNC_STATE = 'BUSY'
# on a new transmission we reset the timer
static.ARQ_START_OF_TRANSMISSION = int(time.time())
dxcallsign = received_json["dxcallsign"]
mode = int(received_json["mode"])
n_frames = int(received_json["n_frames"])
filename = received_json["filename"]
filetype = received_json["filetype"]
data = received_json["data"]
checksum = received_json["checksum"]
static.DXCALLSIGN = bytes(dxcallsign, 'utf-8')
static.DXCALLSIGN_CRC8 = helpers.get_crc_8(static.DXCALLSIGN)
# dt = datatype
# --> f = file
# --> m = message
# fn = filename
# ft = filetype
# d = data
# crc = checksum
rawdata = {"dt": "f", "fn": filename, "ft": filetype,"d": data, "crc": checksum}
dataframe = json.dumps(rawdata)
data_out = bytes(dataframe, 'utf-8')
data_handler.DATA_QUEUE_TRANSMIT.put(['ARQ_FILE', data_out, mode, n_frames])
# TRANSMIT MESSAGE ----------------------------------------------------------
if received_json["type"] == 'ARQ' and received_json["command"] == "sendMessage":
static.TNC_STATE = 'BUSY'
print(received_json)
# on a new transmission we reset the timer
static.ARQ_START_OF_TRANSMISSION = int(time.time())
dxcallsign = received_json["dxcallsign"]
mode = int(received_json["mode"])
n_frames = int(received_json["n_frames"])
data = received_json["data"] # d = data
checksum = received_json["checksum"] # crc = checksum
static.DXCALLSIGN = bytes(dxcallsign, 'utf-8')
static.DXCALLSIGN_CRC8 = helpers.get_crc_8(static.DXCALLSIGN)
# dt = datatype
# --> f = file
# --> m = message
# fn = filename
# ft = filetype
# d = data
# crc = checksum
rawdata = {"dt": "m","d": data, "crc": checksum}
dataframe = json.dumps(rawdata)
data_out = bytes(dataframe, 'utf-8')
data_handler.DATA_QUEUE_TRANSMIT.put(['ARQ_MESSAGE', data_out, mode, n_frames])
# STOP TRANSMISSION ----------------------------------------------------------
if received_json["type"] == 'ARQ' and received_json["command"] == "stopTransmission":
data_handler.DATA_QUEUE_TRANSMIT.put(['STOP'])
structlog.get_logger("structlog").warning("[TNC] Stopping transmission!")
static.TNC_STATE = 'IDLE'
static.ARQ_STATE = False
if received_json["type"] == 'GET' and received_json["command"] == 'RX_BUFFER':
output = {
"COMMAND": "RX_BUFFER",
"DATA-ARRAY": [],
"EOF": "EOF",
}
for i in range(0, len(static.RX_BUFFER)):
rawdata = json.loads(static.RX_BUFFER[i][3])
output["DATA-ARRAY"].append({"DXCALLSIGN": str(static.RX_BUFFER[i][0], 'utf-8'), "DXGRID": str(static.RX_BUFFER[i][1], 'utf-8'), "TIMESTAMP": static.RX_BUFFER[i][2], "RXDATA": [rawdata]})
jsondata = json.dumps(output)
self.request.sendall(bytes(jsondata, encoding))
if received_json["type"] == 'GET' and received_json["command"] == 'RX_MSG_BUFFER':
output = {
"COMMAND": "RX_MSG_BUFFER",
"DATA-ARRAY": [],
"EOF": "EOF",
}
for i in range(0, len(static.RX_MSG_BUFFER)):
rawdata = json.loads(static.RX_MSG_BUFFER[i][3])
output["DATA-ARRAY"].append({"DXCALLSIGN": str(static.RX_MSG_BUFFER[i][0], 'utf-8'), "DXGRID": str(static.RX_MSG_BUFFER[i][1], 'utf-8'), "TIMESTAMP": static.RX_MSG_BUFFER[i][2], "RXDATA": [rawdata]})
jsondata = json.dumps(output)
self.request.sendall(bytes(jsondata, encoding))
if received_json["type"] == 'SET' and received_json["command"] == 'DEL_RX_BUFFER':
static.RX_BUFFER = []
if received_json["type"] == 'SET' and received_json["command"] == 'DEL_RX_MSG_BUFFER':
static.RX_MSG_BUFFER = []
# exception, if JSON cant be decoded
except Exception as e:
structlog.get_logger("structlog").error("[TNC] Network error", e=e)
def send_tnc_state():
encoding = 'utf-8'
output = {
"COMMAND": "TNC_STATE",
"PTT_STATE": str(static.PTT_STATE),
"TNC_STATE": str(static.TNC_STATE),
"ARQ_STATE": str(static.ARQ_STATE),
"AUDIO_RMS": str(static.AUDIO_RMS),
"SNR": str(static.SNR),
"FREQUENCY": str(static.HAMLIB_FREQUENCY),
"MODE": str(static.HAMLIB_MODE),
"BANDWITH": str(static.HAMLIB_BANDWITH),
"FFT": str(static.FFT),
"SCATTER": static.SCATTER,
"RX_BUFFER_LENGTH": str(len(static.RX_BUFFER)),
"RX_MSG_BUFFER_LENGTH": str(len(static.RX_MSG_BUFFER)),
"ARQ_BYTES_PER_MINUTE": str(static.ARQ_BYTES_PER_MINUTE),
"ARQ_BYTES_PER_MINUTE_BURST": str(static.ARQ_BYTES_PER_MINUTE_BURST),
"ARQ_COMPRESSION_FACTOR": str(static.ARQ_COMPRESSION_FACTOR),
"ARQ_TRANSMISSION_PERCENT": str(static.ARQ_TRANSMISSION_PERCENT),
"TOTAL_BYTES": str(static.TOTAL_BYTES),
"INFO" : static.INFO,
"BEACON_STATE" : str(static.BEACON_STATE),
"STATIONS": [],
"MY_CALLSIGN": str(static.MYCALLSIGN, encoding),
"DX_CALLSIGN": str(static.DXCALLSIGN, encoding),
"DX_GRID": str(static.DXGRID, encoding),
"EOF": "EOF",
}
# add heard stations to heard stations object
for i in range(0, len(static.HEARD_STATIONS)):
output["STATIONS"].append({"DXCALLSIGN": str(static.HEARD_STATIONS[i][0], 'utf-8'), "DXGRID": str(static.HEARD_STATIONS[i][1], 'utf-8'),"TIMESTAMP": static.HEARD_STATIONS[i][2], "DATATYPE": static.HEARD_STATIONS[i][3], "SNR": static.HEARD_STATIONS[i][4], "OFFSET": static.HEARD_STATIONS[i][5], "FREQUENCY": static.HEARD_STATIONS[i][6]})
jsondata = json.dumps(output)
static.NETWORK_BUFFER = jsondata
return jsondata
def process_daemon_commands():
if received_json["type"] == 'SET' and received_json["command"] == 'MYCALLSIGN':
callsign = received_json["parameter"]
print(received_json)
if bytes(callsign, 'utf-8') == b'':
self.request.sendall(b'INVALID CALLSIGN')
structlog.get_logger("structlog").warning("[DMN] SET MYCALL FAILED", call=static.MYCALLSIGN, crc=static.MYCALLSIGN_CRC8)
else:
static.MYCALLSIGN = bytes(callsign, 'utf-8')
static.MYCALLSIGN_CRC8 = helpers.get_crc_8(static.MYCALLSIGN)
structlog.get_logger("structlog").info("[DMN] SET MYCALL", call=static.MYCALLSIGN, crc=static.MYCALLSIGN_CRC8)
if received_json["type"] == 'SET' and received_json["command"] == 'MYGRID':
mygrid = received_json["parameter"]
if bytes(mygrid, 'utf-8') == b'':
self.request.sendall(b'INVALID GRID')
else:
static.MYGRID = bytes(mygrid, 'utf-8')
structlog.get_logger("structlog").info("[DMN] SET MYGRID", grid=static.MYGRID)
if received_json["type"] == 'SET' and received_json["command"] == 'STARTTNC' and not static.TNCSTARTED:
mycall = str(received_json["parameter"][0]["mycall"])
mygrid = str(received_json["parameter"][0]["mygrid"])
rx_audio = str(received_json["parameter"][0]["rx_audio"])
tx_audio = str(received_json["parameter"][0]["tx_audio"])
devicename = str(received_json["parameter"][0]["devicename"])
deviceport = str(received_json["parameter"][0]["deviceport"])
serialspeed = str(received_json["parameter"][0]["serialspeed"])
pttprotocol = str(received_json["parameter"][0]["pttprotocol"])
pttport = str(received_json["parameter"][0]["pttport"])
data_bits = str(received_json["parameter"][0]["data_bits"])
stop_bits = str(received_json["parameter"][0]["stop_bits"])
handshake = str(received_json["parameter"][0]["handshake"])
radiocontrol = str(received_json["parameter"][0]["radiocontrol"])
rigctld_ip = str(received_json["parameter"][0]["rigctld_ip"])
rigctld_port = str(received_json["parameter"][0]["rigctld_port"])
if received_json["type"] == 'SET' and received_json["command"] == 'STOPTNC':
static.TNCPROCESS.kill()
structlog.get_logger("structlog").warning("[DMN] Stopping TNC")
static.TNCSTARTED = False
def sent_daemon_state():
pass

View file

@ -7,7 +7,7 @@ Created on Wed Dec 23 11:13:57 2020
Here we are saving application wide variables and stats, which have to be accessed everywhere.
Not nice, tipps are appreciated :-)
"""
NETWORK_BUFFER = b''
# DAEMON
DAEMONPORT = 3001
TNCSTARTED = False