FreeDATA/tnc/sock.py

280 lines
13 KiB
Python
Raw Normal View History

2021-02-16 13:23:57 +00:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 21:25:14 2020
@author: DJ2LS
2021-08-08 09:08:34 +00:00
# GET COMMANDS
# "command" : "..."
# SET COMMANDS
# "command" : "..."
# "parameter" : " ..."
# DATA COMMANDS
# "command" : "..."
# "type" : "..."
# "dxcallsign" : "..."
# "data" : "..."
2021-02-16 13:23:57 +00:00
"""
import socketserver
import threading
import logging
2021-03-08 09:49:50 +00:00
import json
import asyncio
2021-03-17 10:22:06 +00:00
import time
2021-02-16 13:23:57 +00:00
import static
2021-02-24 13:22:28 +00:00
import data_handler
2021-02-16 19:49:02 +00:00
import helpers
2021-07-25 14:34:28 +00:00
import sys, os
2021-03-12 13:14:36 +00:00
class CMDTCPRequestHandler(socketserver.BaseRequestHandler):
2021-02-16 13:36:01 +00:00
2021-02-16 18:39:08 +00:00
def handle(self):
2021-05-29 14:57:31 +00:00
print("Client connected...")
# loop through socket buffer until timeout is reached. then close buffer
2021-08-08 09:43:09 +00:00
socketTimeout = time.time() + 3
while socketTimeout > time.time():
2021-05-29 14:57:31 +00:00
2021-05-28 18:54:23 +00:00
time.sleep(0.01)
encoding = 'utf-8'
#data = str(self.request.recv(1024), 'utf-8')
data = bytes()
# we need to loop through buffer until end of chunk is reached or timeout occured
while True and socketTimeout > time.time():
chunk = self.request.recv(1024) # .strip()
2021-05-28 18:54:23 +00:00
data += chunk
2021-08-08 10:07:26 +00:00
if chunk.endswith(b'}\n'):# or chunk.endswith(b'}') or chunk.endswith(b'\n'):
2021-05-28 18:54:23 +00:00
break
data = data[:-1] # remove b'\n'
data = str(data, 'utf-8')
2021-08-07 09:14:49 +00:00
#print(data)
2021-03-12 16:03:04 +00:00
if len(data) > 0:
socketTimeout = time.time() + static.SOCKET_TIMEOUT
2021-05-28 18:54:23 +00:00
# convert data to json object
# we need to do some error handling in case of socket timeout
2021-07-25 16:00:18 +00:00
try:
2021-08-08 09:08:34 +00:00
received_json = json.loads(data)
2021-08-08 09:08:34 +00:00
2021-07-25 16:00:18 +00:00
except json.decoder.JSONDecodeError as e:
2021-08-08 09:08:34 +00:00
print("++++++++++++ START OF JSON ERROR +++++++++++++++++++++++")
2021-07-25 16:00:18 +00:00
print(e)
2021-08-08 09:08:34 +00:00
print("-----------------------------------")
2021-07-25 16:00:18 +00:00
print(data)
2021-08-08 09:08:34 +00:00
print("++++++++++++ END OF JSON ERROR +++++++++++++++++++++++++")
2021-08-08 09:43:09 +00:00
received_json = {}
2021-05-29 14:57:31 +00:00
try:
# CQ CQ CQ -----------------------------------------------------
if received_json["command"] == "CQCQCQ":
socketTimeout = 0
#asyncio.run(data_handler.transmit_cq())
CQ_THREAD = threading.Thread(target=data_handler.transmit_cq, args=[], name="CQ")
CQ_THREAD.start()
2021-05-29 14:57:31 +00:00
# PING ----------------------------------------------------------
if received_json["type"] == 'PING' and received_json["command"] == "PING":
2021-05-29 14:57:31 +00:00
# send ping frame and wait for ACK
print(received_json)
2021-05-29 14:57:31 +00:00
dxcallsign = received_json["dxcallsign"]
#asyncio.run(data_handler.transmit_ping(dxcallsign))
PING_THREAD = threading.Thread(target=data_handler.transmit_ping, args=[dxcallsign], name="CQ")
PING_THREAD.start()
2021-05-29 14:57:31 +00:00
2021-08-08 09:08:34 +00:00
if received_json["type"] == 'ARQ' and received_json["command"] == "OPEN_DATA_CHANNEL":
2021-05-29 14:57:31 +00:00
static.ARQ_READY_FOR_DATA = False
static.TNC_STATE = 'BUSY'
dxcallsign = received_json["dxcallsign"]
static.DXCALLSIGN = bytes(dxcallsign, 'utf-8')
static.DXCALLSIGN_CRC8 = helpers.get_crc_8(static.DXCALLSIGN)
asyncio.run(data_handler.arq_open_data_channel())
2021-07-28 16:43:41 +00:00
if received_json["type"] == 'ARQ' and received_json["command"] == "sendFile":# and static.ARQ_READY_FOR_DATA == True: # and static.ARQ_STATE == 'CONNECTED' :
2021-05-29 14:57:31 +00:00
static.TNC_STATE = 'BUSY'
#on a new transmission we reset the timer
static.ARQ_START_OF_TRANSMISSION = int(time.time())
dxcallsign = received_json["dxcallsign"]
2021-07-28 16:43:41 +00:00
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"]
2021-08-08 09:08:34 +00:00
2021-05-29 14:57:31 +00:00
static.DXCALLSIGN = bytes(dxcallsign, 'utf-8')
static.DXCALLSIGN_CRC8 = helpers.get_crc_8(static.DXCALLSIGN)
2021-08-16 17:41:20 +00:00
#dataframe = '{"filename": "'+ filename + '", "filetype" : "' + filetype + '", "data" : "' + data + '", "checksum" : "' + checksum + '"}'
2021-08-18 18:03:38 +00:00
rawdata = {"filename" : filename , "filetype" :filetype, "data" : data, "checksum" : checksum}
2021-08-16 17:41:20 +00:00
#dataframe = {filename: filename}
2021-07-28 16:43:41 +00:00
#data_out = bytes(received_json["data"], 'utf-8')
2021-08-18 18:03:38 +00:00
dataframe = json.dumps(rawdata)
print(dataframe)
2021-07-28 16:43:41 +00:00
data_out = bytes(dataframe, 'utf-8')
2021-08-18 18:03:38 +00:00
print(data_out)
2021-07-28 16:43:41 +00:00
2021-05-28 18:54:23 +00:00
2021-05-29 14:57:31 +00:00
#ARQ_DATA_THREAD = threading.Thread(target=data_handler.arq_transmit, args=[data_out], name="ARQ_DATA")
#ARQ_DATA_THREAD.start()
ARQ_DATA_THREAD = threading.Thread(target=data_handler.open_dc_and_transmit, args=[data_out, mode, n_frames], name="ARQ_DATA")
ARQ_DATA_THREAD.start()
# asyncio.run(data_handler.arq_transmit(data_out))
# SETTINGS AND STATUS ---------------------------------------------
if received_json["type"] == 'SET' and received_json["command"] == 'MYCALLSIGN':
callsign = received_json["parameter"]
if bytes(callsign, encoding) == b'':
self.request.sendall(b'INVALID CALLSIGN')
else:
static.MYCALLSIGN = bytes(callsign, encoding)
static.MYCALLSIGN_CRC8 = helpers.get_crc_8(static.MYCALLSIGN)
logging.info("CMD | MYCALLSIGN: " + str(static.MYCALLSIGN))
if received_json["type"] == 'SET' and received_json["command"] == 'MYGRID':
mygrid = received_json["parameter"]
if bytes(mygrid, encoding) == b'':
self.request.sendall(b'INVALID GRID')
else:
static.MYGRID = bytes(mygrid, encoding)
logging.info("CMD | MYGRID: " + str(static.MYGRID))
if received_json["type"] == 'GET' and received_json["command"] == 'STATION_INFO':
output = {
"COMMAND": "STATION_INFO",
2021-08-08 09:43:09 +00:00
"TIMESTAMP" : received_json["timestamp"],
2021-05-29 14:57:31 +00:00
"MY_CALLSIGN": str(static.MYCALLSIGN, encoding),
"DX_CALLSIGN": str(static.DXCALLSIGN, encoding),
2021-08-06 20:09:16 +00:00
"DX_GRID": str(static.DXGRID, encoding),
"EOF" : "EOF",
2021-05-29 14:57:31 +00:00
}
jsondata = json.dumps(output)
self.request.sendall(bytes(jsondata, encoding))
if received_json["type"] == 'GET' and received_json["command"] == 'TNC_STATE':
2021-08-07 09:14:49 +00:00
#print(static.SCATTER)
2021-05-29 14:57:31 +00:00
output = {
"COMMAND": "TNC_STATE",
2021-08-08 09:43:09 +00:00
"TIMESTAMP" : received_json["timestamp"],
2021-05-29 14:57:31 +00:00
"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),
"BER": str(static.BER),
2021-05-29 20:18:11 +00:00
"SNR": str(static.SNR),
2021-05-29 21:19:50 +00:00
"FREQUENCY" : str(static.HAMLIB_FREQUENCY),
"MODE" : str(static.HAMLIB_MODE),
2021-07-09 17:26:02 +00:00
"BANDWITH" : str(static.HAMLIB_BANDWITH),
2021-07-25 14:34:28 +00:00
"FFT" : str(static.FFT),
2021-08-06 20:09:16 +00:00
"SCATTER" : static.SCATTER,
"RX_BUFFER_LENGTH": str(len(static.RX_BUFFER)),
"TX_N_MAX_RETRIES": str(static.TX_N_MAX_RETRIES),
"ARQ_TX_N_FRAMES_PER_BURST": str(static.ARQ_TX_N_FRAMES_PER_BURST),
"ARQ_TX_N_BURSTS": str(static.ARQ_TX_N_BURSTS),
"ARQ_TX_N_CURRENT_ARQ_FRAME": str(int.from_bytes(bytes(static.ARQ_TX_N_CURRENT_ARQ_FRAME), "big")),
"ARQ_TX_N_TOTAL_ARQ_FRAMES": str(int.from_bytes(bytes(static.ARQ_TX_N_TOTAL_ARQ_FRAMES), "big")),
"ARQ_RX_FRAME_N_BURSTS": str(static.ARQ_RX_FRAME_N_BURSTS),
"ARQ_RX_N_CURRENT_ARQ_FRAME": str(static.ARQ_RX_N_CURRENT_ARQ_FRAME),
"ARQ_N_ARQ_FRAMES_PER_DATA_FRAME": str(static.ARQ_N_ARQ_FRAMES_PER_DATA_FRAME),
2021-08-14 18:00:32 +00:00
"ARQ_BYTES_PER_MINUTE" : str(static.ARQ_BYTES_PER_MINUTE),
"ARQ_TRANSMISSION_PERCENT" : str(static.ARQ_TRANSMISSION_PERCENT),
"TOTAL_BYTES" : str(static.TOTAL_BYTES),
"STATIONS" : [],
2021-08-06 20:09:16 +00:00
"EOF" : "EOF",
}
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]})
2021-08-06 20:09:16 +00:00
2021-05-29 14:57:31 +00:00
jsondata = json.dumps(output)
self.request.sendall(bytes(jsondata, encoding))
2021-07-25 16:00:18 +00:00
2021-05-29 14:57:31 +00:00
if received_json["type"] == 'GET' and received_json["command"] == 'RX_BUFFER':
2021-08-15 16:15:08 +00:00
output = {
"COMMAND": "RX_BUFFER",
2021-08-23 13:56:05 +00:00
"DATA-ARRAY" : [],
2021-08-15 16:15:08 +00:00
"EOF" : "EOF",
}
for i in range(0, len(static.RX_BUFFER)):
2021-08-17 18:00:57 +00:00
rawdata = json.loads(static.RX_BUFFER[i][3])
2021-08-15 16:15:08 +00:00
2021-08-23 13:56:05 +00:00
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]})
2021-08-15 16:15:08 +00:00
2021-08-17 18:00:57 +00:00
jsondata = json.dumps(output)
self.request.sendall(bytes(jsondata, encoding))
2021-08-15 16:15:08 +00:00
2021-08-15 15:28:35 +00:00
#data = data.split('GET:RX_BUFFER:')
#bufferposition = int(data[1]) - 1
2021-08-15 16:15:08 +00:00
# print("BUFFER-LENGTH:" + str(len(static.RX_BUFFER)))
# bufferposition = 1
# if bufferposition == -1:
# if len(static.RX_BUFFER) > 0:
# self.request.sendall(static.RX_BUFFER[-1])
#if bufferposition <= len(static.RX_BUFFER) > 0:
# print(static.RX_BUFFER[bufferposition])
# self.request.sendall(bytes(static.RX_BUFFER[bufferposition]))
2021-08-15 15:28:35 +00:00
2021-05-29 14:57:31 +00:00
if received_json["type"] == 'SET' and received_json["command"] == 'DEL_RX_BUFFER':
static.RX_BUFFER = []
#exception, if JSON cant be decoded
2021-07-25 14:34:28 +00:00
except Exception as e:
2021-08-08 09:08:34 +00:00
print("############ START OF ERROR #####################")
print("SOCKET COMMAND ERROR: " + data)
print(e)
2021-07-25 14:34:28 +00:00
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
2021-08-08 09:08:34 +00:00
print(exc_type, fname, exc_tb.tb_lineno)
print("############ END OF ERROR #######################")
2021-05-29 14:57:31 +00:00
print("Client disconnected...")
2021-02-16 13:36:01 +00:00
def start_cmd_socket():
try:
logging.info("SRV | STARTING TCP/IP SOCKET FOR CMD ON PORT: " + str(static.PORT))
2021-03-12 13:14:36 +00:00
socketserver.TCPServer.allow_reuse_address = True # https://stackoverflow.com/a/16641793
cmdserver = socketserver.TCPServer((static.HOST, static.PORT), CMDTCPRequestHandler)
cmdserver.serve_forever()
2021-03-12 13:14:36 +00:00
finally:
cmdserver.server_close()