5 changed files with 186 additions and 13 deletions
@ -0,0 +1,58 @@ |
|||
from pathlib import Path |
|||
from typing import Dict |
|||
from typing import Optional |
|||
|
|||
from dependency_injector import containers |
|||
from dependency_injector import providers |
|||
from flask_api import FlaskAPI |
|||
from serial import Serial |
|||
|
|||
DEFAULTS_DIR = Path(__file__).parent / "defaults" |
|||
CONFIG_FILE = DEFAULTS_DIR / "config.yml" |
|||
|
|||
|
|||
class Container(containers.DeclarativeContainer): |
|||
config = providers.Configuration("config") |
|||
|
|||
serial = providers.Factory( |
|||
Serial, |
|||
port=config.device_id.required(), |
|||
baudrate=config.baudrate.required(), |
|||
) |
|||
|
|||
|
|||
__container: Optional[Container] = None |
|||
|
|||
|
|||
def initialize_container( |
|||
config: Optional[Dict] = None, |
|||
config_file: Optional[Path] = None, |
|||
) -> Container: |
|||
global __container |
|||
if __container is not None: |
|||
raise RuntimeError("Container already initialized") |
|||
|
|||
__container = Container() |
|||
__container.config.from_yaml(CONFIG_FILE) |
|||
|
|||
if config is not None: |
|||
__container.config.from_dict(config) |
|||
|
|||
if config_file is not None: |
|||
__container.config.from_yaml(config_file) |
|||
|
|||
return __container |
|||
|
|||
|
|||
def init_app(app: FlaskAPI): |
|||
initialize_container( |
|||
config=app.config.get("DI_CONFIG"), |
|||
config_file=app.config.get("DI_CONFIG_FILE"), |
|||
) |
|||
|
|||
|
|||
def get_container() -> Container: |
|||
global __container |
|||
if __container is None: |
|||
raise RuntimeError("Container not initialized") |
|||
return __container |
|||
@ -0,0 +1,3 @@ |
|||
device_id: /dev/tty.usbmodem2067368F32521 |
|||
baudrate: 115200 |
|||
header_size: 4 |
|||
@ -1,3 +1,4 @@ |
|||
dependency-injector[yaml]>=4.34.0,<5 |
|||
flask-api>=3.0.post1,<4 |
|||
pre-commit |
|||
pyserial>=3.5,<4 |
|||
|
|||
Loading…
Reference in new issue