FreeDATA/tnc/daemon.py

226 lines
8.7 KiB
Python
Raw Normal View History

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 16:58:45 2020
@author: DJ2LS
"""
import argparse
import threading
import socketserver
import time
2021-07-09 17:26:02 +00:00
import os
2021-08-23 16:14:00 +00:00
import sys
2021-09-25 13:24:25 +00:00
import subprocess
import ujson as json
import psutil
2021-09-04 20:13:15 +00:00
import serial.tools.list_ports
2021-09-25 13:24:25 +00:00
import pyaudio
import static
def start_daemon():
try:
print("SRV | STARTING TCP/IP SOCKET FOR CMD ON PORT: " + str(PORT))
2021-09-25 13:24:25 +00:00
# https://stackoverflow.com/a/16641793
socketserver.TCPServer.allow_reuse_address = True
daemon = socketserver.TCPServer(
('0.0.0.0', PORT), CMDTCPRequestHandler)
daemon.serve_forever()
finally:
daemon.server_close()
2021-09-25 13:24:25 +00:00
class CMDTCPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
2021-09-25 13:24:25 +00:00
print("Client connected...")
# loop through socket buffer until timeout is reached. then close buffer
socketTimeout = time.time() + 3
while socketTimeout > time.time():
time.sleep(0.01)
encoding = 'utf-8'
#data = str(self.request.recv(1024), 'utf-8')
data = bytes()
2021-09-25 13:24:25 +00:00
# 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(45)
data += chunk
2021-09-25 13:24:25 +00:00
# or chunk.endswith(b'\n'):
if chunk.endswith(b'}\n') or chunk.endswith(b'}'):
break
data = data[:-1] # remove b'\n'
data = str(data, 'utf-8')
2021-09-25 13:24:25 +00:00
if len(data) > 0:
socketTimeout = time.time() + 3
2021-09-25 13:24:25 +00:00
# convert data to json object
# we need to do some error handling in case of socket timeout
2021-09-25 13:24:25 +00:00
try:
# 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]
received_json = json.loads(data)
# GET COMMANDS
# "command" : "..."
2021-09-25 13:24:25 +00:00
# SET COMMANDS
# "command" : "..."
# "parameter" : " ..."
2021-09-25 13:24:25 +00:00
# DATA COMMANDS
# "command" : "..."
# "type" : "..."
# "dxcallsign" : "..."
# "data" : "..."
2021-09-25 13:24:25 +00:00
2021-07-10 21:27:33 +00:00
# print(received_json)
2021-09-25 13:24:25 +00:00
# print(received_json["type"])
# print(received_json["command"])
# try:
2021-07-09 17:26:02 +00:00
if received_json["type"] == 'SET' and received_json["command"] == 'STARTTNC' and not static.TNCSTARTED:
2021-09-25 12:57:44 +00:00
rx_audio = str(received_json["parameter"][0]["rx_audio"])
tx_audio = str(received_json["parameter"][0]["tx_audio"])
deviceid = str(received_json["parameter"][0]["deviceid"])
2021-09-25 13:24:25 +00:00
deviceport = str(
received_json["parameter"][0]["deviceport"])
serialspeed = str(
received_json["parameter"][0]["serialspeed"])
pttprotocol = str(
received_json["parameter"][0]["pttprotocol"])
2021-09-25 12:57:44 +00:00
pttport = str(received_json["parameter"][0]["pttport"])
2021-09-03 14:34:46 +00:00
print("---- STARTING TNC !")
2021-07-10 21:54:45 +00:00
print(received_json["parameter"][0])
2021-09-03 14:34:46 +00:00
2021-09-25 13:24:25 +00:00
# command = "--rx "+ rx_audio +" \
2021-09-25 12:57:44 +00:00
# --tx "+ tx_audio +" \
# --deviceport "+ deviceport +" \
# --deviceid "+ deviceid + " \
# --serialspeed "+ serialspeed + " \
# --pttprotocol "+ pttprotocol + " \
# --pttport "+ pttport
2021-09-25 13:24:25 +00:00
2021-09-25 12:57:44 +00:00
# list of parameters, necessary for running subprocess command as a list
options = []
options.append('--rx')
options.append(rx_audio)
options.append('--tx')
options.append(tx_audio)
options.append('--deviceport')
options.append(deviceport)
options.append('--deviceid')
options.append(deviceid)
options.append('--serialspeed')
options.append(serialspeed)
options.append('--pttprotocol')
options.append(pttprotocol)
options.append('--pttport')
options.append(pttport)
2021-09-25 13:24:25 +00:00
2021-09-16 15:17:55 +00:00
# try running tnc from binary, else run from source
# this helps running the tnc in a developer environment
try:
2021-09-25 12:57:44 +00:00
command = []
2021-10-03 17:33:58 +00:00
command.append('./tnc')
2021-09-25 12:57:44 +00:00
command += options
p = subprocess.Popen(command)
2021-09-16 15:17:55 +00:00
print("running TNC from binary...")
2021-10-03 17:33:58 +00:00
except Exception as e:
print(e)
2021-09-25 12:57:44 +00:00
command = []
command.append('python3')
command.append('main.py')
command += options
p = subprocess.Popen(command)
2021-09-16 15:17:55 +00:00
print("running TNC from source...")
2021-09-25 13:24:25 +00:00
static.TNCPROCESS = p # .pid
2021-07-09 17:26:02 +00:00
static.TNCSTARTED = True
if received_json["type"] == 'SET' and received_json["command"] == 'STOPTNC':
static.TNCPROCESS.kill()
print("KILLING PROCESS ------------")
#os.kill(static.TNCPROCESS, signal.SIGKILL)
static.TNCSTARTED = False
2021-09-25 13:24:25 +00:00
if received_json["type"] == 'GET' and received_json["command"] == 'DAEMON_STATE':
2021-09-25 13:24:25 +00:00
data = {'COMMAND': 'DAEMON_STATE', 'DAEMON_STATE': [], 'INPUT_DEVICES': [], 'OUTPUT_DEVICES': [], 'SERIAL_DEVICES': [
], "CPU": str(psutil.cpu_percent()), "RAM": str(psutil.virtual_memory().percent), "VERSION": "0.1-prototype"}
2021-07-09 17:26:02 +00:00
if static.TNCSTARTED:
data["DAEMON_STATE"].append({"STATUS": "running"})
else:
data["DAEMON_STATE"].append({"STATUS": "stopped"})
# UPDATE LIST OF AUDIO DEVICES
p = pyaudio.PyAudio()
for i in range(0, p.get_device_count()):
maxInputChannels = p.get_device_info_by_host_api_device_index(
0, i).get('maxInputChannels')
maxOutputChannels = p.get_device_info_by_host_api_device_index(
0, i).get('maxOutputChannels')
name = p.get_device_info_by_host_api_device_index(
0, i).get('name')
if maxInputChannels > 0:
data["INPUT_DEVICES"].append(
{"ID": i, "NAME": str(name)})
if maxOutputChannels > 0:
data["OUTPUT_DEVICES"].append(
{"ID": i, "NAME": str(name)})
p.terminate()
# UPDATE LIST OF SERIAL DEVICES
ports = serial.tools.list_ports.comports()
for port, desc, hwid in ports:
data["SERIAL_DEVICES"].append(
{"PORT": str(port), "DESCRIPTION": str(desc)})
jsondata = json.dumps(data)
self.request.sendall(bytes(jsondata, encoding))
2021-09-25 13:24:25 +00:00
# exception, if JSON cant be decoded
# except Exception as e:
2021-09-13 18:01:39 +00:00
except ValueError as e:
2021-08-08 09:08:34 +00:00
print("############ START OF ERROR #####################")
2021-09-25 13:24:25 +00:00
print('DAEMON PROGRAM ERROR: %s' % str(e))
2021-08-08 09:08:34 +00:00
print("Wrong command")
print(data)
2021-09-13 18:01:39 +00:00
print(e)
2021-09-25 13:24:25 +00:00
exc_type, exc_tb = sys.exc_info()
2021-08-23 16:14:00 +00:00
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
2021-08-08 09:08:34 +00:00
print("############ END OF ERROR #######################")
2021-07-09 17:26:02 +00:00
print("Client disconnected...")
if __name__ == '__main__':
2021-09-13 18:01:39 +00:00
# --------------------------------------------GET PARAMETER INPUTS
PARSER = argparse.ArgumentParser(description='Simons TEST TNC')
2021-09-25 13:24:25 +00:00
PARSER.add_argument('--port', dest="socket_port",
default=3001, help="Socket port", type=int)
2021-09-16 15:17:55 +00:00
ARGS = PARSER.parse_args()
PORT = ARGS.socket_port
2021-09-16 15:17:55 +00:00
# --------------------------------------------START CMD SERVER
DAEMON_THREAD = threading.Thread(target=start_daemon, name="daemon")
DAEMON_THREAD.start()