Files
mdif/sim/mdif_sim.py

88 lines
2.1 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import re
import socket
import sys
import time
from random import randrange
HOST = "127.0.0.1" # Localhost
PORT = int(sys.argv[1]) # Port to listen on
LOG2FILE = False if len(sys.argv) < 3 else bool(int(sys.argv[2]))
import logging
logger = logging.getLogger('mdif')
if LOG2FILE:
logging.basicConfig(filename=os.path.join(os.getcwd(), 'mdif_sim.log'), level=logging.INFO)
class MDIF:
def __init__(self):
self.delay = 1000
def getDelay(self):
return self.delay
def setDelay(self, delay):
self.delay = delay
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
def send(data: str):
if data:
logger.info(f'SENDING: "{data}"')
return conn.sendall(f'{data}\r'.encode())
else:
logger.info(f'SENDING: ""')
return conn.sendall(b'\r')
def receive():
data = conn.recv(1024)
if data:
# also removes terminator
received = data.decode('ascii').rstrip()
else:
received = ''
logger.info(f'RECEIVED: "{received}"')
return received
mdif = MDIF()
while True:
data = receive()
if not data: # Empty implies client disconnected
break # Close Server
try:
if data == 'RMT 1':
send('')
elif data == 'ECHO 0':
send('')
elif data == 'DT':
send('%d' % mdif.getDelay())
elif re.fullmatch(r'DT (\d+)', data):
new_delay = int(re.fullmatch(r'DT (\d+)', data).group(1))
mdif.setDelay(new_delay)
send('')
else:
send('?2') # Bad command
except Exception as e:
logger.exception('Simulation Broke')
send('?OV')