st-ten-1/src/main.py

250 lines
12 KiB
Python
Raw Normal View History

2022-06-01 16:37:19 +00:00
#!/usr/bin/env python3
2023-01-20 16:19:39 +00:00
import argparse
2022-06-01 16:37:19 +00:00
import faulthandler
import logging
import os
2023-02-17 20:19:30 +00:00
import platform
2022-06-01 16:37:19 +00:00
# import pdb
import signal
import sys
import traceback
2022-07-05 16:16:22 +00:00
import weakref
2022-06-01 16:37:19 +00:00
from datetime import datetime
from pathlib import Path
2023-02-17 20:19:30 +00:00
if platform.system() == "Windows":
sys.path.append(f"{os.getcwd()}\src\components")
2023-01-31 14:02:27 +00:00
from components.usb_586x import USB_586x
2022-07-04 10:36:51 +00:00
app = None
2022-06-01 16:37:19 +00:00
2023-01-20 16:19:39 +00:00
parser = argparse.ArgumentParser(prog='ST-TEN', description='Leak test system')
parser.add_argument('-s', '--system-id')
args,unspec = parser.parse_known_args()
2022-06-01 16:37:19 +00:00
2022-06-29 11:04:31 +00:00
def quit_app(signalnum=None, handler=None):
logging.info(f"quitting app. signal: {signalnum!r}, handler: {handler!r}")
2022-06-01 16:37:19 +00:00
global app
2022-07-04 10:36:51 +00:00
if app is not None:
app.quit()
2022-06-01 16:37:19 +00:00
quit()
# SETUP QUITTING ON CTRL+C
signal.signal(signal.SIGINT, quit_app)
# SETUP FAULTHANDLER
faulthandler.enable(file=sys.stderr, all_threads=True)
# SETUP LOGS
logs_dir = Path(".") / "data" / "logs"
os.makedirs(logs_dir, exist_ok=True)
logging.basicConfig(
format="{asctime}:{name}:{levelname}:{message}",
datefmt="%Y-%m-%dT%H-%M-%S%z",
style="{",
level="INFO",
handlers=[
logging.StreamHandler(stream=sys.stderr),
logging.FileHandler(
2022-07-04 10:36:51 +00:00
logs_dir / f"{datetime.now().isoformat().replace(':', ';')}.log",
2022-06-01 16:37:19 +00:00
mode="a",
encoding="utf-8",
delay=False,
2022-07-06 11:23:46 +00:00
**({"errors": "surrogateescape"} if sys.version_info.major >= 3 and sys.version_info.minor >= 10 else {}),
2022-06-01 16:37:19 +00:00
),
],
force=True,
2022-07-06 11:23:46 +00:00
**({"encoding": "utf-8"} if sys.version_info.major >= 3 and sys.version_info.minor >= 10 else {}),
**({"errors": "surrogateescape"} if sys.version_info.major >= 3 and sys.version_info.minor >= 10 else {}),
2022-06-01 16:37:19 +00:00
)
try:
# IMPORT PROJECT ONLY AFTER SETTING UP SIGNAL, FAULTHANDLER AND LOGGHING
from components import (ArchiveSynchronizer, Multicomp730424,
Os_Label_Printer, RemoteAPI,
TecnaMarpossProvasetT3, TecnaScrewdriver)
2022-06-01 16:37:19 +00:00
from lib.db import Users
from lib.helpers import ConfigReader
from PyQt5.QtCore import QObject, QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QMessageBox
2022-07-25 09:16:14 +00:00
from ui import About, Archive, Login, Main_Window, Test, Users_Management
2022-06-01 16:37:19 +00:00
if "--vision" in sys.argv:
from components import GalaxyCamera, NeoPixels, UVCCamera, Vision, VisionSaver
2022-06-01 16:37:19 +00:00
class Main(QObject):
do = pyqtSignal(dict)
@staticmethod
def _do(config):
return config["f"](*config.get("a", []), **config.get("k", {}))
def __init__(self, parent=None):
# print(f"MAIN {int(QThread.currentThreadId())}", flush=True)
super().__init__()
self.do.connect(self._do)
try:
# READ CONFIG
2023-01-20 16:19:39 +00:00
system_id = args.system_id if "system_id" in args else None
self.config = ConfigReader(system_id=system_id)
self.config["autotest_done"] = False
2022-06-01 16:37:19 +00:00
# INIT COMPONENT
self.components_specs = {
2022-08-24 11:22:16 +00:00
"archive_synchronizer": {"c": ArchiveSynchronizer},
2022-06-08 07:11:38 +00:00
"label_printer": {"c": Os_Label_Printer, "t": False},
2023-02-17 10:46:30 +00:00
"extra_label_printer": {"c": Os_Label_Printer, "t": False},
"multicomp": {"c": Multicomp730424, "k": {"paused": True}},
2022-06-21 12:10:52 +00:00
"remote_api": {"c": RemoteAPI, "k": {"main": self}},
2022-10-04 11:51:36 +00:00
"screwdriver": {"c": TecnaScrewdriver, "k": {"paused": True}},
2022-09-14 12:47:09 +00:00
"tecna_t3": {"c": TecnaMarpossProvasetT3, "k": {"paused": True}},
2023-01-31 14:02:27 +00:00
"digital_io":{"c":USB_586x,"k":{"paused":True}}
2022-06-01 16:37:19 +00:00
}
2023-01-06 14:42:52 +00:00
# VISION COMPONENT IS OPTIONAL AND DISABLED BY DEFAULT
if "--vision" in sys.argv:
# merge dicts
self.components_specs = {**self.components_specs,
**{
"galaxy_camera": {"c": GalaxyCamera, "k": {"paused": True}},
"neo_pixels": {"c": NeoPixels, "t": False},
"uvc_camera": {"c": UVCCamera, "k": {"paused": True}},
"vision_saver": {"c": VisionSaver, "t": False},
"vision": {"c": Vision, "k": {"paused": True}}
}
}
2022-08-23 14:00:04 +00:00
for component_name in list(self.components_specs):
if self.config.get("hardware_config", {}).get(component_name, None) != "present":
2022-08-24 11:22:16 +00:00
self.components_specs.pop(component_name, None)
elif component_name not in self.components_specs:
raise AssertionError(f"{component_name!r} is not a valid component name")
2022-06-01 16:37:19 +00:00
self.components = {}
self.threads = {}
for component_name, spec in self.components_specs.items():
self.components[component_name] = spec["c"](*spec.get("a", []), config=self.config,
name=component_name, **spec.get("k", {}))
2022-06-08 07:11:38 +00:00
if spec.get("t", True):
2022-06-01 16:37:19 +00:00
self.threads[component_name] = QThread()
self.threads[component_name].setTerminationEnabled(True)
self.components[component_name].moveToThread(self.threads[component_name])
for component_name, thread in self.threads.items():
component = self.components[component_name]
thread.started.connect(component.start)
thread.start()
2022-07-20 17:29:11 +00:00
if "--debugger-workaround" in sys.argv:
QApplication.processEvents()
QThread.msleep(1000)
QApplication.processEvents()
2022-10-05 13:27:05 +00:00
if component_name == "vision":
component.wait_completion(timeout=60)
else:
component.wait_completion()
2022-06-01 16:37:19 +00:00
except Exception as e:
logging.exception(traceback.format_exc())
QMessageBox.critical(None, "Errore", f"Errore di avvio del programma di collaudo:\n\n{e}")
2022-06-01 16:37:19 +00:00
quit()
2022-06-22 15:18:29 +00:00
# connect camera frames to vision
2022-10-11 13:30:53 +00:00
if "vision" in self.components and "uvc_camera" in self.components:
self.components["vision"].set_sources({"uvc_camera": self.components["uvc_camera"].out})
elif "vision" in self.components and "galaxy_camera" in self.components:
2022-06-29 11:04:31 +00:00
self.components["vision"].set_sources({"galaxy_camera": self.components["galaxy_camera"].out})
2022-10-04 11:51:36 +00:00
# connect tecna to screwdriver
if "screwdriver" in self.components and "tecna_t3" in self.components:
self.components["tecna_t3"].set_requestors({"screwdriver": self.components["screwdriver"].request})
self.components["screwdriver"].set_sources({"tecna_t3": self.components["tecna_t3"].out})
2022-06-01 16:37:19 +00:00
# GUI INIT
2022-06-29 11:04:31 +00:00
if "--no-gui" not in sys.argv:
# self.main_window = Main_Window(self.bench)
self.main_window = Main_Window()
# CONNECT MAIN WINDOW ACTIONS
2022-09-06 13:15:01 +00:00
self.main_window.logout_a.triggered.connect(lambda checked, self=weakref.ref(self): self().logout())
self.main_window.archive_a.triggered.connect(
lambda checked, self=weakref.ref(self): self().main_window.open_dialog(
Archive(hide_cloud_image="vision_saver" not in self().components)))
2022-06-29 11:04:31 +00:00
if "--archive" in sys.argv:
self.main_window.archive_a.trigger()
self.main_window.about_a.triggered.connect(
lambda checked, self=weakref.ref(self): self().main_window.open_dialog(About()))
2022-06-29 11:04:31 +00:00
if "--about" in sys.argv:
self.main_window.about_a.trigger()
self.main_window.admin_m.menuAction().setVisible(
False) # admin menu should not be visible before an admin logs in
2022-06-29 11:04:31 +00:00
self.main_window.quit_a.triggered.connect(quit_app)
self.main_window.users_management_a.triggered.connect(
lambda checked, self=weakref.ref(self): self().main_window.open_dialog(Users_Management()))
2022-06-29 11:04:31 +00:00
if "--users-management" in sys.argv:
self.main_window.users_management_a.trigger()
2022-07-25 09:16:14 +00:00
# self.main_window.recipes_management_a.triggered.connect(lambda checked, self=weakref.ref(self): self().main_window.open_dialog(Recipes_Management()))
# if "--recipes-management" in sys.argv:
# self.main_window.recipes_management_a.trigger()
# self.main_window.steps_management_a.triggered.connect(lambda checked, self=weakref.ref(self): self().main_window.open_dialog(Steps_Management()))
# if "--steps-management" in sys.argv:
# self.main_window.steps_management_a.trigger()
if "tecna_t3" in self.components and (
"--enable-saving-tecna-recipes" in sys.argv or self.config.get("tecna_t3", {}).get("saver",
None) == "present"):
2022-10-18 14:41:53 +00:00
self.main_window.save_tecna_recipes_a.triggered.connect(self.components["tecna_t3"].store_recipes)
self.main_window.save_tecna_recipes_a.setVisible(True)
if "--save-tecna-recipes" in sys.argv:
self.main_window.save_tecna_recipes_a.trigger()
else:
self.main_window.save_tecna_recipes_a.setVisible(False)
2022-06-29 11:04:31 +00:00
# OPEN LOGIN TAB
self.open_login()
# SHOW MAIN WINDOW
if "--panel" in sys.argv:
self.main_window.show()
elif "--maximized" in sys.argv:
self.main_window.showMaximized()
elif "--full-screen" in sys.argv:
self.main_window.showFullScreen()
else:
self.main_window.showFullScreen()
2022-06-01 16:37:19 +00:00
def open_login(self):
tab = Login()
2022-07-26 14:09:01 +00:00
tab.successful_login.connect(self.logged_in)
2022-06-01 16:37:19 +00:00
self.main_window.open_tab(tab)
2022-07-26 14:09:01 +00:00
def logged_in(self):
2022-06-01 16:37:19 +00:00
session = Users.get_session()
if session is not None:
if session.is_admin:
self.main_window.admin_m.menuAction().setVisible(True)
else:
self.main_window.admin_m.menuAction().setVisible(False)
2022-07-05 16:16:22 +00:00
# open test
2022-09-20 15:42:59 +00:00
self.main_window.open_tab(Test(self.config, self.components))
2022-09-06 13:15:01 +00:00
else:
self.main_window.admin_m.menuAction().setVisible(False)
def logout(self):
if type(self.main_window.centralWidget) is Test:
self.main_window.centralWidget.change_recipe()
Users.logout()
self.main_window.admin_m.menuAction().setVisible(False)
self.open_login()
2022-06-29 11:04:31 +00:00
2022-06-01 16:37:19 +00:00
if __name__ == "__main__":
app = QApplication(sys.argv)
main = Main()
2022-06-29 11:04:31 +00:00
if "--no-gui" not in sys.argv:
app.exec()
if "--interact" in sys.argv:
import code
import readline
2022-06-29 11:04:31 +00:00
variables = globals().copy()
variables.update(locals())
shell = code.InteractiveConsole(variables)
shell.interact()
2022-06-01 16:37:19 +00:00
except Exception:
logging.exception(traceback.format_exc())
# extype, value, tb = sys.exc_info()
# pdb.post_mortem(tb)