From 3a70b87e2155852a22a66830534092e68985fdaa Mon Sep 17 00:00:00 2001 From: Paul Kronenwetter Date: Sun, 8 May 2022 21:27:24 -0400 Subject: [PATCH] Remove excess newlines. --- tnc/audio.py | 5 -- tnc/codec2.py | 12 ++--- tnc/daemon.py | 19 +------ tnc/data_handler.py | 126 +------------------------------------------- tnc/helpers.py | 21 -------- tnc/log_handler.py | 1 - tnc/main.py | 9 ---- tnc/modem.py | 40 -------------- tnc/rig.py | 12 ----- tnc/rigctl.py | 11 +--- tnc/rigctld.py | 6 +-- tnc/rigdummy.py | 3 +- tnc/sock.py | 35 +----------- tnc/static.py | 3 -- 14 files changed, 14 insertions(+), 289 deletions(-) diff --git a/tnc/audio.py b/tnc/audio.py index eb89d129..203205b3 100644 --- a/tnc/audio.py +++ b/tnc/audio.py @@ -8,9 +8,6 @@ import atexit atexit.register(sd._terminate) def get_audio_devices(): - - - """ return list of input and output audio devices in own process to avoid crashes of portaudio on raspberry pi @@ -47,7 +44,6 @@ def fetch_audio_devices(input_devices, output_devices): Returns: """ - devices = sd.query_devices(device=None, kind=None) index = 0 for device in devices: @@ -70,4 +66,3 @@ def fetch_audio_devices(input_devices, output_devices): if maxOutputChannels > 0: output_devices.append({"id": index, "name": str(name)}) index += 1 - diff --git a/tnc/codec2.py b/tnc/codec2.py index 9b2ecc61..f45951f3 100644 --- a/tnc/codec2.py +++ b/tnc/codec2.py @@ -63,13 +63,11 @@ if sys.platform == 'linux': files.append('libcodec2.so') elif sys.platform == 'darwin': files = glob.glob('**/*libcodec2*.dylib',recursive=True) - elif sys.platform == 'win32' or sys.platform == 'win64': files = glob.glob('**\*libcodec2*.dll',recursive=True) else: files = [] - for file in files: try: api = ctypes.CDLL(file) @@ -78,15 +76,11 @@ for file in files: except Exception as e: structlog.get_logger("structlog").warning("[C2 ] Libcodec2 found but not loaded", path=file, e=e) - # quit module if codec2 cant be loaded if not 'api' in locals(): structlog.get_logger("structlog").critical("[C2 ] Libcodec2 not loaded", path=file) os._exit(1) - - - # ctypes function init #api.freedv_set_tuning_range.restype = c_int @@ -211,6 +205,7 @@ MODEM_STATS_EYE_IND_MAX = 160 MODEM_STATS_NSPEC = 512 MODEM_STATS_MAX_F_HZ = 4000 MODEM_STATS_MAX_F_EST = 4 + # modem stats structure class MODEMSTATS(ctypes.Structure): """ """ @@ -233,8 +228,6 @@ class MODEMSTATS(ctypes.Structure): ("fft_buf", (ctypes.c_float * MODEM_STATS_NSPEC * 2)), ] - - # Return code flags for freedv_get_rx_status() function api.FREEDV_RX_TRIAL_SYNC = 0x1 # demodulator has trial sync api.FREEDV_RX_SYNC = 0x2 # demodulator has sync @@ -275,6 +268,7 @@ class audio_buffer: self.buffer = np.zeros(size, dtype=np.int16) self.nbuffer = 0 self.mutex = Lock() + def push(self,samples): """ Push new data to buffer @@ -291,6 +285,7 @@ class audio_buffer: self.buffer[self.nbuffer:self.nbuffer+len(samples)] = samples self.nbuffer += len(samples) self.mutex.release() + def pop(self,size): """ get data from buffer in size of NIN @@ -328,7 +323,6 @@ class resampler: self.filter_mem8 = np.zeros(self.MEM8, dtype=np.int16) self.filter_mem48 = np.zeros(self.MEM48) - def resample48_to_8(self,in48): """ audio resampler integration from codec2 diff --git a/tnc/daemon.py b/tnc/daemon.py index 5ed6b25b..573a5101 100755 --- a/tnc/daemon.py +++ b/tnc/daemon.py @@ -8,7 +8,6 @@ Author: DJ2LS, January 2022 daemon for providing basic information for the tnc like audio or serial devices """ - import argparse import threading import socketserver @@ -49,7 +48,6 @@ def signal_handler(sig, frame): signal.signal(signal.SIGINT, signal_handler) - class DAEMON(): """ daemon class @@ -70,8 +68,6 @@ class DAEMON(): worker = threading.Thread(target=self.worker, name="WORKER", daemon=True) worker.start() - - def update_audio_devices(self): """ update audio devices and set to static @@ -85,7 +81,6 @@ class DAEMON(): print(e) time.sleep(1) - def update_serial_devices(self): """ update serial devices and set to static @@ -115,7 +110,6 @@ class DAEMON(): """ while 1: try: - data = self.daemon_queue.get() # data[1] mycall @@ -168,7 +162,6 @@ class DAEMON(): # disabled mode if data[13] != 'disabled': - options.append('--devicename') options.append(data[5]) @@ -212,7 +205,6 @@ class DAEMON(): if data[18] == 'True': options.append('--500hz') - options.append('--tuning_range_fmin') options.append(data[19]) @@ -229,8 +221,6 @@ class DAEMON(): if data[23] == 'True': options.append('--qrv') - - # try running tnc from binary, else run from source # this helps running the tnc in a developer environment try: @@ -282,7 +272,6 @@ class DAEMON(): # data[10] rigctld_ip # data[11] rigctld_port if data[0] == 'TEST_HAMLIB': - devicename = data[1] deviceport = data[2] serialspeed = data[3] @@ -295,8 +284,6 @@ class DAEMON(): rigctld_ip = data[10] rigctld_port = data[11] - - # check how we want to control the radio if radiocontrol == 'direct': import rig @@ -334,13 +321,10 @@ class DAEMON(): except Exception as e: print(e) - - if __name__ == '__main__': # we need to run this on windows for multiprocessing support multiprocessing.freeze_support() - # --------------------------------------------GET PARAMETER INPUTS PARSER = argparse.ArgumentParser(description='FreeDATA Daemon') PARSER.add_argument('--port', dest="socket_port",default=3001, help="Socket port in the range of 1024-65536", type=int) @@ -348,7 +332,6 @@ if __name__ == '__main__': static.DAEMONPORT = ARGS.socket_port - try: if sys.platform == 'linux': logging_path = os.getenv("HOME") + '/.config/' + 'FreeDATA/' + 'daemon' @@ -377,8 +360,8 @@ if __name__ == '__main__': except Exception as e: structlog.get_logger("structlog").error("[DMN] Starting TCP/IP socket failed", port=static.DAEMONPORT, e=e) os._exit(1) - daemon = DAEMON() + daemon = DAEMON() structlog.get_logger("structlog").info("[DMN] Starting FreeDATA Daemon", author="DJ2LS", year="2022", version=static.VERSION) while True: diff --git a/tnc/data_handler.py b/tnc/data_handler.py index ec178350..b8200366 100644 --- a/tnc/data_handler.py +++ b/tnc/data_handler.py @@ -28,11 +28,11 @@ TESTMODE = False DATA_QUEUE_TRANSMIT = queue.Queue() DATA_QUEUE_RECEIVED = queue.Queue() + class DATA(): """ """ def __init__(self): - self.mycallsign = static.MYCALLSIGN # initial callsign. Will be overwritten later self.data_queue_transmit = DATA_QUEUE_TRANSMIT @@ -49,8 +49,6 @@ class DATA(): self.received_mycall_crc = b'' # received my callsign crc if we received a crc for another ssid - - self.data_channel_last_received = 0.0 # time of last "live sign" of a frame self.burst_ack_snr = 0 # SNR from received ack frames self.burst_ack = False # if we received an acknowledge frame for a burst @@ -113,11 +111,9 @@ class DATA(): self.beacon_thread = threading.Thread(target=self.run_beacon, name="watchdog",daemon=True) self.beacon_thread.start() - def worker_transmit(self): """ """ while True: - data = self.data_queue_transmit.get() # [0] Command @@ -154,7 +150,6 @@ class DATA(): # [5] mycallsign with ssid self.open_dc_and_transmit(data[1], data[2], data[3], data[4], data[5]) - elif data[0] == 'CONNECT': # [0] DX CALLSIGN self.arq_session_handler(data[1]) @@ -171,7 +166,6 @@ class DATA(): print(f"wrong command {data}") pass - def worker_receive(self): """ """ while True: @@ -181,7 +175,6 @@ class DATA(): # [2] bytes_per_frame self.process_data(bytes_out=data[0],freedv=data[1],bytes_per_frame=data[2]) - def process_data(self, bytes_out, freedv, bytes_per_frame): """ @@ -197,11 +190,8 @@ class DATA(): # bytes_out[1:4] == callsign check for signalling frames, # bytes_out[2:5] == transmission # we could also create an own function, which returns True. - frametype = int.from_bytes(bytes(bytes_out[:1]), "big") - - print(f"self.n_retries_per_burst = {self.n_retries_per_burst}") _valid1, _ = helpers.check_callsign(self.mycallsign, bytes(bytes_out[1:4])) @@ -251,7 +241,6 @@ class DATA(): structlog.get_logger("structlog").debug("BURST NACK RECEIVED....") self.burst_nack_received(bytes_out[:-2]) - # CQ FRAME elif frametype == 200: structlog.get_logger("structlog").debug("CQ RECEIVED....") @@ -262,20 +251,16 @@ class DATA(): structlog.get_logger("structlog").debug("QRV RECEIVED!") self.received_qrv(bytes_out[:-2]) - # PING FRAME elif frametype == 210: structlog.get_logger("structlog").debug("PING RECEIVED....") self.received_ping(bytes_out[:-2]) - # PING ACK elif frametype == 211: structlog.get_logger("structlog").debug("PING ACK RECEIVED....") self.received_ping_ack(bytes_out[:-2]) - - # SESSION OPENER elif frametype == 221: structlog.get_logger("structlog").debug("OPEN SESSION RECEIVED....") @@ -301,14 +286,11 @@ class DATA(): structlog.get_logger("structlog").debug("ARQ arq_received_channel_is_open") self.arq_received_channel_is_open(bytes_out[:-2]) - - # ARQ MANUAL MODE TRANSMISSION elif 230 <= frametype <= 240 : structlog.get_logger("structlog").debug("ARQ manual mode ") self.arq_received_data_channel_opener(bytes_out[:-2]) - # ARQ STOP TRANSMISSION elif frametype == 249: structlog.get_logger("structlog").debug("ARQ received stop transmission") @@ -330,8 +312,6 @@ class DATA(): # for debugging purposes to receive all data structlog.get_logger("structlog").debug("[TNC] Unknown frame received", frame=bytes_out[:-2]) - - def arq_data_received(self, data_in:bytes, bytes_per_frame:int, snr:int, freedv): """ @@ -376,7 +356,6 @@ class DATA(): RX_N_FRAME_OF_BURST = int.from_bytes(bytes(data_in[:1]), "big") - 10 # get number of burst frame RX_N_FRAMES_PER_BURST = int.from_bytes(bytes(data_in[1:2]), "big") # get number of bursts from received frame - ''' The RX burst buffer needs to have a fixed length filled with "None". We need this later for counting the "Nones" check if burst buffer has expected length else create it @@ -387,8 +366,6 @@ class DATA(): # append data to rx burst buffer static.RX_BURST_BUFFER[RX_N_FRAME_OF_BURST] = data_in[8:] # [frame_type][n_frames_per_burst][CRC24][CRC24] - - structlog.get_logger("structlog").debug("[TNC] static.RX_BURST_BUFFER", buffer=static.RX_BURST_BUFFER) helpers.add_to_heard_stations(static.DXCALLSIGN,static.DXGRID, 'DATA-CHANNEL', static.SNR, static.FREQ_OFFSET, static.HAMLIB_FREQUENCY) @@ -414,14 +391,11 @@ class DATA(): # here we are going to search for our data in the last received bytes # this increases chance we are not loosing the entire frame in case of signalling frame loss else: - - # static.RX_FRAME_BUFFER --> exisitng data # temp_burst_buffer --> new data # search_area --> area where we want to search search_area = 510 - search_position = len(static.RX_FRAME_BUFFER)-search_area # find position of data. returns -1 if nothing found in area else >= 0 # we are beginning from the end, so if data exists twice or more, only the last one should be replaced @@ -436,9 +410,6 @@ class DATA(): static.RX_FRAME_BUFFER += temp_burst_buffer structlog.get_logger("structlog").debug("[TNC] ARQ | RX | appending data to buffer") - - - # lets check if we didnt receive a BOF and EOF yet to avoid sending ack frames if we already received all data if not self.rx_frame_bof_received and not self.rx_frame_eof_received and data_in.find(self.data_frame_eof) < 0: @@ -474,7 +445,6 @@ class DATA(): # calculate statistics self.calculate_transfer_rate_rx(self.rx_start_of_transmission, len(static.RX_FRAME_BUFFER)) - # check if we received last frame of burst and we have "Nones" in our rx buffer # this is an indicator for missed frames. # with this way of doing this, we always MUST receive the last frame of a burst otherwise the entire @@ -490,7 +460,6 @@ class DATA(): # we need to work on this codec2.api.freedv_set_frames_per_burst(freedv,len(missing_frames)) - # then create a repeat frame rpt_frame = bytearray(14) rpt_frame[:1] = bytes([62]) @@ -508,12 +477,10 @@ class DATA(): time.sleep(0.01) self.calculate_transfer_rate_rx(self.rx_start_of_transmission, len(static.RX_FRAME_BUFFER)) - # we should never reach this point else: structlog.get_logger("structlog").error("we shouldnt reach this point...", frame=RX_N_FRAME_OF_BURST, frames=RX_N_FRAMES_PER_BURST) - # We have a BOF and EOF flag in our data. If we received both we received our frame. # In case of loosing data but we received already a BOF and EOF we need to make sure, we # received the complete last burst by checking it for Nones @@ -531,7 +498,6 @@ class DATA(): static.ARQ_COMPRESSION_FACTOR = compression_factor / 10 self.calculate_transfer_rate_rx(self.rx_start_of_transmission, len(static.RX_FRAME_BUFFER)) - if bof_position >= 0 and eof_position > 0 and not None in static.RX_BURST_BUFFER: print(f"bof_position {bof_position} / eof_position {eof_position}") self.rx_frame_bof_received = True @@ -545,7 +511,6 @@ class DATA(): static.TOTAL_BYTES = frame_length # 8:9 = compression factor - data_frame = payload[9:] data_frame_crc_received = helpers.get_crc_32(data_frame) @@ -554,17 +519,14 @@ class DATA(): if data_frame_crc == data_frame_crc_received: structlog.get_logger("structlog").info("[TNC] ARQ | RX | DATA FRAME SUCESSFULLY RECEIVED") - # decompression data_frame_decompressed = zlib.decompress(data_frame) static.ARQ_COMPRESSION_FACTOR = len(data_frame_decompressed) / len(data_frame) data_frame = data_frame_decompressed - uniqueid = str(uuid.uuid4()) timestamp = int(time.time()) - # check if callsign ssid override valid, mycallsign = helpers.check_callsign(self.mycallsign, self.received_mycall_crc) if not valid: @@ -622,7 +584,6 @@ class DATA(): while static.TRANSMITTING: time.sleep(0.01) - # update session timeout self.arq_session_last_received = int(time.time()) # we need to update our timeout timestamp @@ -631,8 +592,6 @@ class DATA(): if not TESTMODE: self.arq_cleanup() - - def arq_transmit(self, data_out:bytes, mode:int, n_frames_per_burst:int): """ @@ -644,7 +603,6 @@ class DATA(): Returns: """ - global TESTMODE self.arq_file_transfer = True @@ -663,7 +621,6 @@ class DATA(): DATA_FRAME_ACK_TIMEOUT_SECONDS = 3.0 # timeout for data frame acknowledges RPT_ACK_TIMEOUT_SECONDS = 3.0 # timeout for rpt frame acknowledges - # save len of data_out to TOTAL_BYTES for our statistics --> kBytes #static.TOTAL_BYTES = round(len(data_out) / 1024, 2) static.TOTAL_BYTES = len(data_out) @@ -674,10 +631,8 @@ class DATA(): json_data_out = json.dumps(jsondata) sock.SOCKET_QUEUE.put(json_data_out) - structlog.get_logger("structlog").info("[TNC] | TX | DATACHANNEL", mode=mode, Bytes=static.TOTAL_BYTES) - # compression data_frame_compressed = zlib.compress(data_out) compression_factor = len(data_out) / len(data_frame_compressed) @@ -694,7 +649,6 @@ class DATA(): frame_payload_crc = helpers.get_crc_32(data_out) structlog.get_logger("structlog").debug("frame payload crc", crc=frame_payload_crc) - # data_out = self.data_frame_bof + frame_payload_crc + data_out + self.data_frame_eof data_out = self.data_frame_bof + frame_payload_crc + frame_total_size + compression_factor + data_out + self.data_frame_eof @@ -704,10 +658,8 @@ class DATA(): # iterate through data out buffer while bufferposition < len(data_out) and not self.data_frame_ack_received and static.ARQ_STATE: - # we have TX_N_MAX_RETRIES_PER_BURST attempts for sending a burst for self.tx_n_retry_of_burst in range(0,TX_N_MAX_RETRIES_PER_BURST): - # AUTO MODE SELECTION # mode 255 == AUTO MODE # force usage of selected mode @@ -715,7 +667,6 @@ class DATA(): data_mode = mode structlog.get_logger("structlog").debug("FIXED MODE", mode=data_mode) - else: # we are doing a modulo check of transmission retries of the actual burst # every 2nd retry which failes, decreases speedlevel by 1. @@ -735,8 +686,6 @@ class DATA(): # self.speed_level = len(self.mode_list)-1 # if speed level is greater than our available modes, set speed level to maximum = lenght of mode list -1 - - if self.speed_level >= len(self.mode_list): self.speed_level = len(self.mode_list) - 1 static.ARQ_SPEED_LEVEL = self.speed_level @@ -744,8 +693,6 @@ class DATA(): structlog.get_logger("structlog").debug("Speed-level:", level=self.speed_level, retry=self.tx_n_retry_of_burst, mode=data_mode) - - # payload information payload_per_frame = modem.get_bytes_per_frame(data_mode) -2 @@ -755,7 +702,6 @@ class DATA(): # append data frames with TX_N_FRAMES_PER_BURST to tempbuffer # this part ineeds to a completly rewrite! # TX_NF_RAMES_PER_BURST = 1 is working - arqheader = bytearray() arqheader[:1] = bytes([10]) #bytes([10 + i]) arqheader[1:2] = bytes([TX_N_FRAMES_PER_BURST]) @@ -766,7 +712,6 @@ class DATA(): # normal behavior if bufferposition_end <= len(data_out): - frame = data_out[bufferposition:bufferposition_end] frame = arqheader + frame @@ -780,7 +725,6 @@ class DATA(): extended_data_out += bytes([0]) * (payload_per_frame-len(extended_data_out)-len(arqheader)) frame = arqheader + extended_data_out - # append frame to tempbuffer for transmission tempbuffer.append(frame) @@ -822,7 +766,6 @@ class DATA(): if self.data_frame_ack_received: break #break retry loop - # we need this part for leaving the repeat loop # static.ARQ_STATE == 'DATA' --> when stopping transmission manually if not static.ARQ_STATE: @@ -845,9 +788,7 @@ class DATA(): #GOING TO NEXT ITERATION - if self.data_frame_ack_received: - static.INFO.append("ARQ;TRANSMITTING;SUCCESS") jsondata = {"arq":"transmission", "status" :"success", "uuid" : self.transmission_uuid, "percent" : static.ARQ_TRANSMISSION_PERCENT, "bytesperminute" : static.ARQ_BYTES_PER_MINUTE} json_data_out = json.dumps(jsondata) @@ -855,8 +796,6 @@ class DATA(): structlog.get_logger("structlog").info("ARQ | TX | DATA TRANSMITTED!", BytesPerMinute=static.ARQ_BYTES_PER_MINUTE, BitsPerSecond=static.ARQ_BITS_PER_SECOND, overflows=static.BUFFER_OVERFLOW_COUNTER) - - else: static.INFO.append("ARQ;TRANSMITTING;FAILED") jsondata = {"arq":"transmission", "status" :"failed", "uuid" : self.transmission_uuid, "percent" : static.ARQ_TRANSMISSION_PERCENT, "bytesperminute" : static.ARQ_BYTES_PER_MINUTE} @@ -876,8 +815,6 @@ class DATA(): import os os._exit(0) - - # signalling frames received def burst_ack_received(self, data_in:bytes): """ @@ -888,7 +825,6 @@ class DATA(): Returns: """ - # increase speed level if we received a burst ack #self.speed_level += 1 #if self.speed_level >= len(self.mode_list)-1: @@ -907,6 +843,7 @@ class DATA(): self.burst_nack_counter = 0 # reset n retries per burst counter self.n_retries_per_burst = 0 + # signalling frames received def burst_nack_received(self, data_in:bytes): """ @@ -917,7 +854,6 @@ class DATA(): Returns: """ - # increase speed level if we received a burst ack #self.speed_level += 1 #if self.speed_level >= len(self.mode_list)-1: @@ -934,7 +870,6 @@ class DATA(): self.burst_nack_counter += 1 print(self.speed_level) - def frame_ack_received(self): """ """ # only process data if we are in ARQ and BUSY state @@ -963,8 +898,6 @@ class DATA(): if not TESTMODE: self.arq_cleanup() - - def burst_rpt_received(self, data_in:bytes): """ @@ -974,7 +907,6 @@ class DATA(): Returns: """ - # only process data if we are in ARQ and BUSY state if static.ARQ_STATE and static.TNC_STATE == 'BUSY': helpers.add_to_heard_stations(static.DXCALLSIGN,static.DXGRID, 'DATA-CHANNEL', static.SNR, static.FREQ_OFFSET, static.HAMLIB_FREQUENCY) @@ -990,8 +922,6 @@ class DATA(): missing = missing_area[i:i + 2] self.rpt_request_buffer.insert(0, missing) - - # ############################################################################################################ # ARQ SESSION HANDLER # ############################################################################################################ @@ -1023,7 +953,6 @@ class DATA(): static.ARQ_SESSION_STATE = 'failed' return False - def open_session(self, callsign): """ @@ -1044,7 +973,6 @@ class DATA(): connection_frame[4:7] = static.MYCALLSIGN_CRC connection_frame[7:13] = helpers.callsign_to_bytes(self.mycallsign) - while not static.ARQ_SESSION: time.sleep(0.01) for attempt in range(1,self.session_connect_max_retries+1): @@ -1077,7 +1005,6 @@ class DATA(): self.close_session() return False - def received_session_opener(self, data_in:bytes): """ @@ -1102,7 +1029,6 @@ class DATA(): self.transmit_session_heartbeat() - def close_session(self): """ """ static.ARQ_SESSION_STATE = 'disconnecting' @@ -1153,7 +1079,6 @@ class DATA(): def transmit_session_heartbeat(self): """ """ - # static.ARQ_SESSION = True # static.TNC_STATE = 'BUSY' # static.ARQ_SESSION_STATE = 'connected' @@ -1165,7 +1090,6 @@ class DATA(): connection_frame[1:4] = static.DXCALLSIGN_CRC connection_frame[4:7] = static.MYCALLSIGN_CRC - txbuffer = [connection_frame] static.TRANSMITTING = True @@ -1174,9 +1098,6 @@ class DATA(): while static.TRANSMITTING: time.sleep(0.01) - - - def received_session_heartbeat(self, data_in:bytes): """ @@ -1186,7 +1107,6 @@ class DATA(): Returns: """ - # Accept session data if the DXCALLSIGN_CRC matches the station in static. _valid_crc, _ = helpers.check_callsign(static.DXCALLSIGN, bytes(data_in[4:7])) if _valid_crc: @@ -1229,7 +1149,6 @@ class DATA(): if static.ARQ_SESSION: time.sleep(0.5) - self.datachannel_timeout = False # we need to compress data for gettin a compression factor. @@ -1269,7 +1188,6 @@ class DATA(): frametype = bytes([225]) structlog.get_logger("structlog").debug("requesting high bandwith mode") - if 230 <= mode <= 240: structlog.get_logger("structlog").debug("requesting manual mode --> not yet implemented ") frametype = bytes([mode]) @@ -1320,10 +1238,6 @@ class DATA(): return False #sys.exit() # close thread and so connection attempts - - - - def arq_received_data_channel_opener(self, data_in:bytes): """ @@ -1353,7 +1267,6 @@ class DATA(): self.time_list = self.time_list_low_bw self.speed_level = len(self.mode_list) - 1 - if 230 <= frametype <= 240: print("manual mode request") @@ -1375,7 +1288,6 @@ class DATA(): static.ARQ_STATE = True static.TNC_STATE = 'BUSY' - self.reset_statistics() self.data_channel_last_received = int(time.time()) @@ -1405,8 +1317,6 @@ class DATA(): # set start of transmission for our statistics self.rx_start_of_transmission = time.time() - - def arq_received_channel_is_open(self, data_in:bytes): """ Called if we received a data channel opener @@ -1448,7 +1358,6 @@ class DATA(): structlog.get_logger("structlog").warning("protocol version missmatch", received=protocol_version, own=static.ARQ_PROTOCOL_VERSION) self.arq_cleanup() - # ---------- PING def transmit_ping(self, dxcallsign:bytes): """ @@ -1492,7 +1401,6 @@ class DATA(): Returns: """ - static.DXCALLSIGN_CRC = bytes(data_in[4:7]) static.DXCALLSIGN = helpers.bytes_to_callsign(bytes(data_in[7:13])) helpers.add_to_heard_stations(static.DXCALLSIGN, static.DXGRID, 'PING', static.SNR, static.FREQ_OFFSET, static.HAMLIB_FREQUENCY) @@ -1534,7 +1442,6 @@ class DATA(): Returns: """ - static.DXCALLSIGN_CRC = bytes(data_in[4:7]) static.DXGRID = bytes(data_in[7:13]).rstrip(b'\x00') @@ -1549,7 +1456,6 @@ class DATA(): structlog.get_logger("structlog").info("[TNC] PING ACK [" + str(self.mycallsign, 'utf-8') + "] >|< [" + str(static.DXCALLSIGN, 'utf-8') + "]", snr=static.SNR ) static.TNC_STATE = 'IDLE' - def stop_transmission(self): """ Force a stop of the running transmission @@ -1594,7 +1500,6 @@ class DATA(): """ try: - while 1: time.sleep(0.5) while static.BEACON_STATE: @@ -1616,7 +1521,6 @@ class DATA(): else: modem.MODEM_TRANSMIT_QUEUE.put([14,1,0,txbuffer]) - # wait while transmitting while static.TRANSMITTING: time.sleep(0.01) @@ -1649,7 +1553,6 @@ class DATA(): structlog.get_logger("structlog").info("[TNC] BEACON RCVD [" + str(dxcallsign, 'utf-8') + "]["+ str(dxgrid, 'utf-8') +"] ", snr=static.SNR) helpers.add_to_heard_stations(dxcallsign,dxgrid, 'BEACON', static.SNR, static.FREQ_OFFSET, static.HAMLIB_FREQUENCY) - def transmit_cq(self): """ Transmit a CQ @@ -1675,7 +1578,6 @@ class DATA(): time.sleep(0.01) return - def received_cq(self, data_in:bytes): """ Called if we received a CQ @@ -1696,7 +1598,6 @@ class DATA(): if static.RESPOND_TO_CQ: self.transmit_qrv() - def transmit_qrv(self): """ Called if we send a QRV frame @@ -1731,7 +1632,6 @@ class DATA(): while static.TRANSMITTING: time.sleep(0.01) - def received_qrv(self, data_in:bytes): """ Called if we receive a QRV frame @@ -1753,7 +1653,6 @@ class DATA(): structlog.get_logger("structlog").info("[TNC] QRV RCVD [" + str(dxcallsign, 'utf-8') + "]["+ str(dxgrid, 'utf-8') +"] ", snr=static.SNR) helpers.add_to_heard_stations(dxcallsign,dxgrid, 'QRV', static.SNR, static.FREQ_OFFSET, static.HAMLIB_FREQUENCY) - # ------------ CALUCLATE TRANSFER RATES def calculate_transfer_rate_rx(self, rx_start_of_transmission:float, receivedbytes:int) -> list: """ @@ -1765,7 +1664,6 @@ class DATA(): Returns: """ - try: if static.TOTAL_BYTES == 0: static.TOTAL_BYTES = 1 @@ -1791,8 +1689,6 @@ class DATA(): static.ARQ_BYTES_PER_MINUTE, \ static.ARQ_TRANSMISSION_PERCENT] - - def reset_statistics(self): """ Reset statistics @@ -1816,7 +1712,6 @@ class DATA(): Returns: """ - try: static.ARQ_TRANSMISSION_PERCENT = int((sentbytes / tx_buffer_length) * 100) @@ -1843,14 +1738,12 @@ class DATA(): static.ARQ_BYTES_PER_MINUTE, \ static.ARQ_TRANSMISSION_PERCENT] - # ----------------------CLEANUP AND RESET FUNCTIONS def arq_cleanup(self): """ Cleanup funktion which clears all ARQ states """ - structlog.get_logger("structlog").debug("cleanup") self.received_mycall_crc = b'' @@ -1894,10 +1787,6 @@ class DATA(): static.BEACON_PAUSE = False - - - - def arq_reset_ack(self,state:bool): """ Funktion for resetting acknowledge states @@ -1907,12 +1796,10 @@ class DATA(): Returns: """ - self.burst_ack = state self.rpt_request_received = state self.data_frame_ack_received = state - def set_listening_modes(self, mode): """ Function for setting the data modes we are listening to for saving cpu power @@ -1941,7 +1828,6 @@ class DATA(): modem.RECEIVE_FSK_LDPC_1 = True structlog.get_logger("structlog").debug("changing listening data mode", mode="datac1/datac3/fsk_ldpc") - # ------------------------- WATCHDOG FUNCTIONS FOR TIMER def watchdog(self): """Author: DJ2LS @@ -1959,13 +1845,11 @@ class DATA(): self.burst_watchdog() self.arq_session_keep_alive_watchdog() - def burst_watchdog(self): """ watchdog which checks if we are running into a connection timeout DATA BURST """ - # IRS SIDE if static.ARQ_STATE and static.ARQ_SESSION_STATE == 'connected' and static.TNC_STATE == 'BUSY' and self.is_IRS: if self.data_channel_last_received + self.time_list[self.speed_level] > time.time(): @@ -2011,13 +1895,11 @@ class DATA(): self.stop_transmission() self.arq_cleanup() - def data_channel_keep_alive_watchdog(self): """ watchdog which checks if we are running into a connection timeout DATA CHANNEL """ - # and not static.ARQ_SEND_KEEP_ALIVE: if static.ARQ_STATE and static.TNC_STATE == 'BUSY': time.sleep(0.01) @@ -2045,8 +1927,6 @@ class DATA(): static.INFO.append("ARQ;SESSION;TIMEOUT") self.close_session() - - def heartbeat(self): """ heartbeat thread which auto resumes the heartbeat signal within a arq session @@ -2058,7 +1938,5 @@ class DATA(): self.transmit_session_heartbeat() time.sleep(2) - - def send_test_frame(self): modem.MODEM_TRANSMIT_QUEUE.put([12,1,0,[bytearray(126)]]) diff --git a/tnc/helpers.py b/tnc/helpers.py index f5782607..7a922c3d 100644 --- a/tnc/helpers.py +++ b/tnc/helpers.py @@ -5,13 +5,10 @@ Created on Fri Dec 25 21:25:14 2020 @author: DJ2LS """ - import time import crcengine import static - - def wait(seconds): """ @@ -27,8 +24,6 @@ def wait(seconds): time.sleep(0.01) return True - - def get_crc_8(data): """Author: DJ2LS @@ -47,7 +42,6 @@ def get_crc_8(data): crc_data = crc_data.to_bytes(1, byteorder='big') return crc_data - def get_crc_16(data): """Author: DJ2LS @@ -87,7 +81,6 @@ def get_crc_24(data): crc_data = crc_data.to_bytes(3, byteorder='big') return crc_data - def get_crc_32(data): """Author: DJ2LS @@ -106,7 +99,6 @@ def get_crc_32(data): crc_data = crc_data.to_bytes(4, byteorder='big') return crc_data - def add_to_heard_stations(dxcallsign, dxgrid, datatype, snr, offset, frequency): """ @@ -137,14 +129,11 @@ def add_to_heard_stations(dxcallsign, dxgrid, datatype, snr, offset, frequency): static.HEARD_STATIONS.append([dxcallsign, dxgrid, int(time.time()), datatype, snr, offset, frequency]) break - # for idx, item in enumerate(static.HEARD_STATIONS): # if dxcallsign in item: # item = [dxcallsign, int(time.time())] # static.HEARD_STATIONS[idx] = item - - def callsign_to_bytes(callsign): """ @@ -195,7 +184,6 @@ def callsign_to_bytes(callsign): ssid = bytes([ssid]).decode("utf-8") return encode_call(callsign + ssid) - #return bytes(bytestring) def bytes_to_callsign(bytestring): @@ -209,7 +197,6 @@ def bytes_to_callsign(bytestring): bytes """ - # http://www.aprs.org/aprs11/SSIDs.txt #-0 Your primary station usually fixed and message capable #-1 generic additional station, digi, mobile, wx, etc @@ -246,8 +233,6 @@ def bytes_to_callsign(bytestring): ssid = ord(bytes(decoded[-1], "utf-8")) return bytes(callsign + "-" + str(ssid), "utf-8") - - def check_callsign(callsign:bytes, crc_to_check:bytes): """ Funktion to check a crc against a callsign to calculate the ssid by generating crc until we got it @@ -260,7 +245,6 @@ def check_callsign(callsign:bytes, crc_to_check:bytes): [True, Callsign + SSID] False """ - print(callsign) try: callsign = callsign.split(b'-') @@ -282,8 +266,6 @@ def check_callsign(callsign:bytes, crc_to_check:bytes): return [False, ""] - - def encode_grid(grid): """ @auther: DB1UJ @@ -345,8 +327,6 @@ def decode_grid(b_code_word:bytes): return grid - - def encode_call(call): """ @auther: DB1UJ @@ -390,4 +370,3 @@ def decode_call(b_code_word:bytes): call = call[0:-1] + ssid # remove the last char from call and replace with SSID return call - diff --git a/tnc/log_handler.py b/tnc/log_handler.py index a14a4159..6d489cca 100644 --- a/tnc/log_handler.py +++ b/tnc/log_handler.py @@ -8,7 +8,6 @@ def setup_logging(filename): Returns: """ - import logging.config import structlog diff --git a/tnc/main.py b/tnc/main.py index e45a54bf..a3a2fe4d 100755 --- a/tnc/main.py +++ b/tnc/main.py @@ -6,11 +6,7 @@ Created on Tue Dec 22 16:58:45 2020 @author: DJ2LS main module for running the tnc - - """ - - import argparse import threading import static @@ -26,7 +22,6 @@ import signal import time import multiprocessing - # signal handler for closing aplication def signal_handler(sig, frame): """ @@ -75,7 +70,6 @@ if __name__ == '__main__': PARSER.add_argument('--tuning_range_fmax', dest="tuning_range_fmax", choices=[50.0, 100.0, 150.0, 200.0, 250.0], default=50.0, help="Tuning range fmax", type=float) PARSER.add_argument('--tx-audio-level', dest="tx_audio_level", default=50, help="Set the tx audio level at an early stage", type=int) - ARGS = PARSER.parse_args() # additional step for beeing sure our callsign is correctly @@ -132,8 +126,6 @@ if __name__ == '__main__': except: structlog.get_logger("structlog").error("[DMN] logger init error") - - structlog.get_logger("structlog").info("[TNC] Starting FreeDATA", author="DJ2LS", year="2022", version=static.VERSION) # start data handler @@ -142,7 +134,6 @@ if __name__ == '__main__': # start modem modem = modem.RF() - # --------------------------------------------START CMD SERVER try: diff --git a/tnc/modem.py b/tnc/modem.py index a6a46864..0722cbc2 100644 --- a/tnc/modem.py +++ b/tnc/modem.py @@ -40,7 +40,6 @@ RECEIVE_DATAC1 = False RECEIVE_DATAC3 = False RECEIVE_FSK_LDPC_1 = False - class RF(): """ """ @@ -49,7 +48,6 @@ class RF(): self.sampler_avg = 0 self.buffer_avg = 0 - self.AUDIO_SAMPLE_RATE_RX = 48000 self.AUDIO_SAMPLE_RATE_TX = 48000 self.MODEM_SAMPLE_RATE = codec2.api.FREEDV_FS_8000 @@ -107,7 +105,6 @@ class RF(): codec2.api.freedv_set_frames_per_burst(self.datac3_freedv,1) self.datac3_buffer = codec2.audio_buffer(2*self.AUDIO_FRAMES_PER_BUFFER_RX) - self.fsk_ldpc_freedv_0 = cast(codec2.api.freedv_open_advanced(codec2.api.FREEDV_MODE_FSK_LDPC, ctypes.byref(codec2.api.FREEDV_MODE_FSK_LDPC_0_ADV)), c_void_p) self.fsk_ldpc_bytes_per_frame_0 = int(codec2.api.freedv_get_bits_per_modem_frame(self.fsk_ldpc_freedv_0)/8) self.fsk_ldpc_bytes_out_0 = create_string_buffer(self.fsk_ldpc_bytes_per_frame_0) @@ -147,7 +144,6 @@ class RF(): structlog.get_logger("structlog").error("[TNC] starting pyaudio callback failed", e=e) else: - # create a stream object for simulating audio stream class Object(object): pass @@ -168,7 +164,6 @@ class RF(): mkfifo_read_callback_thread = threading.Thread(target=self.mkfifo_read_callback, name="MKFIFO READ CALLBACK THREAD",daemon=True) mkfifo_read_callback_thread.start() - # --------------------------------------------INIT AND OPEN HAMLIB # check how we want to control the radio if static.HAMLIB_RADIOCONTROL == 'direct': @@ -182,7 +177,6 @@ class RF(): else: import rigdummy as rig - self.hamlib = rig.radio() self.hamlib.open_rig(devicename=static.HAMLIB_DEVICE_NAME, deviceport=static.HAMLIB_DEVICE_PORT, hamlib_ptt_type=static.HAMLIB_PTT_TYPE, serialspeed=static.HAMLIB_SERIAL_SPEED, pttport=static.HAMLIB_PTT_PORT, data_bits=static.HAMLIB_DATA_BITS, stop_bits=static.HAMLIB_STOP_BITS, handshake=static.HAMLIB_HANDSHAKE, rigctld_ip = static.HAMLIB_RGICTLD_IP, rigctld_port = static.HAMLIB_RGICTLD_PORT) @@ -219,7 +213,6 @@ class RF(): # -------------------------------------------------------------------------------------------------------- def mkfifo_read_callback(self): while 1: - time.sleep(0.01) # -----read data_in48k = bytes() @@ -245,8 +238,6 @@ class RF(): if RECEIVE_DATAC3: self.datac3_buffer.push(x) - - def mkfifo_write_callback(self): while 1: time.sleep(0.01) @@ -264,7 +255,6 @@ class RF(): fifo_write.write(data_out48k) fifo_write.flush() - # -------------------------------------------------------------------------------------------------------- #def audio_callback(self, data_in48k, frame_count, time_info, status): def callback(self, data_in48k, outdata, frames, time, status): @@ -279,7 +269,6 @@ class RF(): Returns: """ - x = np.frombuffer(data_in48k, dtype=np.int16) x = self.resampler.resample48_to_8(x) @@ -358,18 +347,15 @@ class RF(): data_out = json.dumps(jsondata) sock.SOCKET_QUEUE.put(data_out) - # open codec2 instance self.MODE = mode if self.MODE == 'FSK_LDPC_0' or self.MODE == 200: freedv = cast(codec2.api.freedv_open_advanced(codec2.api.FREEDV_MODE_FSK_LDPC, ctypes.byref(codec2.api.FREEDV_MODE_FSK_LDPC_0_ADV)), c_void_p) elif self.MODE == 'FSK_LDPC_1' or self.MODE == 201: freedv = cast(codec2.api.freedv_open_advanced(codec2.api.FREEDV_MODE_FSK_LDPC, ctypes.byref(codec2.api.FREEDV_MODE_FSK_LDPC_1_ADV)), c_void_p) - else: freedv = cast(codec2.api.freedv_open(self.MODE), c_void_p) - # get number of bytes per frame for mode bytes_per_frame = int(codec2.api.freedv_get_bits_per_modem_frame(freedv)/8) payload_bytes_per_frame = bytes_per_frame -2 @@ -415,7 +401,6 @@ class RF(): codec2.api.freedv_rawdatatx(freedv,mod_out,data) # modulate DATA and save it into mod_out pointer txbuffer += bytes(mod_out) - # codec2 fsk preamble may be broken - at least it sounds like that so we are disabling it for testing if not self.MODE == 'FSK_LDPC_0' or self.MODE == 200 or self.MODE == 'FSK_LDPC_1' or self.MODE == 201: # write preamble to txbuffer @@ -437,12 +422,8 @@ class RF(): # deaktivated for testing purposes self.mod_out_locked = False - # ------------------------------- - - - chunk_length = self.AUDIO_FRAMES_PER_BUFFER_TX #4800 chunk = [txbuffer_48k[i:i+chunk_length] for i in range(0, len(txbuffer_48k), chunk_length)] for c in chunk: @@ -455,8 +436,6 @@ class RF(): #structlog.get_logger("structlog").debug("[TNC] mod out shorter than audio buffer", delta=delta) self.modoutqueue.append(c) - - # Release our mod_out_lock so we can use the queue self.mod_out_locked = False @@ -553,8 +532,6 @@ class RF(): #self.get_scatter(self.fsk_ldpc_freedv_1) self.calculate_snr(self.fsk_ldpc_freedv_1) - - # worker for FIFO queue for processing received frames def worker_transmit(self): """ """ @@ -564,8 +541,6 @@ class RF(): self.transmit(mode=data[0], repeats=data[1], repeat_delay=data[2], frames=data[3]) #self.modem_transmit_queue.task_done() - - # worker for FIFO queue for processing received frames def worker_received(self): """ """ @@ -577,7 +552,6 @@ class RF(): data_handler.DATA_QUEUE_RECEIVED.put([data[0], data[1], data[2]]) self.modem_received_queue.task_done() - def get_frequency_offset(self, freedv): """ @@ -594,7 +568,6 @@ class RF(): static.FREQ_OFFSET = offset return offset - def get_scatter(self, freedv): """ @@ -629,7 +602,6 @@ class RF(): scatterdata_small = scatterdata[::10] static.SCATTER = scatterdata_small - def calculate_snr(self, freedv): """ @@ -639,7 +611,6 @@ class RF(): Returns: """ - try: modem_stats_snr = c_float() modem_stats_sync = c_int() @@ -666,7 +637,6 @@ class RF(): static.HAMLIB_MODE = self.hamlib.get_mode() static.HAMLIB_BANDWITH = self.hamlib.get_bandwith() - def calculate_fft(self): """ """ # channel_busy_delay counter @@ -678,7 +648,6 @@ class RF(): # WE NEED TO OPTIMIZE THIS! if len(self.fft_data) >= 128: - # https://gist.github.com/ZWMiller/53232427efc5088007cab6feee7c6e4c # Fast Fourier Transform, 10*log10(abs) is to scale it to dB # and make sure it's not imaginary @@ -693,7 +662,6 @@ class RF(): # get average of dfft avg = np.mean(dfft) - # detect signals which are higher than the average + 10 ( +10 smoothes the output ) # data higher than the average must be a signal. Therefore we are setting it to 100 so it will be highlighted # have to do this when we are not transmittig so our own sending data will not affect this too much @@ -703,7 +671,6 @@ class RF(): # calculate audio max value # static.AUDIO_RMS = np.amax(self.fft_data) - # check for signals higher than average by checking for "100" # if we have a signal, increment our channel_busy delay counter so we have a smoother state toggle @@ -728,9 +695,7 @@ class RF(): static.FFT = dfftlist[0:320] #320 --> bandwith 3000 - except: - structlog.get_logger("structlog").debug("[TNC] Setting fft=0") # else 0 static.FFT = [0] @@ -750,8 +715,6 @@ class RF(): codec2.api.freedv_set_frames_per_burst(self.datac3_freedv,n_frames_per_burst) codec2.api.freedv_set_frames_per_burst(self.fsk_ldpc_freedv_0,n_frames_per_burst) - - def get_bytes_per_frame(mode): """ provide bytes per frame information for accessing from data handler @@ -772,9 +735,6 @@ def get_bytes_per_frame(mode): # get number of bytes per frame for mode return int(codec2.api.freedv_get_bits_per_modem_frame(freedv)/8) - def set_audio_volume(datalist, volume): data = np.fromstring(datalist, np.int16) * (volume / 100.) return data.astype(np.int16) - - diff --git a/tnc/rig.py b/tnc/rig.py index 8e64784b..0016b77d 100644 --- a/tnc/rig.py +++ b/tnc/rig.py @@ -7,7 +7,6 @@ import atexit import subprocess import os - # set global hamlib version hamlib_version = 0 @@ -19,7 +18,6 @@ except: app_path = os.path.abspath(".") sys.path.append(app_path) - # try importing hamlib try: # get python version @@ -76,7 +74,6 @@ except Exception as e: class radio: """ """ def __init__(self): - self.devicename = '' self.devicenumber = '' self.deviceport = '' @@ -106,7 +103,6 @@ class radio: Returns: """ - self.devicename = devicename self.deviceport = str(deviceport) self.serialspeed = str(serialspeed) # we need to ensure this is a str, otherwise set_conf functions are crashing @@ -116,7 +112,6 @@ class radio: self.stop_bits = str(stop_bits) self.handshake = str(handshake) - # try to init hamlib try: Hamlib.rig_set_debug(Hamlib.RIG_DEBUG_NONE) @@ -128,7 +123,6 @@ class radio: structlog.get_logger("structlog").error("[RIG] Hamlib: rig not supported...") self.devicenumber = 0 - self.my_rig = Hamlib.Rig(self.devicenumber) self.my_rig.set_conf("rig_pathname", self.deviceport) self.my_rig.set_conf("retry", "5") @@ -138,9 +132,6 @@ class radio: self.my_rig.set_conf("data_bits", self.data_bits) self.my_rig.set_conf("ptt_pathname", self.pttport) - - - if self.hamlib_ptt_type == 'RIG': self.hamlib_ptt_type = Hamlib.RIG_PTT_RIG self.my_rig.set_conf("ptt_type", 'RIG') @@ -149,7 +140,6 @@ class radio: self.hamlib_ptt_type = Hamlib.RIG_PORT_USB self.my_rig.set_conf("ptt_type", 'USB') - elif self.hamlib_ptt_type == 'DTR-H': self.hamlib_ptt_type = Hamlib.RIG_PTT_SERIAL_DTR self.my_rig.set_conf("dtr_state", "HIGH") @@ -182,7 +172,6 @@ class radio: structlog.get_logger("structlog").info("[RIG] Opening...", device=self.devicenumber, path=self.my_rig.get_conf("rig_pathname"), serial_speed=self.my_rig.get_conf("serial_speed"), serial_handshake=self.my_rig.get_conf("serial_handshake"), stop_bits=self.my_rig.get_conf("stop_bits"), data_bits=self.my_rig.get_conf("data_bits"), ptt_pathname=self.my_rig.get_conf("ptt_pathname")) - self.my_rig.open() atexit.register(self.my_rig.close) @@ -199,7 +188,6 @@ class radio: except: structlog.get_logger("structlog").info("[RIG] Hamlib device opened", status='SUCCESS') - # set ptt to false if ptt is stuck for some reason self.set_ptt(False) diff --git a/tnc/rigctl.py b/tnc/rigctl.py index 229176c9..3e92e093 100644 --- a/tnc/rigctl.py +++ b/tnc/rigctl.py @@ -18,10 +18,10 @@ import os # set global hamlib version hamlib_version = 0 + class radio: """ """ def __init__(self): - self.devicename = '' self.devicenumber = '' self.deviceport = '' @@ -51,7 +51,6 @@ class radio: Returns: """ - self.devicename = devicename self.deviceport = deviceport self.serialspeed = str(serialspeed) # we need to ensure this is a str, otherwise set_conf functions are crashing @@ -61,8 +60,7 @@ class radio: self.stop_bits = stop_bits self.handshake = handshake - - # check if we are running in a pyinstaller environment + # check if we are running in a pyinstaller environment try: app_path = sys._MEIPASS except: @@ -86,9 +84,6 @@ class radio: print(self.devicenumber, self.deviceport, self.serialspeed) - - - # select precompiled executable for win32/win64 rigctl # this is really a hack...somewhen we need a native hamlib integration for windows if sys.platform == 'win32' or sys.platform == 'win64': @@ -116,7 +111,6 @@ class radio: except: return False - def get_mode(self): """ """ #(hamlib_mode, bandwith) = self.my_rig.get_mode() @@ -126,7 +120,6 @@ class radio: except: return False - def get_bandwith(self): """ """ #(hamlib_mode, bandwith) = self.my_rig.get_mode() diff --git a/tnc/rigctld.py b/tnc/rigctld.py index ea7452a8..f21b1d3f 100644 --- a/tnc/rigctld.py +++ b/tnc/rigctld.py @@ -5,6 +5,7 @@ import log_handler import logging import time import static + # class taken from darsidelemm # rigctl - https://github.com/darksidelemm/rotctld-web-gui/blob/master/rotatorgui.py#L35 # @@ -13,6 +14,7 @@ import static # set global hamlib version hamlib_version = 0 + class radio(): """rotctld (hamlib) communication class""" # Note: This is a massive hack. @@ -48,7 +50,6 @@ class radio(): self.hostname = rigctld_ip self.port = int(rigctld_port) - if self.connect(): logging.debug(f"Rigctl intialized") return True @@ -75,7 +76,6 @@ class radio(): self.sock.close() self.connected = False - def send_command(self, command): """Send a command to the connected rotctld instance, and return the return value. @@ -104,7 +104,6 @@ class radio(): time.sleep(0.5) self.connect() - def get_mode(self): """ """ try: @@ -114,6 +113,7 @@ class radio(): return mode.decode("utf-8") except: 0 + def get_bandwith(self): """ """ try: diff --git a/tnc/rigdummy.py b/tnc/rigdummy.py index 06bcc38f..445cfb58 100644 --- a/tnc/rigdummy.py +++ b/tnc/rigdummy.py @@ -4,12 +4,12 @@ import structlog hamlib_version = 0 + class radio: """ """ def __init__(self): pass - def open_rig(self, **kwargs): """ @@ -62,4 +62,3 @@ class radio: def close_rig(self): """ """ return - diff --git a/tnc/sock.py b/tnc/sock.py index 2c5b9af2..c3e3bd47 100644 --- a/tnc/sock.py +++ b/tnc/sock.py @@ -42,10 +42,6 @@ CONNECTED_CLIENTS = set() CLOSE_SIGNAL = False - - - - class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): """ the socket handler base class @@ -53,11 +49,9 @@ class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass - class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): """ """ - def send_to_client(self): """ function called by socket handler @@ -66,10 +60,8 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): """ tempdata = b'' while self.connection_alive and not CLOSE_SIGNAL: - # send tnc state as network stream # check server port against daemon port and send corresponding data - if self.server.server_address[1] == static.PORT and not static.TNCSTARTED: data = send_tnc_state() if data != tempdata: @@ -82,7 +74,6 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): SOCKET_QUEUE.put(data) time.sleep(0.5) - while not SOCKET_QUEUE.empty(): data = SOCKET_QUEUE.get() sock_data = bytes(data, 'utf-8') @@ -120,7 +111,6 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): #print("connection broken. Closing...") self.connection_alive = False - if data.startswith(b'{') and data.endswith(b'}\n'): # split data by \n if we have multiple commands in socket buffer data = data.split(b'\n') @@ -141,19 +131,16 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): # and which one can be processed during a running transmission time.sleep(3) - # finally delete our rx buffer to be ready for new commands data = bytes() except Exception as e: structlog.get_logger("structlog").info("[SCK] Connection closed", ip=self.client_address[0], port=self.client_address[1], e=e) self.connection_alive = False - def handle(self): """ socket handler """ - CONNECTED_CLIENTS.add(self.request) structlog.get_logger("structlog").debug("[SCK] Client connected", ip=self.client_address[0], port=self.client_address[1]) @@ -166,8 +153,6 @@ class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): while self.connection_alive and not CLOSE_SIGNAL: time.sleep(1) - - def finish(self): """ """ structlog.get_logger("structlog").warning("[SCK] Closing client socket", ip=self.client_address[0], port=self.client_address[1]) @@ -189,7 +174,6 @@ 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) structlog.get_logger("structlog").debug("[SCK] CMD", command=received_json) @@ -203,7 +187,6 @@ def process_tnc_commands(data): command_response("tx_audio_level", False) structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) - # TRANSMIT SINE WAVE ----------------------------------------------------- if received_json["type"] == "set" and received_json["command"] == "send_test_frame": try: @@ -222,6 +205,7 @@ def process_tnc_commands(data): except Exception as e: command_response("cqcqcq", False) structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) + # START_BEACON ----------------------------------------------------- if received_json["command"] == "start_beacon": try: @@ -262,7 +246,6 @@ def process_tnc_commands(data): command_response("ping", False) structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) - # CONNECT ---------------------------------------------------------- if received_json["type"] == 'arq' and received_json["command"] == "connect": static.BEACON_PAUSE = True @@ -297,7 +280,6 @@ def process_tnc_commands(data): # TRANSMIT RAW DATA ------------------------------------------- if received_json["type"] == 'arq' and received_json["command"] == "send_raw": - static.BEACON_PAUSE = True try: if not static.ARQ_SESSION: @@ -314,7 +296,6 @@ def process_tnc_commands(data): dxcallsign = static.DXCALLSIGN static.DXCALLSIGN_CRC = helpers.get_crc_24(static.DXCALLSIGN) - mode = int(received_json["parameter"][0]["mode"]) n_frames = int(received_json["parameter"][0]["n_frames"]) base64data = received_json["parameter"][0]["data"] @@ -335,15 +316,13 @@ def process_tnc_commands(data): binarydata = base64.b64decode(base64data) data_handler.DATA_QUEUE_TRANSMIT.put(['ARQ_RAW', binarydata, mode, n_frames, arq_uuid, mycallsign]) - else: raise TypeError + except Exception as e: command_response("send_raw", False) structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) - - # STOP TRANSMISSION ---------------------------------------------------------- if received_json["type"] == 'arq' and received_json["command"] == "stop_transmission": try: @@ -357,7 +336,6 @@ def process_tnc_commands(data): command_response("stop_transmission", False) structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) - if received_json["type"] == 'get' and received_json["command"] == 'rx_buffer': try: output = { @@ -380,7 +358,6 @@ def process_tnc_commands(data): command_response("rx_buffer", False) structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) - if received_json["type"] == 'set' and received_json["command"] == 'del_rx_buffer': try: static.RX_BUFFER = [] @@ -397,7 +374,6 @@ def send_tnc_state(): """ send the tnc state to network """ - encoding = 'utf-8' output = { @@ -438,7 +414,6 @@ def send_tnc_state(): jsondata = json.dumps(output) return jsondata - def process_daemon_commands(data): """ process daemon commands @@ -469,7 +444,6 @@ def process_daemon_commands(data): command_response("mycallsign", False) structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) - if received_json["type"] == 'set' and received_json["command"] == 'mygrid': try: mygrid = received_json["parameter"] @@ -484,9 +458,7 @@ def process_daemon_commands(data): command_response("mygrid", False) structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) - if received_json["type"] == 'set' and received_json["command"] == 'start_tnc' and not static.TNCSTARTED: - try: mycall = str(received_json["parameter"][0]["mycall"]) mygrid = str(received_json["parameter"][0]["mygrid"]) @@ -512,7 +484,6 @@ def process_daemon_commands(data): tx_audio_level = str(received_json["parameter"][0]["tx_audio_level"]) respond_to_cq = str(received_json["parameter"][0]["respond_to_cq"]) - # print some debugging parameters for item in received_json["parameter"][0]: structlog.get_logger("structlog").debug("[DMN] TNC Startup Config : " + item, value=received_json["parameter"][0][item]) @@ -549,7 +520,6 @@ def process_daemon_commands(data): structlog.get_logger("structlog").warning("[SCK] command execution error", e=e, command=received_json) if received_json["type"] == 'get' and received_json["command"] == 'test_hamlib': - try: devicename = str(received_json["parameter"][0]["devicename"]) deviceport = str(received_json["parameter"][0]["deviceport"]) @@ -619,7 +589,6 @@ def send_daemon_state(): else: output["daemon_state"].append({"status": "stopped"}) - jsondata = json.dumps(output) return jsondata diff --git a/tnc/static.py b/tnc/static.py index 4bf08ad1..2922520c 100644 --- a/tnc/static.py +++ b/tnc/static.py @@ -15,7 +15,6 @@ DAEMONPORT = 3001 TNCSTARTED = False TNCPROCESS = 0 - # Operator Defaults MYCALLSIGN = b'AA0AA' MYCALLSIGN_CRC = b'A' @@ -39,7 +38,6 @@ SOCKET_TIMEOUT = 1 # seconds SERIAL_DEVICES = [] # --------------------------------- - PTT_STATE = False TRANSMITTING = False @@ -96,7 +94,6 @@ ARQ_TRANSMISSION_PERCENT = 0 ARQ_SPEED_LEVEL = 0 TOTAL_BYTES = 0 - #CHANNEL_STATE = 'RECEIVING_SIGNALLING' TNC_STATE = 'IDLE' ARQ_STATE = False