93 lines
2.5 KiB
Python
93 lines
2.5 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import logging
|
|
import os
|
|
import re
|
|
import socket
|
|
import sys
|
|
import time
|
|
|
|
from threading import Thread
|
|
|
|
HOST = "127.0.0.1" # Localhost
|
|
READ_PORT = int(sys.argv[1]) # Port to listen on
|
|
WRITE_PORT = int(sys.argv[2]) # Port to listen on
|
|
|
|
LOG2FILE = True # TODO False if len(sys.argv) < 3 else bool(int(sys.argv[3]))
|
|
|
|
logger = logging.getLogger('shutter')
|
|
|
|
if LOG2FILE:
|
|
logging.basicConfig(filename=os.path.join(os.getcwd(), 'shutter_sim.log'), level=logging.INFO)
|
|
|
|
logger.info(f'Read Requests on {HOST}:{READ_PORT}, Write Requests on {HOST}:{WRITE_PORT}')
|
|
|
|
def receive(conn, sock_name):
|
|
# received = conn.recv(1024, socket.MSG_DONTWAIT)
|
|
received = conn.recv(1024)
|
|
logger.info(f'RECEIVED on {sock_name}: "{received}"')
|
|
logger.info('Decimal on %s: %s' % (sock_name, ' '.join(map(str, [received[i+2] for i in range(len(received)-2)]))))
|
|
return received
|
|
|
|
def send(conn, data: str):
|
|
logger.info(f'SENDING: "{data}"')
|
|
return conn.sendall(data)
|
|
|
|
def read_requests():
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
|
|
s.bind((HOST, READ_PORT))
|
|
s.listen()
|
|
conn, _ = s.accept()
|
|
|
|
with conn:
|
|
while True:
|
|
data = receive(conn, "read")
|
|
|
|
# if not data: # Empty implies client disconnected
|
|
# break # Close Server
|
|
|
|
try:
|
|
|
|
if data == b'':
|
|
send(conn, b'')
|
|
|
|
elif len(data) == 14 and data[0] == 83 and data[1] == 53:
|
|
# Trying to fetch data
|
|
org = data[8]
|
|
db = data[9]
|
|
s7addr = data[10] * 256 + data[11]
|
|
s7len = data[12] * 256 + data[13]
|
|
logger.info(f'Fetch: db: {db}, address: {s7addr}, total: {s7len}')
|
|
|
|
send(conn, b'0' * s7len)
|
|
|
|
except Exception as e:
|
|
logger.exception('Simulation Broke')
|
|
# send('?OV')
|
|
|
|
def write_requests():
|
|
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
|
|
s.bind((HOST, WRITE_PORT))
|
|
s.listen()
|
|
conn, _ = s.accept()
|
|
|
|
with conn:
|
|
while True:
|
|
data = receive(conn, "write")
|
|
|
|
# if not data: # Empty implies client disconnected
|
|
# break # Close Server
|
|
|
|
|
|
read_thread = Thread(target=read_requests)
|
|
write_thread = Thread(target=write_requests)
|
|
|
|
read_thread.run()
|
|
write_thread.run()
|
|
|
|
while True:
|
|
pass
|