Compare commits

..

2 Commits
main ... main

Author SHA1 Message Date
Mikhail Zelenyy
e26b8e541b For homework 4 2023-11-04 19:05:45 +03:00
Mikhail Zelenyy
fb45d7291c For homework 3 2023-10-13 22:33:07 +03:00
18 changed files with 224 additions and 229 deletions

View File

@ -1,9 +0,0 @@
MIT License
Copyright (c) [2023] [Темур]
Данное разрешение предоставляется бесплатно, любому лицу, получившему копию данного программного обеспечения и связанных с ним файлов документации (программное обеспечение), без ограничений, включая неограниченное право на использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование и/или продажу копий программного обеспечения, а также лицам, которым предоставляется данное программное обеспечение, при соблюдении следующих условий:
Указанное выше уведомление об авторском праве и данное разрешение должны быть включены во все копии или значительные части программного обеспечения.
ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ "КАК ЕСТЬ", БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ, ЯВНЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМ ПРОДАЖИ, ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОГО НАЗНАЧЕНИЯ И НЕНАРУШЕНИЯ. НИ В КОЕМ СЛУЧАЕ АВТОРЫ ИЛИ ДЕТИ АВТОРОВ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ЗА КАКИЕ-ЛИБО ПРЕТЕНЗИИ, УБЫТКИ ИЛИ ДРУГИЕ ОБЯЗАТЕЛЬСТВА, БУДЬ-ТО В РЕЗУЛЬТАТЕ ДЕЙСТВИЙ ДОГОВОРА, ДЕЛИКТА ИЛИ ИНЫХ ДЕЙСТВИЙ, В РЕЗУЛЬТАТЕ ИЛИ В СВЯЗИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ИЛИ ДРУГИМИ ДЕЛОВЫМИ ОТНОШЕНИЯМИ В ПРОГРАММНОМ ОБЕСПЕЧЕНИИ.

View File

@ -1,56 +1,2 @@
# advanced-python-homework-2023 # 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)

View File

@ -1,16 +0,0 @@
"""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.
"""

82
controls/device.py Normal file
View File

@ -0,0 +1,82 @@
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

View File

@ -1,2 +0,0 @@
def hello_world():
return "Hello, World!"

View File

@ -1,20 +0,0 @@
# 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)

View File

@ -1,21 +0,0 @@
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:

View File

@ -1,35 +0,0 @@
@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

View File

@ -1,35 +0,0 @@
# 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']

View File

@ -1,21 +0,0 @@
.. 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`

0
equipment/__init__.py Normal file
View File

View File

@ -0,0 +1,8 @@
from turtle import Turtle
from controls.device import SynchronyDevice
class TurtleDevice(SynchronyDevice):
pass # TODO(Homework #3)

View File

@ -0,0 +1,35 @@
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()

View File

@ -1,4 +0,0 @@
# requirements-dev.txt
sphinx==3.5
pylint==2.9
mypy==0.910

View File

@ -1,12 +0,0 @@
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
],
)

View File

@ -0,0 +1,12 @@
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)

View File

@ -0,0 +1,13 @@
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()

74
turtle_shell.py Normal file
View File

@ -0,0 +1,74 @@
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()