Skip to content

Commit

Permalink
Add ptd logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Lilit1122 committed Feb 1, 2021
1 parent 9152879 commit 39ec56e
Showing 1 changed file with 38 additions and 29 deletions.
67 changes: 38 additions & 29 deletions ptd_client_server/lib/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from decimal import Decimal
from enum import Enum
from ipaddress import ip_address
from typing import Any, Callable, Optional, Dict, Tuple, List, Set
from typing import Any, Callable, Optional, Dict, Tuple, List, Set, TextIO
from pathlib import Path
import argparse
import atexit
Expand Down Expand Up @@ -215,14 +215,16 @@ def _check(self, filename: str) -> None:


class Ptd:
def __init__(self, command: List[str], port: int) -> None:
self._process: Optional[subprocess.Popen[bytes]] = None
def __init__(self, command: List[str], port: int, logfile_path: str) -> None:
self._process: Optional[subprocess.Popen[Any]] = None
self._socket: Optional[socket.socket] = None
self._proto: Optional[common.Proto] = None
self._command = command
self._port = port
self._init_Amps: Optional[str] = None
self._init_Volts: Optional[str] = None
self._log_file_path: str = logfile_path
self._log_file_fd: Optional[TextIO] = None
atexit.register(self._force_terminate)

def start(self) -> None:
Expand All @@ -238,21 +240,34 @@ def _start(self) -> None:
if tcp_port_is_occupied(self._port):
raise RuntimeError(f"The PTDaemon port {self._port} is already occupied")
logging.info(f"Running PTDaemon: {self._command}")

if sys.platform == "win32":
# creationflags=subprocess.CREATE_NEW_PROCESS_GROUP:
# We do not want to pass ^C from the current console to the
# PTDaemon. Instead, we terminate it explicitly in self.terminate().
self._process = subprocess.Popen(
self._command,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
bufsize=1,
universal_newlines=True,
stdout=open(self._log_file_path, "w"),
stderr=subprocess.STDOUT,
)
else:
self._process = subprocess.Popen(self._command)
self._process = (
subprocess.Popen(
self._command,
bufsize=1,
universal_newlines=True,
stdout=open(self._log_file_path, "w"),
stderr=subprocess.STDOUT,
),
)

retries = 100
s = None
while s is None and retries > 0:
if self._process.poll() is not None:
if self._process is not None and self._process.poll() is not None:
raise RuntimeError("PTDaemon unexpectedly terminated")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
Expand Down Expand Up @@ -305,6 +320,7 @@ def terminate(self) -> None:
self._process.wait()
self._process = None


def _force_terminate(self) -> None:
if self._process is not None:
logging.info("Force stopping ptd...")
Expand Down Expand Up @@ -359,7 +375,6 @@ class Server:
def __init__(self, config: ServerConfig) -> None:
self.session: Optional[Session] = None
self._config = config
self._ptd = Ptd(config.ptd_command, config.ptd_port)
self._stop = False

def handle_connection(self, p: common.Proto) -> None:
Expand Down Expand Up @@ -481,10 +496,7 @@ def _drop_session(self) -> None:
self.session = None

def close(self) -> None:
try:
self._drop_session()
finally:
self._ptd.terminate()
self._drop_session()


class SessionState(Enum):
Expand All @@ -506,7 +518,10 @@ def __init__(self, server: Server, label: str) -> None:
self._server: Server = server
self._go_command_time: Optional[float] = None
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
self._id: str = timestamp + "_" + label if label != "" else timestamp
id = timestamp + "_" + label if label != "" else timestamp
log_path = os.path.join(server._config.out_dir, id)
self._id: str = id
self._ptd = Ptd(server._config.ptd_command, server._config.ptd_port, log_path)

# State
self._state = SessionState.INITIAL
Expand All @@ -520,27 +535,27 @@ def start(self, mode: Mode) -> bool:
return True

if mode == Mode.RANGING and self._state == SessionState.INITIAL:
self._server._ptd.start()
self._server._ptd.cmd("SR,V,Auto")
self._server._ptd.cmd("SR,A,Auto")
self._ptd.start()
self._ptd.cmd("SR,V,Auto")
self._ptd.cmd("SR,A,Auto")
with common.sig:
time.sleep(ANALYZER_SLEEP_SECONDS)
logging.info("Starting ranging mode")
self._server._ptd.cmd(f"Go,1000,0,{self._id}_ranging")
self._ptd.cmd(f"Go,1000,0,{self._id}_ranging")
self._go_command_time = time.monotonic()

self._state = SessionState.RANGING

return True

if mode == Mode.TESTING and self._state == SessionState.RANGING_DONE:
self._server._ptd.start()
self._server._ptd.cmd(f"SR,V,{self._maxVolts}")
self._server._ptd.cmd(f"SR,A,{self._maxAmps}")
self._ptd.start()
self._ptd.cmd(f"SR,V,{self._maxVolts}")
self._ptd.cmd(f"SR,A,{self._maxAmps}")
with common.sig:
time.sleep(ANALYZER_SLEEP_SECONDS)
logging.info("Starting testing mode")
self._server._ptd.cmd(f"Go,1000,0,{self._id}_testing")
self._ptd.cmd(f"Go,1000,0,{self._id}_testing")

self._state = SessionState.TESTING

Expand All @@ -562,7 +577,7 @@ def stop(self, mode: Mode) -> bool:

if mode == Mode.RANGING and self._state == SessionState.RANGING:
self._state = SessionState.RANGING_DONE
self._server._ptd.stop()
self._ptd.stop()
assert self._go_command_time is not None
test_duration = time.monotonic() - self._go_command_time
dirname = os.path.join(self._server._config.out_dir, self._id + "_ranging")
Expand All @@ -587,7 +602,7 @@ def stop(self, mode: Mode) -> bool:

if mode == Mode.TESTING and self._state == SessionState.TESTING:
self._state = SessionState.TESTING_DONE
self._server._ptd.stop()
self._ptd.stop()
dirname = os.path.join(self._server._config.out_dir, self._id + "_testing")
os.mkdir(dirname)
with open(os.path.join(dirname, "spl.txt"), "w") as f:
Expand All @@ -611,14 +626,8 @@ def upload(self, mode: Mode, fname: str) -> bool:
return False

def drop(self) -> None:
try:
if (
self._state == SessionState.RANGING
or self._state == SessionState.TESTING
):
self._server._ptd.stop()
finally:
self._state = SessionState.DONE
self._ptd.terminate()
self._state = SessionState.DONE

def _extract(self, fname: str, dirname: str) -> bool:
try:
Expand Down

0 comments on commit 39ec56e

Please sign in to comment.