Skip to content

Commit

Permalink
Routine updates.
Browse files Browse the repository at this point in the history
Configuration system implemented.
Tests required.
Docs update required.
  • Loading branch information
ATATC committed Dec 14, 2023
1 parent 14788c6 commit fc9205c
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 44 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ python -m leads_vec
### Remote Server (Remote)

```shell
python -m leads_vec remote
python -m leads_vec --remote
```

## Periodic Report
Expand Down
2 changes: 1 addition & 1 deletion leads/comm/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from leads.comm.prototype import Callback


def create_client(port: int = 16400, callback: Callback = Callback()) -> Client:
def create_client(port: int = 16900, callback: Callback = Callback()) -> Client:
return Client(port, callback)


Expand Down
2 changes: 1 addition & 1 deletion leads/comm/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from leads.comm.server.server import Server


def create_server(port: int = 16400, callback: Callback = Callback()) -> Server:
def create_server(port: int = 16900, callback: Callback = Callback()) -> Server:
return Server(port, callback)


Expand Down
27 changes: 22 additions & 5 deletions leads_vec/__main__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,32 @@
from importlib.util import find_spec as _find_spec
from sys import argv as _argv, exit as _exit

from leads_vec.config import load_config as _load_config, DEFAULT_CONFIG as _DEFAULT_CONFIG


def get_arg(args: list[str], name: str) -> str | None:
for arg in args:
if arg.startswith(name + "="):
return arg[len(name) + 1:]


if __name__ == '__main__':
if not _find_spec("dearpygui"):
raise ImportError("Please install `dearpygui` to run this module\n>>> pip install dearpygui")
if not _find_spec("keyboard"):
raise ImportError("Please install `keyboard` to run this module\n>>> pip install keyboard")
try:
from leads_emulation import SRWRandom as Controller
from leads_emulation import SRWRandom as _Controller
except ImportError:
raise EnvironmentError("At least one adapter has to be installed")
if "remote" in _argv:
raise ImportError("At least one adapter has to be installed")
cfg_arg = get_arg(_argv, "config")
config = _load_config(cfg_arg) if cfg_arg else _DEFAULT_CONFIG

if "--remote" in _argv:
from leads_vec.remote import remote as _main

_exit(_main())
_exit(_main(config))
else:
from leads_vec.cli import main as _main

_exit(_main(Controller("main")))
_exit(_main(_Controller("main"), config))
2 changes: 1 addition & 1 deletion leads_vec/__version__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__: str = "9458732e"
__version__: str = "14788c69"
22 changes: 8 additions & 14 deletions leads_vec/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,16 @@
from leads.comm import *
from leads_dashboard import *
from leads_vec.__version__ import __version__
from leads_vec.config import Config


class CustomRuntimeData(RuntimeData):
m1_mode: int = 0
m3_mode: int = 0


def main(main_controller: Controller,
srw_mode: bool = True,
analysis_rate: float = .01,
update_rate: float = .25,
communication_server_address: str = "") -> int:
context = Leads(srw_mode=srw_mode)
def main(main_controller: Controller, config: Config) -> int:
context = Leads(srw_mode=config.srw_mode)
rd = CustomRuntimeData()

class CustomCallback(Callback):
Expand All @@ -30,10 +27,7 @@ def on_fail(self, service: Service, error: Exception) -> None:
def on_receive(self, service: Service, msg: bytes) -> None:
print(msg)

if communication_server_address != "":
rd.comm = start_client(communication_server_address,
create_client(callback=CustomCallback()),
True)
rd.comm = start_client(config.comm_addr, create_client(config.comm_port, CustomCallback()), True)

def switch_m1_mode():
rd.m1_mode = (rd.m1_mode + 1) % 2
Expand Down Expand Up @@ -124,9 +118,9 @@ def on_update(self, e: UpdateEvent) -> None:
f"VeC {__version__.upper()}\n\n"
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
f"{duration // 60} MIN {duration % 60} SEC\n\n"
f"{'SRW MODE' if srw_mode else 'DRW MODE'}\n"
f"ANALYSIS RATE: {int(1 / analysis_rate)} TPS\n"
f"UPDATE RATE: {int(1 / update_rate)} TPS")
f"{'SRW MODE' if config.srw_mode else 'DRW MODE'}\n"
f"ANALYSIS RATE: {int(1 / config.analysis_rate)} TPS\n"
f"UPDATE RATE: {int(1 / config.update_rate)} TPS")
dpg.set_item_label("m2", f"{int(context.data().front_wheel_speed)}")
if rd.m3_mode == 0:
dpg.bind_item_font("m3", H1)
Expand All @@ -152,6 +146,6 @@ def post_suspend(self, e: SuspensionEvent) -> None:
dpg.set_value(e.system.lower() + "_status", e.system + " READY")

