Compare commits
4 Commits
Author | SHA1 | Date | |
---|---|---|---|
091c87af7e | |||
e78b7b5b14 | |||
d1764cb178 | |||
f239ede75d |
9
LICENSE
Normal file
9
LICENSE
Normal file
@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) [2023] [Темур]
|
||||
|
||||
Данное разрешение предоставляется бесплатно, любому лицу, получившему копию данного программного обеспечения и связанных с ним файлов документации (программное обеспечение), без ограничений, включая неограниченное право на использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование и/или продажу копий программного обеспечения, а также лицам, которым предоставляется данное программное обеспечение, при соблюдении следующих условий:
|
||||
|
||||
Указанное выше уведомление об авторском праве и данное разрешение должны быть включены во все копии или значительные части программного обеспечения.
|
||||
|
||||
ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ "КАК ЕСТЬ", БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМ ПРОДАЖИ, ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОГО НАЗНАЧЕНИЯ И НЕНАРУШЕНИЯ. НИ В КОЕМ СЛУЧАЕ АВТОРЫ ИЛИ ДЕТИ АВТОРОВ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ЗА КАКИЕ-ЛИБО ПРЕТЕНЗИИ, УБЫТКИ ИЛИ ДРУГИЕ ОБЯЗАТЕЛЬСТВА, БУДЬ-ТО В РЕЗУЛЬТАТЕ ДЕЙСТВИЙ ДОГОВОРА, ДЕЛИКТА ИЛИ ИНЫХ ДЕЙСТВИЙ, В РЕЗУЛЬТАТЕ ИЛИ В СВЯЗИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ИЛИ ДРУГИМИ ДЕЛОВЫМИ ОТНОШЕНИЯМИ В ПРОГРАММНОМ ОБЕСПЕЧЕНИИ.
|
54
README.md
54
README.md
@ -1,2 +1,56 @@
|
||||
# advanced-python-homework-2023
|
||||
## Установка зависимостей для разработки
|
||||
|
||||
Для разработки рекомендуется использовать виртуальное окружение. Для его создания и активации выполните следующие команды:
|
||||
|
||||
```bash
|
||||
# Создание виртуального окружения (в директории venv)
|
||||
python -m virtualenv venv
|
||||
|
||||
# Активация виртуального окружения в Linux/MacOS
|
||||
source venv/bin/activate
|
||||
|
||||
# Активация виртуального окружения в Windows
|
||||
venv\Scripts\activate
|
||||
|
||||
После активации виртуального окружения установите зависимости разработки:
|
||||
# Для проектов с использованием poetry
|
||||
poetry install
|
||||
|
||||
# Для проектов с использованием pip
|
||||
pip install -r requirements-dev.txt
|
||||
Теперь в вашем виртуальном окружении будут установлены Sphinx, Pylint и MyPy, которые рекомендуется использовать для разработки проекта.
|
||||
|
||||
|
||||
|
||||
## Генерация документации
|
||||
|
||||
#Документация создана с использованием Sphinx. Для ее перегенерации выполните следующие шаги:
|
||||
|
||||
cd advanced-python-homework-2023
|
||||
mkdir doc
|
||||
cd doc
|
||||
sphinx-quickstart
|
||||
cd ..
|
||||
sphinx-apidoc -o doc .
|
||||
cd doc
|
||||
rm modules.rst
|
||||
rm setup.rst
|
||||
|
||||
#Отредактируйте файл docs/conf.py и добавьте следующий код:
|
||||
|
||||
import os
|
||||
import sys
|
||||
sys.path.insert(0, os.path.abspath('../'))
|
||||
|
||||
extensions = [
|
||||
'sphinx.ext.autodoc',
|
||||
'sphinx.ext.napoleon', # Для поддержки Google-style docstrings
|
||||
]
|
||||
|
||||
|
||||
#Выполните команду для генерации документации:
|
||||
|
||||
cd ..
|
||||
make html
|
||||
#Open file:///home/timur/Gitea/advanced-python-homework-2023/doc/build/html/search.html THAT`s ALL FOR TODAY)
|
||||
|
@ -0,0 +1,16 @@
|
||||
"""Controls Package
|
||||
|
||||
This package implements the control logic for a SCADA (Supervisory Control and Data Acquisition) system.
|
||||
|
||||
SCADA systems are used to monitor and control industrial processes. They provide the following capabilities:
|
||||
|
||||
- Real-time Data Acquisition: Collect data from sensors and devices in real-time.
|
||||
- Process Monitoring: Monitor and display the status of industrial processes.
|
||||
- Remote Control: Allow remote operators to control industrial processes.
|
||||
- Alarming: Raise alarms in case of abnormal conditions.
|
||||
- Historical Data Logging: Record and store historical data for analysis.
|
||||
- Human-Machine Interface (HMI): Provide a graphical interface for operators.
|
||||
|
||||
This package is designed to encapsulate the control logic required for a SCADA system, providing a modular
|
||||
and maintainable structure for implementing the various functionalities.
|
||||
"""
|
@ -1,82 +0,0 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Collection, Any
|
||||
from abc import abstractmethod
|
||||
|
||||
class DeviceLifecycleState:
|
||||
pass # TODO(Homework #3)
|
||||
|
||||
|
||||
class DevaceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NonReadableTrait(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NonWritableTrait(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class TraitDescriptor:
|
||||
name: str
|
||||
info: Optional[str] = None
|
||||
readable: bool = True
|
||||
writable: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ActionDescriptor:
|
||||
name: str
|
||||
arguments: dict[str, type]
|
||||
info: Optional[str] = None
|
||||
|
||||
|
||||
class Device:
|
||||
# TODO(Homework #3)
|
||||
_state = DeviceLifecycleState.INIT
|
||||
|
||||
@property
|
||||
def state(self) -> DeviceLifecycleState:
|
||||
return self._state
|
||||
|
||||
def close(self):
|
||||
self._state = DeviceLifecycleState.CLOSE
|
||||
|
||||
def trait_descriptors(self) -> Collection[TraitDescriptor]:
|
||||
pass
|
||||
|
||||
def action_descriptors(self) -> Collection[ActionDescriptor]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def __getitem__(self, trait_name: str) -> Optional[Any]:
|
||||
"""Return logical state of trait `trait_name`."""
|
||||
pass
|
||||
|
||||
|
||||
class SynchronyDevice(Device):
|
||||
|
||||
def open(self):
|
||||
self._state = DeviceLifecycleState.OPEN
|
||||
|
||||
@abstractmethod
|
||||
def execute(self, action_name: str, *args, **kwargs):
|
||||
"""Execute action `action_name`, using `args` and `kwargs` as action argument."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def read(self, trait_name: str) -> Any:
|
||||
"""Read physical state of trait `trait_name` from device."""
|
||||
raise NonReadableTrait
|
||||
|
||||
@abstractmethod
|
||||
def write(self, trait_name: str, value: Any) -> bool:
|
||||
"""Pass `value` to trait `trait_name` of device."""
|
||||
raise NonWritableTrait
|
||||
|
||||
@abstractmethod
|
||||
def invalidate(self, trait_name: str):
|
||||
"""Invalidate logical state of trait `trait_name`"""
|
||||
pass
|
2
controls/my_module.py
Normal file
2
controls/my_module.py
Normal file
@ -0,0 +1,2 @@
|
||||
def hello_world():
|
||||
return "Hello, World!"
|
20
doc/Makefile
Normal file
20
doc/Makefile
Normal file
@ -0,0 +1,20 @@
|
||||
# Minimal makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line, and also
|
||||
# from the environment for the first two.
|
||||
SPHINXOPTS ?=
|
||||
SPHINXBUILD ?= sphinx-build
|
||||
SOURCEDIR = source
|
||||
BUILDDIR = build
|
||||
|
||||
# Put it first so that "make" without argument is like "make help".
|
||||
help:
|
||||
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
||||
|
||||
.PHONY: help Makefile
|
||||
|
||||
# Catch-all target: route all unknown targets to Sphinx using the new
|
||||
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
|
||||
%: Makefile
|
||||
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
21
doc/controls.rst
Normal file
21
doc/controls.rst
Normal file
@ -0,0 +1,21 @@
|
||||
controls package
|
||||
================
|
||||
|
||||
Submodules
|
||||
----------
|
||||
|
||||
controls.my\_module module
|
||||
--------------------------
|
||||
|
||||
.. automodule:: controls.my_module
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
|
||||
Module contents
|
||||
---------------
|
||||
|
||||
.. automodule:: controls
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
35
doc/make.bat
Normal file
35
doc/make.bat
Normal file
@ -0,0 +1,35 @@
|
||||
@ECHO OFF
|
||||
|
||||
pushd %~dp0
|
||||
|
||||
REM Command file for Sphinx documentation
|
||||
|
||||
if "%SPHINXBUILD%" == "" (
|
||||
set SPHINXBUILD=sphinx-build
|
||||
)
|
||||
set SOURCEDIR=source
|
||||
set BUILDDIR=build
|
||||
|
||||
%SPHINXBUILD% >NUL 2>NUL
|
||||
if errorlevel 9009 (
|
||||
echo.
|
||||
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
|
||||
echo.installed, then set the SPHINXBUILD environment variable to point
|
||||
echo.to the full path of the 'sphinx-build' executable. Alternatively you
|
||||
echo.may add the Sphinx directory to PATH.
|
||||
echo.
|
||||
echo.If you don't have Sphinx installed, grab it from
|
||||
echo.https://www.sphinx-doc.org/
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if "%1" == "" goto help
|
||||
|
||||
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
|
||||
goto end
|
||||
|
||||
:help
|
||||
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
|
||||
|
||||
:end
|
||||
popd
|
35
doc/source/conf.py
Normal file
35
doc/source/conf.py
Normal file
@ -0,0 +1,35 @@
|
||||
# Configuration file for the Sphinx documentation builder.
|
||||
#
|
||||
# For the full list of built-in configuration values, see the documentation:
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html
|
||||
|
||||
# -- Project information -----------------------------------------------------
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
|
||||
|
||||
project = 'Sphinx_project'
|
||||
copyright = '2023, Temur'
|
||||
author = 'Temur'
|
||||
|
||||
# -- General configuration ---------------------------------------------------
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
|
||||
|
||||
import os
|
||||
import sys
|
||||
sys.path.insert(0, os.path.abspath('../'))
|
||||
|
||||
extensions = [
|
||||
'sphinx.ext.autodoc',
|
||||
'sphinx.ext.napoleon', # Для поддержки Google-style docstrings
|
||||
]
|
||||
|
||||
|
||||
templates_path = ['_templates']
|
||||
exclude_patterns = []
|
||||
|
||||
|
||||
|
||||
# -- Options for HTML output -------------------------------------------------
|
||||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
|
||||
|
||||
html_theme = 'alabaster'
|
||||
html_static_path = ['_static']
|
21
doc/source/index.rst
Normal file
21
doc/source/index.rst
Normal file
@ -0,0 +1,21 @@
|
||||
.. Sphinx_project documentation master file, created by
|
||||
sphinx-quickstart on Fri Sep 29 02:08:39 2023.
|
||||
You can adapt this file completely to your liking, but it should at least
|
||||
contain the root `toctree` directive.
|
||||
|
||||
Welcome to Sphinx_project's documentation!
|
||||
==========================================
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
:caption: Contents:
|
||||
|
||||
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
|
@ -1,8 +0,0 @@
|
||||
from turtle import Turtle
|
||||
from controls.device import SynchronyDevice
|
||||
|
||||
class TurtleDevice(SynchronyDevice):
|
||||
pass # TODO(Homework #3)
|
||||
|
||||
|
||||
|
@ -1,35 +0,0 @@
|
||||
import cmd
|
||||
import threading
|
||||
|
||||
from queue import Queue
|
||||
|
||||
from equipment.turtle_device import TurtleDevice
|
||||
|
||||
|
||||
class TurtleDeviceThread(threading.Thread):
|
||||
# TODO(Homework 4)
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.device = TurtleDevice()
|
||||
self.queue = Queue()
|
||||
|
||||
|
||||
class NoBlockingTurtleShell(cmd.Cmd):
|
||||
intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n'
|
||||
prompt = '(turtle) '
|
||||
file = None
|
||||
|
||||
def __init__(self, turtle_thread: TurtleDeviceThread):
|
||||
pass # TODO(Homework 4)
|
||||
|
||||
def do_execute(self, arg):
|
||||
pass # TODO(Homework 4)
|
||||
|
||||
def do_exit(self, arg):
|
||||
pass # TODO(Homework 4)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
turtle_thread = TurtleDeviceThread()
|
||||
# TODO(Homework 4: Correct start thread)
|
||||
NoBlockingTurtleShell(turtle_thread).cmdloop()
|
4
requirements-dev.txt
Normal file
4
requirements-dev.txt
Normal file
@ -0,0 +1,4 @@
|
||||
# requirements-dev.txt
|
||||
sphinx==3.5
|
||||
pylint==2.9
|
||||
mypy==0.910
|
12
setup.py
Normal file
12
setup.py
Normal file
@ -0,0 +1,12 @@
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name='controls',
|
||||
version='0.1.0',
|
||||
description='My first project',
|
||||
author='Temur',
|
||||
packages=find_packages(),
|
||||
install_requires=[
|
||||
# Your dependencies go here
|
||||
],
|
||||
)
|
@ -1,12 +0,0 @@
|
||||
from unittest import TestCase
|
||||
|
||||
from controls.device import DeviceLifecycleState
|
||||
|
||||
|
||||
class DeviceLifecycleStateTest(TestCase):
|
||||
|
||||
def setUp(self) -> None:
|
||||
pass
|
||||
|
||||
def test_enum(self):
|
||||
self.assertEqual(DeviceLifecycleStateTest["INIT"], DeviceLifecycleStateTest.INIT)
|
@ -1,13 +0,0 @@
|
||||
from unittest import TestCase
|
||||
|
||||
from equipment.turtle_device import TurtleDevice
|
||||
|
||||
|
||||
class TurtleDeviceTest(TestCase):
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.device = TurtleDevice()
|
||||
|
||||
def test_open(self):
|
||||
self.device.open()
|
||||
self.device.close()
|
@ -1,74 +0,0 @@
|
||||
import cmd, sys
|
||||
from turtle import *
|
||||
|
||||
|
||||
class TurtleShell(cmd.Cmd):
|
||||
intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n'
|
||||
prompt = '(turtle) '
|
||||
file = None
|
||||
|
||||
# ----- basic turtle commands -----
|
||||
def do_forward(self, arg):
|
||||
'Move the turtle forward by the specified distance: FORWARD 10'
|
||||
forward(*parse(arg))
|
||||
def do_right(self, arg):
|
||||
'Turn turtle right by given number of degrees: RIGHT 20'
|
||||
right(*parse(arg))
|
||||
def do_left(self, arg):
|
||||
'Turn turtle left by given number of degrees: LEFT 90'
|
||||
left(*parse(arg))
|
||||
def do_goto(self, arg):
|
||||
'Move turtle to an absolute position with changing orientation. GOTO 100 200'
|
||||
goto(*parse(arg))
|
||||
def do_home(self, arg):
|
||||
'Return turtle to the home position: HOME'
|
||||
home()
|
||||
def do_circle(self, arg):
|
||||
'Draw circle with given radius an options extent and steps: CIRCLE 50'
|
||||
circle(*parse(arg))
|
||||
def do_position(self, arg):
|
||||
'Print the current turtle position: POSITION'
|
||||
print('Current position is %d %d\n' % position())
|
||||
def do_heading(self, arg):
|
||||
'Print the current turtle heading in degrees: HEADING'
|
||||
print('Current heading is %d\n' % (heading(),))
|
||||
def do_color(self, arg):
|
||||
'Set the color: COLOR BLUE'
|
||||
color(arg.lower())
|
||||
def do_undo(self, arg):
|
||||
'Undo (repeatedly) the last turtle action(s): UNDO'
|
||||
def do_reset(self, arg):
|
||||
'Clear the screen and return turtle to center: RESET'
|
||||
reset()
|
||||
def do_bye(self, arg):
|
||||
'Stop recording, close the turtle window, and exit: BYE'
|
||||
print('Thank you for using Turtle')
|
||||
self.close()
|
||||
bye()
|
||||
return True
|
||||
|
||||
# ----- record and playback -----
|
||||
def do_record(self, arg):
|
||||
'Save future commands to filename: RECORD rose.cmd'
|
||||
self.file = open(arg, 'w')
|
||||
def do_playback(self, arg):
|
||||
'Playback commands from a file: PLAYBACK rose.cmd'
|
||||
self.close()
|
||||
with open(arg) as f:
|
||||
self.cmdqueue.extend(f.read().splitlines())
|
||||
def precmd(self, line):
|
||||
line = line.lower()
|
||||
if self.file and 'playback' not in line:
|
||||
print(line, file=self.file)
|
||||
return line
|
||||
def close(self):
|
||||
if self.file:
|
||||
self.file.close()
|
||||
self.file = None
|
||||
|
||||
def parse(arg):
|
||||
'Convert a series of zero or more numbers to an argument tuple'
|
||||
return tuple(map(int, arg.split()))
|
||||
|
||||
if __name__ == '__main__':
|
||||
TurtleShell().cmdloop()
|
Loading…
Reference in New Issue
Block a user