context.set_event_listener(CustomListener())
start(render, context, main_controller, analysis_rate, update_rate, rd)
start(render, context, main_controller, config.analysis_rate, config.update_rate, rd)
rd.comm_kill()
return 0
33 changes: 24 additions & 9 deletions leads_vec/config.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,37 @@
from json import load as _load, loads as _loads
from typing import TextIO as _TextIO, Any as _Any
from json import load as _load
from typing import TextIO as _TextIO, Any as _Any, Self as _Self


class Config(object):
def __init__(self, base: dict[str, _Any]) -> None:
self._d: dict[str, _Any] = base
self.srw_mode: bool = True
self.analysis_rate: float = .01
self.update_rate: float = .25
self.comm_addr: str = "127.0.0.1"
self.comm_port: int = 16900
self.data_dir: str = "./data"

def __getitem__(self, name: str) -> _Any | None:
return self._d.get(name, None)
return self.get(name)

def __getattr__(self, name: str) -> _Any | None:
return self[name]
return self.get(name)

def require(self, name: str) -> _Any:
if r := self[name] is None:
raise KeyError(name)
return r
def get(self, name: str, default: _Any | None = None) -> _Any:
if r := self._d.get(name):
return r
return default

def load(self) -> _Self:
for name in dir(self):
if not name.startswith("_") and (v := self.get(name)):
self.__setattr__(name, v)
return self


DEFAULT_CONFIG = Config({})


def load_config(file: str | _TextIO) -> Config:
return Config(_loads(file) if isinstance(file, str) else _load(file))
return Config(_load(open(file, "r")) if isinstance(file, str) else _load(file)).load()
17 changes: 7 additions & 10 deletions leads_vec/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from leads.comm import *
from leads.utils import *
from leads_dashboard import *
from leads_vec.config import Config


def render():
Expand All @@ -23,14 +24,14 @@ def integrate_speed2displacement(x: DataPersistence, y: DataPersistence) -> floa
dx=.001)


def remote(data_dir: str = "./data") -> int:
if not exists(data_dir):
mkdir(data_dir)
def remote(config: Config) -> int:
if not exists(config.data_dir):
mkdir(config.data_dir)

class CustomCallback(Callback):
speed_seq: deque = deque(maxlen=512)
speed_record: DataPersistence = DataPersistence(data_dir + "/speed.csv", max_size=256)
time_stamp_record: DataPersistence = DataPersistence(data_dir + "/time_stamp.csv", max_size=256)
speed_record: DataPersistence = DataPersistence(config.data_dir + "/speed.csv", max_size=256)
time_stamp_record: DataPersistence = DataPersistence(config.data_dir + "/time_stamp.csv", max_size=256)

def on_initialize(self, service: Service) -> None:
print("Server started")
Expand All @@ -52,9 +53,5 @@ def on_receive(self, service: Service, msg: bytes) -> None:
def on_disconnect(self, service: Service) -> None:
self.speed_record.close()

start_comm_server(render, create_server(callback=CustomCallback()))
start_comm_server(render, create_server(config.comm_port, CustomCallback()))
return 0


if __name__ == '__main__':
remote()
3 changes: 2 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from leads_emulation import SRWSin
from leads_vec.cli import main
from leads_vec.config import DEFAULT_CONFIG

if __name__ == '__main__':
main(SRWSin("main", 20, 60, acceleration=.008), communication_server_address="127.0.0.1")
main(SRWSin("main", 20, 60, acceleration=.008), DEFAULT_CONFIG)
3 changes: 2 additions & 1 deletion remote.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from leads_vec.config import DEFAULT_CONFIG
from leads_vec.remote import remote

if __name__ == '__main__':
remote()
remote(DEFAULT_CONFIG)

0 comments on commit fc9205c

Please sign in to comment.